Mockito Verify With Examples

Mockito Verify methods are used to check that certain behavior happened. We can use Mockito verify methods at the end of the testing method code to make sure that specified methods are called.

Mockito Verify

  • 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. If any method verification is still left, it will fail and provide proper message.
  • verifyZeroInteractions() behavior is same as verifyNoMoreInteractions() method.
  • We can use inOrder() method to verify the order of method invocation. We can skip a method invocation but the methods being verified must be in the same order.

Let’s look at some of the mockito verify method examples.

Mockito verify() simple example

Above verify method will pass if add("Pankaj") is called only once on the mocked list object.

It’s the same as calling with times(1) argument with verify method.

If we want to make sure a method is called but we don’t care about the argument, then we can use ArgumentMatchers with verify method.

Note that org.mockito.Mockito class provides static methods for most of the useful methods in the Mockito framework, this helps us in writing fluent code by importing them using import static.

Mockito verify with number of times

Mockito verify() method is overloaded, the second one is verify(T mock, VerificationMode mode). We can use it to verify for the invocation count.

verifyNoMoreInteractions()

This method can be used after all the verify methods to make sure that all the interactions are verified. It will fail the test if there are any unverified interactions on the mocked object.

The second invocation of verifyNoMoreInteractions() will fail with the error message as:

One of the great features of Mockito is the exception message, it clearly points out where our test is failing so that we can easily fix it.

verifyZeroInteractions()

verifyZeroInteractions() method behavior is same as verifyNoMoreInteractions() method.

Mockito verify only method call

If we want to verify that only one method is being called, then we can use only() with verify method.

Mockito Verify Order of Invocation

We can use InOrder to verify the order of invocation. We can skip any method to verify, but the methods being verified must be invoked in the same order.

Summary

Mockito verify() methods can be used to make sure the mock object methods are being called. If any method call is deleted by mistake, then verify method will throw an error.

By admin

Leave a Reply

%d bloggers like this: