Issue
I know that by creating a stub in Mockito, consecutive values can be returned from a mock like so:
when(mockedObject.doSomething()).thenReturn(1, 1, 1, 1, 5);
or
when(mockedObject.doSomething()).thenReturn(1).thenReturn(1).thenReturn(1).thenReturn(1).thenReturn(5);
Is it possible to specify a repeat number for a specific return value? Something like this:
when(mockedObject.doSomething()).thenReturn(1, times(4)).thenReturn(5);
Solution
You can use a loop:
class Mockme {
@Test
void test() {
final UnderTest mock = Mockito.mock(UnderTest.class);
OngoingStubbing<Integer> stubbing = Mockito.when(mock.get());
for (int i = 0; i < 4; i++) {
stubbing = stubbing.thenReturn(1);
}
stubbing.thenReturn(5, 7, 10);
for (int i = 0; i < 10; i++) {
System.out.println(mock.get());
}
}
}
interface UnderTest {
int get();
}
Or a pre-computed array, but thenReturn
expects the first return value as a separate argument, so this will be difficult to maintain:
@Test
void test() {
final Integer[] returns = new Integer[6];
Arrays.fill(returns, 1);
returns[3] = 5;
returns[4] = 7;
returns[5] = 10;
final UnderTest mock = Mockito.mock(UnderTest.class);
Mockito.when(mock.get()).thenReturn(1, returns);
for (int i = 0; i < 10; i++) {
System.out.println(mock.get());
}
}
Answered By - knittl
Answer Checked By - Marie Seifert (JavaFixing Admin)