How to verify that a specific method was not called using Mockito?

How to verify that a method is not called on an object's dependency?

For example:

public interface Dependency {
    void someMethod();

public class Foo {
    public bar(final Dependency d) {

With the Foo test:

public class FooTest {
    public void dependencyIsNotCalled() {
        final Foo foo = new Foo(...);
        final Dependency dependency = mock(Dependency.class);;
        **// verify here that someMethod was not called??**


Even more meaningful :

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

// ...

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

The documentation of this feature is there ยง4 "Verifying exact number of invocations / at least x / never", and the never javadoc is here.

use the second argument on the Mockito.verify method, as in:

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

As a more general pattern to follow, I tend to use an @After block in the test:

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

Then the test is free to verify only what should be called.

Also, I found that I often forgot to check for "no interactions", only to later discover that things were being called that shouldn't have been.

So I find this pattern useful for catching all unexpected calls that haven't specifically been verified.

Both the verifyNoMoreInteractions() and verifyZeroInteracions() method internally have the same implementation as:

public static transient void verifyNoMoreInteractions(Object mocks[])

public static transient void verifyZeroInteractions(Object mocks[])

so we can use any one of them on mock object or array of mock objects to check that no methods have been called using mock objects.

Need Your Help

Free memory allocated in a different function?

c pointers memory-management malloc free

I'm trying to learn C and I'm currently trying to write a basic stack data structure, but I can't seem to get basic malloc/free right.

Returning anonymous types with Web API

c# json

When using MVC, returning adhoc Json was easy.