如何验证是否未使用Mockito调用特定方法?

2022-08-31 04:04:00

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

例如:

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

答案 1

更有意义的是:

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

// ...

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

这个特性的文档有§4“验证确切的调用次数/至少x/从不”,javadoc在这里never


答案 2

对方法使用第二个参数,如:Mockito.verify

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

推荐