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

2021-6-3 anglehua

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:

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


Powered by emlog 京ICP备15036472号-3 sitemap