Mockito verify — How to test method invocations

Sachithra Dangalla
1 min readDec 4, 2020

Mockito verify is an impressive tool used in testing and there are various functionalities that would allow a developer to test method invocations.

Test number of invocations of a method

verify(mockedObject, times(1)).someMethod(); would test if someMethod() was called exactly 1 time.

verify(mockedObject, never()).someMethod(); would test if someMethod() was never called.

Test order of invocation

InOrder inOrder = Mockito.inOrder(mockedObject);        inOrder.verify(mockedObject).firstMethod();        inOrder.verify(mockedObject).secondMethod();

The above would verify that the firstMethod() was called before the secondMethod()

Test minimum/maximum number of invocations

verify(mockedObject, atLeast(2)).someMethod; would test if someMethod() was called at least 2 times.

verify(mockedObject, atMost(5)).someMethod(); would test if someMethod() was called not more than 5 times.

Test no interactions were made with the test object

verifyNoMoreInteractions(mockedObject); can be used to test if none of the methods of mockedObject were called.

Complete example

For this article, I will be using a sample Animal.java class with simple sample methods. The ParrotTest.java test class is testing an instance of a parrot. The methods to be tested are nested methods (which do not work on mocks directly) andverify works on mocked instances, therefore I have used spy to mock a solid animal instance.

--

--