omer
omer

Reputation: 1442

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?

Upvotes: 9

Views: 10875

Answers (5)

Shubham Kumar
Shubham Kumar

Reputation: 181

You can use

verifyNoInteractions()

Exactly same behaviour as verifyZeroInteractions()

Upvotes: 18

Sma Ma
Sma Ma

Reputation: 3715

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

Upvotes: 3

Ioan M
Ioan M

Reputation: 1207

Or even more elegant

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

Upvotes: 1

atti
atti

Reputation: 180

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

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

More information is here

Upvotes: 5

KnotGillCup
KnotGillCup

Reputation: 175

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

Upvotes: 1

Related Questions