在Mockito中打樁(即stub)有兩種方法when(...).thenReturn(...)和doReturn(...).when(...)。這兩個方法在大部分情況下都是可以相互替換的,但是在使用了Spies對象(@Spy注解),而不是mock對象(@Mock注解)的情況下他們調用的結果是不相同的(目前我只知道這一種情況,可能還有別的情形下是不能相互替換的)。
● when(...) thenReturn(...)會調用真實的方法,如果你不想調用真實的方法而是想要mock的話,就不要使用這個方法。
● doReturn(...) when(...) 不會調用真實方法
下面我寫一個簡單的單元測試來驗證一下。
1.被測試類
public class Myclass { public String methodToBeTested(){ return function(); } public String function(){ throw new NullPointerException(); } }
2.單元測試
@RunWith(MockitoJUnitRunner.class) public class MyclassTest { @Spy private Myclass myclass; @Test public void test(){ // when(myclass.methodToBeTested()).thenReturn("when(...)thenReturn(...)"); doReturn("doReturn(...)when(...)").when(myclass).methodToBeTested(); String str = myclass.methodToBeTested(); System.out.println(str); } }
測試結果
1.使用when(...).thenReturn(...),拋出了異常。
2.doReturn(...).when(...),測試通過