I have a while loop as follows
while (nodeIterator.hasNext())
I have mocked this method hasNext to return true so that I can test the code inside while loop but now the problem is everytime it returns true and this loop will never end. Please tell me is there anyway by which I can make sure that this method is called only once, or if not then how can I return false after first execution
Mockito verify() method can be used to test number of method invocations too. We can test exact number of times, at least once, at least, at most number of invocation times for a mocked method.
verify(bar, times(1)). someMethod();
Mockito allows us to partially mock an object. This means that we can create a mock object and still be able to call a real method on it.
Mockito verifyZeroInteractions() method It verifies that no interaction has occurred on the given mocks. It also detects the invocations that have occurred before the test method, for example, in setup(), @Before method or the constructor.
I got the answer we can do it in the following way
when(nodeIterator.hasNext()).thenReturn(true).thenReturn(false);
this is known as method stubbing. Similarly if you want to call it twice and then you want to return false, then do as follows
when(nodeIterator.hasNext()).thenReturn(true).thenReturn(true).thenReturn(false);
see OngoingStubbing.thenReturn(T,T...)
this way you can return values for a sequence of calls.
when(nodeIterator.hasNext()).thenReturn(true,false);
above returns true on the first call and false on every subsequent call.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With