When using mocks for unit testing, I often encounter the need to check whether a certain method of the mock is invoked with proper arguments. This means that I have to somehow find a way to peek into what gets passed to the method in question. In Spock this can be done using something like:
1 * serviceMock.operate(*_) >> { args ->
def argument = args[0]
assert expectedValue = argument.actualValue
}
With Mockito (and JUnit), the only way I think this can be done is by using doAnswer
and verify
, something like:
doAnswer(new Answer() {
//check arguments here
}).when(service).operate(any(Data.class));
Then I have to verify that the operation actually gets called with:
verify(service).operate(any(Data.class));
The code above, however, interferes with doAnswer
as if it's an actual call to the method in question. How do I work around this so that I can both verify that the method is called, and verify that the arguments it gets are correct?