2 回答

TA貢獻1830條經驗 獲得超9個贊
調用的時候when(spyClass.functionB(any(),any()).thenReturn(mockString)確實會走debug模式下的real方法。但是這個方法被嘲笑了,你functionA得到了mockString. 它確實有效。我真的不明白為什么看到你可以進入調試模式是一個問題。
要回答這個問題,使用mock不會通過該方法:
Class mockClass = mock(Class.class);
when(mockClass.functionB(any(),any())).thenReturn(mockString);
when(mockClass.functionA(arguments)).thenCallRealMethod();
mockClass.functionA(arguments);
但是:這是一個非常糟糕的測試,你永遠不需要這樣做(間諜或模擬)。如果您測試一個類,那么您將測試所有類。 如果您需要模擬一個方法來測試另一個方法,那么其中一個方法可能屬于另一個類。

TA貢獻1799條經驗 獲得超9個贊
或者在測試類的情況下。ClassA 有一個在 methodB() 內部調用的 methodA() 并且您對 methodB() 內部發生的所有事情都不感興趣,那么您可以簡單地對代表當前被測類的對象使用間諜,然后設置 methodB 的自定義行為() 用于例如。Mockito.doNothing().when() + @Spy。
@InjectMocks
@Spy
private ClassA testObj;
@BeforeEach
public void setUp() {
super.setUp();
// the actual call of the methodB() will be totally ignored
doNothing().when(testObj).methodB(input);
}
@Test
public void methodTest() {}
添加回答
舉報