Java verify void method calls n times with Mockito
Identifying the number of times a void method is called with Mockito is as simple as:
You only need to replace mockObject
with your mock instance, n
with the expected invocation count, and voidMethodToCheck
with the method you want to confirm was called n
times.
Verification modes in Mockito
Verifying single calls
If you're confident your method is called only once, try using this neat trick:
Zero interaction verification
Ensure a method is never invoked with:
Verifying call frequency
You can verify a method has been invoked at least X or at most Y times:
These tools make it easy to test for a range of acceptable method calls without needing to know an exact number.
Digging deeper into verification tools
Parameter verification
In reality, a method call count isn't always enough, sometimes we need to check if the right arguments were passed:
Order of calls
To establish the right sequence of method calls:
Resetting mocks
Sometimes you want to begin afresh with your mock:
But caution! This can lead to dropped data and fragile tests.
Matching arguments while verifying
Mockito matches exact arguments, if you want partial matching use ArgumentMatchers:
Was this article helpful?