How can you use Mockito to verify that a specific method was not called on an object's dependency?

How can you use Mockito to verify that a specific method was not called on an object’s dependency?

Hi,

This sounds more meaningful:

import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;

// ...

verify(dependency, never()).someMethod();

For detailed information on verifying method invocations, refer to section - Verifying exact number of invocations / at least x / never

The specific details about the never() verification can be found here: https://static.javadoc.io/org.mockito/mockito-core/2.7.21/org/mockito/Mockito.html#never_verification

Here are a few options based on your use case:

To verify that someMethod is not invoked on dependency, you can use:

verify(dependency, times(0)).someMethod();

or, for better readability:

verify(dependency, never()).someMethod();

To ensure no interactions occur on a specific dependency, use:

verifyNoInteractions(dependency);

If you want to verify that only the expected method is invoked and no other methods are called on dependency, use:

verify(dependency, times(1)).someMethod();
verifyNoMoreInteractions(dependency);

As a general practice, I use an @After block in my tests:

@After
public void after() {
    verifyNoMoreInteractions(<your mock1>, <your mock2>, ...);
}

This approach allows the test to focus solely on verifying expected interactions. I often forget to check for “no interactions,” only to later find unexpected calls that shouldn’t have been made. This pattern helps catch any unverified calls and ensures that only the intended interactions are present.