I have a code with a condition inside that does nothing in some condition as follows. I would like to test that particular scenario.
Code under test, the return statement:
public void someTask(){
if(somecondition){
return;
}else if(){
//more work to do
}
}
I have tried but failed so far using the following:
@Test
public void testSomeTask(){
when(mock.somecondition()).thenReturn(true);
mock.someTask();
verifyNoMoreInteractions(mock); //fails
verifyZeroInteractions(mock); //fails this calls the above method anyway
}
UPDATE: The condition and the method under test belong to the same class. I am spying that class instead of mocking but the result is the same. The error I am getting is No Interactions wanted here, points to my verifyNoMoreInteractions line. But found this interaction on mock, points to the above call. I will change the arguments and force it to point to my line and give updates later.I think I see what's wrong in my test.
SOLUTION: Verify the method call and all other call that will be invoked as a result of the method under test parameters and the verify the condition itself. Then verifyNomoreINteractions at the end. Unfortunately,there is no way to verify that there is nothing is to be invoked as a result of return; statement as of this version of Mockito. It would be handy to have something like verifyNothingIsDone kind of tool, just like doNothing().when(.....);
It seems like you're trying to test the implementation of a mocked instance.
Instead you should use spy
and only mock somecondition()
.
Then you need to verify the actual interactions.
verify(spy).someTask();
verify(spy).somecondition();
verifyNoMoreInteractions(spy);
The verifyZeroInteractions
check will always fail, as there were interactions with the mock.