1

I am new to using Mockito. In my logic I need to mock a function that is inside the loop and for every iteration, it should return different value.

Example :

for(value : values )
{
int i = getValue(value);
i=i+1;
}
if(i=somevalue)
{
some code
}
else
{
 Some other code
}

So if I mock getValue() method to return a particular value. Everytime, it is returning the same value and only one part of if else is covered. Can you please suggest me a way such that everytime in the loop getValue() is returned different value.

Thank you !

Developer
  • 11
  • 1
  • 2
  • 1
    Does this answer your question? [How to tell a Mockito mock object to return something different the next time it is called?](https://stackoverflow.com/questions/4216569/how-to-tell-a-mockito-mock-object-to-return-something-different-the-next-time-it) – Milgo Sep 23 '20 at 05:50
  • Please note, that if(i=somevalue) will always be true, you might want to use if (i == somevalue) – Milgo Sep 23 '20 at 05:53

1 Answers1

5

Since you have an input in getValue() you can use that.

when(mockFoo.getValue(value1).thenReturn(1);
when(mockFoo.getValue(value2).thenReturn(2);
when(mockFoo.getValue(value2).thenReturn(3);

But if you just don't care you can return different values in a sequence.

when(mockFoo.getValue(any()))
    .thenReturn(0)
    .thenReturn(1)
    .thenReturn(-1); //any subsequent call will return -1

// Or a bit shorter with varargs:
when(mockFoo.getValue())
    .thenReturn(0, 1, -1); //any subsequent call will return -1

Also please note, that if(i=somevalue) will always be true, you might want to use if (i == somevalue).

Milgo
  • 2,617
  • 4
  • 22
  • 37