2011-03-29 93 views
0

我有这样的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(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文档说明你不能像这样嵌套嘲笑?

我该如何解决这个问题?

回答

2

间谍不这样工作。在你的示例代码中,真正的方法legacy.legacyMethod()实际上被称为是因为它是一个间谍不是模拟(然后调用dao.doSomething()),这就是为什么你得到这个错误。

如果你想使一个部分模拟,你必须写为:

doReturn("Replacement").when(legacy).legacyMethod(); 

这样会的Mockito知道你想的部分模拟,这样就不会调用真正的方法。