2013-10-01 32 views
2

我有一個類,在那裏我想模擬某些方法的類和測試其他人。這是我唯一可以證明並確定它正在工作的方法。現在mockito,間諜 - 不知道它是如何完成部分嘲諷

class UnderTest{ 
    public void methodToTest(){ 
    methodToCall1() 
    methodToCall2() 
    } 


    public void methodToCall1(){ 
    } 

    public void methodToCall2(){ 
    } 

} 

,因爲我想測試的第一方法中,我想創建UnderTest的部分模擬,所以我可以驗證這兩個方法被稱爲。 我如何在Mockito中實現這一點?

感謝您的幫助!

回答

5

你提到你想要做的兩件事情:
1. Create real partial mocks
2. Verify method invocations

但是,因爲你的目標是驗證methodToCall1()methodToCall2()實際上調用,所有你需要做的是spy on the real object。這可以用下面的代碼塊來完成:

//Spy UnderTest and call methodToTest() 
    UnderTest mUnderTest = new UnderTest(); 
    UnderTest spyUnderTest = Spy(mUnderTest); 
    spyUnderTest.methodToTest(); 

    //Verify methodToCall1() and methodToCall2() were invoked 
    verify(spyUnderTest).methodToCall1(); 
    verify(spyUnderTest).methodToCall2(); 

如果不調用的方法之一,例如methodToCall1,一個將引發異常:

Exception in thread "main" Wanted but not invoked: 
    undertest.methodToCall1(); 
    ... 
2
package foo; 

import static org.mockito.Mockito.verify; 

import org.junit.Test; 
import org.junit.runner.RunWith; 
import org.mockito.Spy; 
import org.mockito.runners.MockitoJUnitRunner; 

@RunWith(MockitoJUnitRunner.class) 
public class FooTest { 

    @Spy 
    private UnderTest underTest; 

    @Test 
    public void whenMethodToTestExecutedThenMethods1And2AreCalled() { 
     // Act 
     underTest.methodToTest(); 

     // Assert 
     verify(underTest).methodToCall1(); 
     verify(underTest).methodToCall2(); 
    } 

}