'Is there an equivalent of verifyZeroInteractions() for verifying an exact number of interaction with a mock object?

I would like to verify there were exactly x interactions with might db mock object. Is there something similar to the 'verifyZeroInteractions()' method for doing so?



Solution 1:[1]

Mockito.verify(MOCKED_OBJ, Mockito.times(number)).YOUR_METHOD_CALL();

Mockito.verify(MOCKED_OBJ, Mockito.atLeast(number)).YOUR_METHOD_CALL();

More information is here

Solution 2:[2]

You can use

verifyNoInteractions()

Exactly same behaviour as verifyZeroInteractions()

Solution 3:[3]

According to mockito doc u can use verify(mockedList, never()).add("never happened");.

There are a lot of useful combinitions to check your expected behaviour. Other example from Mockito doc:

//using mock
mockedList.add("once");

mockedList.add("twice");
mockedList.add("twice");

mockedList.add("three times");
mockedList.add("three times");
mockedList.add("three times");

//following two verifications work exactly the same - times(1) is used by default
verify(mockedList).add("once");
verify(mockedList, times(1)).add("once");

//exact number of invocations verification
verify(mockedList, times(2)).add("twice");
verify(mockedList, times(3)).add("three times");

//verification using never(). never() is an alias to times(0)
verify(mockedList, never()).add("never happened");

//verification using atLeast()/atMost()
verify(mockedList, atLeastOnce()).add("three times");
verify(mockedList, atLeast(2)).add("three times");
verify(mockedList, atMost(5)).add("three times");

Or you can use verifyNoMoreInteractions to ensure no other interaction with you mock.

//using mocks
mockedList.add("one");
mockedList.add("two");

verify(mockedList).add("one");

//following verification will fail
verifyNoMoreInteractions(mockedList);

In addtion you can use inOrder to verify interactions of multiple mocks in exact same order and add verifyNoMoreInteractions() to ensure that there is no other interactions as defined with your mocks.

InOrder inOrder = inOrder(firstMock, secondMock);
inOrder.verify(firstMock).add("was called first");
inOrder.verify(secondMock).add("was called second");
inOrder.verifyNoMoreInteractions();

Check the Mockito doc fo feel the full power of mockito: https://static.javadoc.io/org.mockito/mockito-core/2.27.0/org/mockito/Mockito.html

See also https://static.javadoc.io/org.mockito/mockito-core/2.27.0/org/mockito/Mockito.html#4 https://static.javadoc.io/org.mockito/mockito-core/2.27.0/org/mockito/Mockito.html#8

Solution 4:[4]

You can use Mockito.verify() method passing Mockito.times(...) or Mockito.atLeast(..) as an argument.

Solution 5:[5]

Or even more elegant

verify(MOCK, never()).method()

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 atti
Solution 2 Shubham Kumar
Solution 3 Sma Ma
Solution 4 KnotGillCup
Solution 5 Ioan M