Search code examples
javamockitopowermockito

Mockito - when ... thenReturn multiple times by passing a list of expected values


Why Mockito does not support a collection in thenReturn method?

I want

// mockObject.someMethod() returns an instance of "Something".
// Want to achieve that call mockObject.someMethod the first time returns Something_1, call mockObject.someMethod the second time returns Something_2, call mockObject.someMethod the third time returns Something_3, ...
List<Something> expectedValues = ...;
when(mockObject.someMethod()).thenReturn(expectedValues);

because the count of expectedValues is arbitrary.


Solution

  • The method thenReturn supports varargs but no Collections:

    Mockito.when(mockObject.someMethod()).thenReturn(something1, something2, ...);
    
    OR
    
    Mockito.when(mockObject.someMethod()).thenReturn(something, arrayOfSomething);
    

    An alternative is to chain the thenReturn calls:

    Mockito.when(mockObject.someMethod()).thenReturn(something1).thenReturn(something2);
    

    Both will return something1 on the first call of mockObject.someMethod() and something2 on the second call etc.