Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rhino Mocks: Repeat.Once() not working?

Tags:

rhino-mocks

Can anyone tell me why in the world the following test is not failing?

[Test]
public void uhh_what() {
    var a = MockRepository.GenerateMock<IPrebuiltNotifier>();
    a.Expect(x => x.Notify()).Repeat.Once();
    a.Notify();
    a.Notify();
    a.VerifyAllExpectations();
}

Really need a second pair of eyes to confirm I'm not crazy...now I'm worried that all my tests are unreliable.

like image 444
George Mauer Avatar asked May 20 '09 10:05

George Mauer


2 Answers

There is already a thread on the RhinoMocks group.

GenerateMock creates a dynamic mock. The dynamic mock allows calls that are not specified (=expected). If this happens, it just returns null (or the default value of the return type).

Note: Repeat is a specification of the behaviour (like Stub), not the expectation even if specified in an expectation.

If you want to avoid having more then a certain number of calls, you could write:

[Test]
public void uhh_what() 
{
    var a = MockRepository.GenerateMock<IPrebuiltNotifier>();
    a.Expect(x => x.Notify()).Repeat.Once();
    a.Stub(x => x.Notify()).Throw(new InvalidOperationException("gotcha"));
    a.Notify();

    // this fails
    a.Notify();

    a.VerifyAllExpectations();
}

Or

[Test]
public void uhh_what() 
{
    var a = MockRepository.GenerateMock<IPrebuiltNotifier>();
    a.Notify();
    a.Notify();

    // this fails
    a.AssertWasCalled(
      x => x.Notify(), 
      o => o.Repeat.Once());
}
like image 140
Stefan Steinegger Avatar answered Nov 18 '22 19:11

Stefan Steinegger


When using GenerateMock (or with Dynamic Mocks in general) I always mentally insert the following:

a.Expect(x => x.Notify()).Repeat.*[AtLeast]*Once();

like image 45
Sam Shiles Avatar answered Nov 18 '22 20:11

Sam Shiles