I am experimenting with converting some of my unit tests from using JMock to using Mockito and have hit a few stumbling blocks.
Firstly in my tests when using JMock the verification and returning of the stub happen in one step as follows
contextMockery.checking(new Expectations() {{
oneOf(dateUtilityService).isBeforeToday(URGENT_DATE);
will(returnValue(true));
}});
This essentially verifies that the method is being called and returns a canned value at the same time. The test fails if isBeforeToday method is NOT called and returns my canned value of true at the same time. Whereas when using Mockito I have to verify that the method is being called and then return my canned value in separate steps which are pretty much a duplicate as follows:
doReturn(true).when(dateUtilityService).isBeforeToday(URGENT_DATE);
verify(dateUtilityService).isBeforeToday(URGENT_DATE);
Is there no way to do this in one step?
Secondly, if I forget to list a method call to one of my mocks in my expectations, JMock fails the test with "Unexpected invocation exception" which in my opinion is correct whereas Mockito will happily pass the test unless I explicitly verify that a method call to the mock must never happen, is this correct (seems wrong)? Is there a way to tell mockito to fail the test if unexpected method calls are made to my mocked out dependencies?
1.
When you stub a method call the verify method is usually not necessary - you should check the action based on the return value (in your case something might happen or something will be returned when the dateUtilityService returns true - check that instead of verifying interaction with a mock.
Mockito documentation also talks about this. http://site.mockito.org/mockito/docs/current/org/mockito/Mockito.html#2
2.
This actually leads to fragile tests and is not recommended way of doing things with mockito. That's why there is no way to set this behaviour.
See http://site.mockito.org/mockito/docs/current/org/mockito/Mockito.html#8
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