java – How to check in Mockito that a method has not been called?

Question:

To verify that a method has been called we call verify(mock).method() . And how to check the opposite, that the method was not called?

Answer:

Using the verify method in verify (from the documentation ):

LinkedList mockedList = mock(LinkedList.class);
mockedList.add("once");

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

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

To make sure the method was called once

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

or

verify(mockedList, times(1)).add("once");

Both options are identical because:

public static <T> T verify(T mock) {
    return MOCKITO_CORE.verify(mock, times(1));
}

The options for your case are:

verify(mockedList, times(0)).add("never happened");
verify(mockedList, never()).add("never happened");

Scroll to Top