[英]Mockito - Spy bug - recording a when as an Invocation
我有一些非常簡單的代碼,如下所示。
@Test
public void bugInInvokingASpyAndVerification() throws ColdDayException {
//given
Engine en = new Engine();
Engine spyEngine = spy(en);
Vehicle realDeal = new Vehicle(new Wheel(), spyEngine, new Brake());
Vehicle spyVehicle = spy(realDeal);
//When part - set-up stubs
when(spyVehicle.start(true)).thenReturn("Sure");
//Mockito.reset(spyVehicle);
//then part - actual calls + verifications
String x = spyVehicle.start(true);
assertEquals(x, "Sure");
verify(spyVehicle, times(1)).start(true);
verify(spyEngine, atLeastOnce()).startEngine(true);
verify(spyEngine, times(1)).startEngine(true);
}
上面的代碼似乎將“ when”調用記錄為“ start”的第一個調用,因此第一個“ verify”失敗。 該代碼僅在我取消對“重置”的調用的注釋時有效。 我在Windows和Java 1.8上使用Mockito 2.1.0。
確實,在when(spyVehicle.start(true)).thenReturn("Sure");
你叫start
。 有幾種方法可以避免這種情況。
其中之一是使用doReturn
:
doReturn("Sure").when(spyVehicle).start(eq(true));
注意,這里我們正在執行存根,而不是調用該方法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.