Dakotah North
Dakotah North

Reputation: 1344

Ensure non-mocked methods are not called in mockito

In the following example:

   Execution execution = mock(Execution.class);
   when(execution.getLastQty()).thenReturn(1000.0);
   when(execution.getLastPrice()).thenReturn(75.0);

   order.onFillReceived(execution);

   assertEquals(0, order.getLeavesQty(), 0);

Execution has many other methods that should not be called. Only the two methods that have been mocked should be used within this test and should be called. If any other methods are called, then the test should fail.

How to I tell Mockito to fail if any other methods are called?

Upvotes: 6

Views: 5601

Answers (2)

Usman Ismail
Usman Ismail

Reputation: 18689

You could try the never method if that fits the use case:

i.e.

verify(execution, never()).someOtherMethod();

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1503839

The documentation covers this explicitly. You want to call verifyNoMoreInteractions, either after calling verify (as per the docs) or

verify(execution).getLastQty();
verify(execution).getLastPrice();
verifyNoMoreInteractions(execution);

or using ignoreStubs:

verifyNoMoreInteractions(ignoreStubs(execution));

Upvotes: 9

Related Questions