ankit
ankit

Reputation: 5127

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

Upvotes: 16

Views: 16642

Answers (2)

Max Fichtelmann
Max Fichtelmann

Reputation: 3504

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.

Upvotes: 9

ankit
ankit

Reputation: 5127

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);

Upvotes: 27

Related Questions