Reputation: 633
I have some pretty simple code as shown below.
@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);
}
The above code seems to record the 'when' call as the first call to the 'start' & hence the first 'verify' fails. The code works only when I uncomment the call to 'reset'. I am using Mockito 2.1.0 on Windows, with Java 1.8.
Upvotes: 1
Views: 217
Reputation: 8057
Indeed, in the line when(spyVehicle.start(true)).thenReturn("Sure");
you call start
.
There are several ways to avoid this.
One of them is use doReturn
:
doReturn("Sure").when(spyVehicle).start(eq(true));
Notice, that here we are are doing stubbing and not calling the method.
Upvotes: 2