验证方法调用而不在间谍

时间:2015-12-22 09:35:33

标签: java unit-testing junit mockito

让我们假设以下测试

public void someTest() throws Exception {
   Foo foo = spy(new Foo());
   foo.someMethod(); // invokes methodToBeVerified()
   verify(foo).methodToBeVerified();
}

当测试执行时,它会调用foo.methodToBeVerified()的实际实现。我想测试验证是否已调用该特定方法但是我不希望它的实现被执行。是否可以使用Mockito的间谍来做到这一点?

1 个答案:

答案 0 :(得分:1)

是的,使用

doNothing().when(foo).methodToBeVerified();

如以下示例

public class FooTest {

    static class Foo {

        public void someMethod() {
            System.out.println("someMethod called");
            System.out.println("calling method to be verified...");
            methodToBeVerified();
        }

        public void methodToBeVerified() {
            System.out.println("methodToBeVerified called");
        }
    }

    @Test
    public void someTest() throws Exception {
        Foo foo = spy(new Foo());
        doNothing().when(foo).methodToBeVerified();
        foo.someMethod();
        verify(foo).methodToBeVerified();
    }

}

作为参考,您要找的是 Partial Mocks 。自1.8.0以来,Mockito支持Real (spied) partial mocks