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?
Verify in Mockito simply means that you want to check if a certain method of a mock object has been called by specific number of times. When doing verification that a method was called exactly once, then we use: ? If the method was called multiple times, and you want to verify that it was called for specific times, lets say 3 times, then we use: ?
Mockito verify () method can be used to test number of method invocations too. We can test exact number of times, at least once, at least, at most number of invocation times for a mocked method. We can use verifyNoMoreInteractions () after all the verify () method calls to make sure everything is verified.
We can use assertEquals (expected, result) to verify that expected multiple arguments match with the retrieved values from ArgumentCaptor. Drop me your questions related to invoking a method multiple times and verify it’s method different arguments values in mockito based unit tests.
If the verified method called 2+ times, mockito passes all the called combinations to each verifier. So mockito expects your verifier silently returns true for one of the argument set, and false (no assert exceptions) for other valid calls. That expectation is not a problem for 1 method call-it should just return true 1 time.
Mockito verifies argument values in natural java style: by using an equals() method. This is also the recommended way of matching arguments because it makes tests clean & simple.
ArgumentCaptor<Data> argument = ArgumentCaptor.forClass(Data.class);
verify(service).operate(argument.capture());
assertEquals("John", argument.getValue().getDataName());
more refer here
I hope this will be helpful
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