I want a Mockito mock to return several values one after another when the same function is called on the mock, and have those values come from a list, instead of by writing them out as mock.thenReturn(1).thenReturn(2)
One way to do it is to roll my own function:
class A{
public int getVal() {return 0;}
}
class OneTest {
static void makeMockReturnSomeObjects(A mock, List<Integer> returnValues ) {
OngoingStubbing<Integer> stubbing = Mockito.when(mock.getVal());
for (Integer integer : returnValues) {
stubbing = stubbing.thenReturn(integer);
}
}
@Test
void test() {
A mock = Mockito.mock(A.class);
makeMockReturnSomeObjects(mock, List.of(1,2,3));
System.out.println(mock.getVal()); // prints 1
System.out.println(mock.getVal()); // prints 2
System.out.println(mock.getVal()); // prints 3
}
}
Is there a built in api or better way to accomplish this?