Explain Codes LogoExplain Codes Logo

Java verify void method calls n times with Mockito

java
mockito
testing
verification
Anton ShumikhinbyAnton Shumikhin·Feb 27, 2025
TLDR

Identifying the number of times a void method is called with Mockito is as simple as:

// Mate, you've just entered the Matrix! verify(mockObject, times(n)).voidMethodToCheck();

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:

// Invoke this once is a programmer's equivalent of "Take it easy!" verify(mockObject).voidMethodToCheck();

Zero interaction verification

Ensure a method is never invoked with:

// No calls, no drama! verify(mockObject, never()).voidMethodToCheck();

Verifying call frequency

You can verify a method has been invoked at least X or at most Y times:

// John called Mary at least X times, I hope she is not getting annoyed verify(mockObject, atLeast(x)).voidMethodToCheck(); // But, at most Y times, because John respects Mary's space verify(mockObject, atMost(y)).voidMethodToCheck();

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:

// This is like checking if the right pizza toppings were added verify(mockObject, times(n)).voidMethodToCheck("expectedParam");

Order of calls

To establish the right sequence of method calls:

// This is like following the right steps to brew that perfect cup of coffee InOrder inOrder = inOrder(mockObject); inOrder.verify(mockObject).firstMethod(); inOrder.verify(mockObject).voidMethodToCheck();

Resetting mocks

Sometimes you want to begin afresh with your mock:

// Workers aren't the only ones that need a coffee break, mocks do too! reset(mockObject); // Now your mock is fresh and ready for further testing

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:

// Imagine telling a kid to pick up any toy from a toy store. verify(mockObject, times(n)).voidMethodToCheck(anyString());