1
when(/* some method call*/).thenReturn(mockFetchReturn).thenReturn(mockFetchReturn2)
            .thenReturn(mockFetchReturn3);

This is working fine and I am able to call mocked method three times with different output. But my output list can change for each test scenario and I couldn't find how this can be done in a loop based on different returns. For e.g. If I pass a list of 10 mockFetchReturn3 objects then there should be 10 return statements.

user1298426
  • 3,467
  • 15
  • 50
  • 96
  • 1
    `when` returns an object (probably something called `Expectation` or something similar). Your can do the `thenReturn` method chaining due to each method returning the same object. Save the object, and you can call this in a loop. – Giora Guttsait Feb 07 '18 at 17:19
  • Possible duplicate of [Dynamic chaining "thenReturn" in mockito](https://stackoverflow.com/questions/25010390/dynamic-chaining-thenreturn-in-mockito) – tkruse Feb 08 '18 at 11:07

1 Answers1

5

Just code for the answer provided in comment:

OngoingStubbing stubbing = when(/* some method call*/);
for (int i = 0; ...) {
   stubbing = stubbing.thenReturn(mockFetchReturn(i));
}

Alternatively, you can pass a list to

List<String> answers = Arrays.asList(mockFetchReturn, mockFetchReturn, ...);
when(/* some method call*/).thenAnswer(AdditionalAnswers.returnsElementsOf(logEntryList));

Also see similar questions

tkruse
  • 10,222
  • 7
  • 53
  • 80
  • First example returns `org.mockito.exceptions.base.MockitoException: Incorrect use of API detected˙` in mockito 3.11.2 – Kajzer Nov 30 '21 at 07:31
  • feel free to fix code if you find out the issue. Anyway first example is probably worst way to solve this. – tkruse Nov 30 '21 at 09:23