I want to assert that a method is called exactly one time. I'm using RhinoMocks 3.5.
Here's what I thought would work:
[Test] public void just_once() { var key = "id_of_something"; var source = MockRepository.GenerateStub<ISomeDataSource>(); source.Expect(x => x.GetSomethingThatTakesALotOfResources(key)) .Return(new Something()) .Repeat.Once(); var client = new Client(soure); // the first call I expect the client to use the source client.GetMeMyThing(key); // the second call the result should be cached // and source is not used client.GetMeMyThing(key); } I want this test to fail if the second invocation of GetMeMyThing() calls source.GetSomethingThatTakesALotOfResources().
Mockito verify only method call If we want to verify that only one method is being called, then we can use only() with verify method.
AtLeastOnce - Specifies that a mocked method should be invoked one time as minimum. AtMost - Specifies that a mocked method should be invoked times time as maximum. AtMostOnce - Specifies that a mocked method should be invoked one time as maximum.
Using the verify() Method Whenever we mock a void method, we do not expect a return value. That is why we can only verify whether that method is being called or not. Features of verify() : Mockito provides us with a verify() method that lets us verify whether the mock void method is being called or not.
While you can replace it with blank == true , which will work fine, it's unnecessary to use the == operator at all. Instead, use if (blank) to check if it is true, and if (! blank) to check if it is false.
Here's how I'd verify a method is called once.
[Test] public void just_once() { // Arrange (Important to GenerateMock not GenerateStub) var a = MockRepository.GenerateMock<ISomeDataSource>(); a.Expect(x => x.GetSomethingThatTakesALotOfResources()).Return(new Something()).Repeat.Once(); // Act // First invocation should call GetSomethingThatTakesALotOfResources a.GetMeMyThing(); // Second invocation should return cached result a.GetMeMyThing(); // Assert a.VerifyAllExpectations(); }
I have been using the AssertWasCalled extension to get around this problem. This is the best I could find/come up with but it would be better if I didn't have to specify the call twice.
[Test] public void just_once() { var key = "id_of_something"; var source = MockRepository.GenerateStub<ISomeDataSource>(); // set a positive expectation source.Expect(x => x.GetSomethingThatTakesALotOfResources(key)) .Return(new Something()) .Repeat.Once(); var client = new Client(soure); client.GetMeMyThing(key); client.GetMeMyThing(key); source.AssertWasCalled(x => x.GetSomethingThatTakesALotOfResources(key), x => x.Repeat.Once()); source.VerifyAllExpectations(); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With