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

543    Asked by Anil Mer in Devops , Asked on Jun 29, 2021

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 {
    @Test
    public void dependencyIsNotCalled() {
        final Foo foo = new Foo(...);
        final Dependency dependency = mock(Dependency.class);
        foo.bar(dependency);
        **// verify here that someMethod was not called??**
    }
}

Answered by Anushri Singh

The best way to solve mockito verify not called that a specific method was not called using Mockito is to use the following syntax:

  import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
// ...
  verify(dependency, never()).someMethod();


Your Answer

Interviews

Parent Categories