Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to make sure mocked object is called only once in mockito

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

like image 612
ankit Avatar asked Nov 14 '13 07:11

ankit


People also ask

How do you know if mocked method called?

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.

How do you check whether a method is called in Mockito?

verify(bar, times(1)). someMethod();

Can you call method on mocked object?

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.

Which method in Mockito verifies that no interaction has happened with a mock in Java?

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.


2 Answers

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);
like image 167
ankit Avatar answered Oct 18 '22 23:10

ankit


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.

like image 25
Max Fichtelmann Avatar answered Oct 18 '22 23:10

Max Fichtelmann