In the previous steps, we used Mockito to mock or stub method behaviors. For instance, we told Mockito:
- “When this method is called, return this value.”
- “When this method is called with this argument, return that value.”
- “Use argument matchers to return something for any value.”
These are called stubbing behaviors.
However, stubbing alone is not sufficient for comprehensive unit testing. In real-world scenarios, we also need to verify interactions — i.e., whether certain methods were called and whether they were called with the correct arguments.
Why Verification?
Consider a method calculateSum()
that uses a DataService
. If it returns the sum directly, mocking is enough. But suppose instead of returning the result, it calls another method like dataService.storeSum(sum)
.
In such cases, we cannot check the result via return value alone. We must verify that storeSum()
was called, and that it was called with the correct sum.
That’s where Mockito verification comes in.
Example: Basic Verification
@Test void verificationBasics() { List<String> mock = mock(List.class); // Simulating some code that calls mock.get(0) String value = mock.get(0); // Verifying that get(0) was called verify(mock).get(0); }
This test will succeed if mock.get(0)
is called exactly once.
Using Argument Matchers
verify(mock).get(anyInt());
This verifies that get()
was called with any integer.
Verifying Number of Invocations
Mockito provides the times()
method to verify the exact number of method calls:
verify(mock, times(1)).get(0); // called exactly once verify(mock, times(2)).get(anyInt()); // called twice with any integer
Verifying With Multiple Calls
mock.get(0); mock.get(1); verify(mock, times(2)).get(anyInt()); // OK verify(mock, times(1)).get(0); // OK verify(mock, times(1)).get(1); // OK
At Least / At Most Verifications
verify(mock, atLeastOnce()).get(anyInt()); // called at least once verify(mock, atLeast(2)).get(anyInt()); // at least twice verify(mock, atMost(2)).get(anyInt()); // at most twice
These allow for more flexible verifications.
Verifying That a Method Was Never Called
verify(mock, never()).get(2); // get(2) was never called
This is useful to assert that certain interactions did not happen.