3 回答

TA貢獻1775條經驗 獲得超8個贊
如果您使用間諜對象(標有@Spy)而不是模擬對象(標有),則兩種方法的行為會有所不同@Mock:
when(...) thenReturn(...) 在返回指定值之前進行真正的方法調用。因此,如果被調用的方法引發Exception,則必須對其進行處理/模擬。等等。當然,您仍然可以獲得結果(在中定義thenReturn(...))
doReturn(...) when(...) 根本不調用該方法。
例:
public class MyClass {
protected String methodToBeTested() {
return anotherMethodInClass();
}
protected String anotherMethodInClass() {
throw new NullPointerException();
}
}
測試:
@Spy
private MyClass myClass;
// ...
// would work fine
doReturn("test").when(myClass).anotherMethodInClass();
// would throw a NullPointerException
when(myClass.anotherMethodInClass()).thenReturn("test");
添加回答
舉報