如何验证没有使用 Mockito 调用特定方法?

2022-01-14 00:00:00 unit-testing tdd mockito java junit

如何验证方法是否没有在对象的依赖项上调用?

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

例如:

public interface Dependency {
    void someMethod();
}

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

通过 Foo 测试:

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??**
    }
}

推荐答案

更有意义:

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

// ...

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

这里有这个功能的文档 §4 "验证调用的确切数量/至少 x/never",并且 never javadoc 是 这里.

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

相关文章