Java Mockito中的嵌套mocking

Java Mockito中的嵌套mocking,java,unit-testing,mockito,Java,Unit Testing,Mockito,我有一个Mockito代码: interface Dao { public void doSomething(); } class LegacyClass { Dao dao; public String legacyMethod() { dao.doSomething(); return "Test"; } } public class MockitoTest { public static void main(St

我有一个Mockito代码:

interface Dao {
    public void doSomething();
}

class LegacyClass {
    Dao dao;

    public String legacyMethod() {
        dao.doSomething();
        return "Test";
    }
}

public class MockitoTest {
    public static void main(String[] args) {
        Dao dao = mock(Dao.class);
        LegacyClass legacyInst = new LegacyClass();
        legacyInst.dao = dao;
        LegacyClass legacy = spy(legacyInst);

        when(legacy.legacyMethod()).thenReturn("Replacement");
    }
}
最后一个
when()
抛出以下异常:

Exception in thread "main" org.mockito.exceptions.base.MockitoException: 
'doSomething' is a *void method* and it *cannot* be stubbed with a *return value*!
Voids are usually stubbed with Throwables:
    doThrow(exception).when(mock).someVoidMethod();
If the method you are trying to stub is *overloaded* then make sure you are calling the right overloaded version.
    at mypkg.MockitoTest.main(MockitoTest.java:28)
然而,我不是在模拟
Dao.doSomething
的返回值,而是在模拟
LegacyClass.legacyMethod()
的返回值

这是预期的行为吗?有没有Mockito文档声明您不能像这样嵌套Mock


我怎么能走这条路呢?

间谍不是这样工作的。在示例代码中,实际调用的方法
legacy.legacyMethod()
,是因为它是一个间谍而不是一个模拟(然后调用
dao.doSomething()
),这就是为什么会出现此错误

如果要进行部分模拟,必须将其写成:

doReturn("Replacement").when(legacy).legacyMethod();
这样Mockito就会知道您想要进行部分模拟,所以它不会调用真正的方法