Search code examples
javaunit-testingjunitmockito

Mockito - check if NO method was called on an object(object was not accessed)


I want to write a test that passes a mock object A into an object under test B and checks if ANY of the methods of A were called. To give some context, class B is designed to manipulate A in a specific way, based on a set of parameters, and under certain conditions it shouldn't do anything to it at all. So my goal is to test that scenario. I know how to test whether a specific method was called or not:

verify(A, never()).myMethod();

But I can't find a way to make sure that NONE of the methods A has were called. Is there a way to do this?


Solution

  • I believe that verifyNoInteractions might be what you're looking for. In your case you'd call Mockito.verifyNoInteractions(A).

    public static void verifyNoInteractions(java.lang.Object... mocks)

    Verifies that no interactions happened on given mocks. 
    

    https://www.javadoc.io/doc/org.mockito/mockito-core/latest/org/mockito/Mockito.html#verifyNoInteractions-java.lang.Object...-