2011-03-29 106 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知道你想的部分模擬,這樣就不會調用真正的方法。