Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 789
user465342 Avatar asked Jan 24 '12 07:01

user465342


People also ask

How do you know if a mock method is called?

To check if a method was called on a mocked object you can use the Mockito. verify method: Mockito. verify(someMock).

Which method in Mockito verifies that no interaction has happened with a mock in Java?

Mockito verifyZeroInteractions() method It verifies that no interaction has occurred on the given mocks. It also detects the invocations that have occurred before the test method, for example, in setup(), @Before method or the constructor.

What is never () in Mockito?

It's a VerificationMode object. That object is used to verify that a certain action occurred a number of times. But that number could be 0. And that's what Mockito. never() is checking.


1 Answers

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));
like image 115
Jon Skeet Avatar answered Oct 07 '22 01:10

Jon Skeet