1

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.

coderz
  • 4,847
  • 11
  • 47
  • 70
  • Does mockObject.someMethod() return a List ? – Steve Benett Mar 08 '20 at 22:46
  • @SteveBenett No, it returns a `Something` object. Updated the question. – coderz Mar 08 '20 at 23:17
  • Check [this answer](https://stackoverflow.com/a/33698670/9985287). I think it is exactly what you are looking for. – Mansur Mar 08 '20 at 23:23
  • @MensurQulami This only works if I know the count of expected values. What if I don't know the count of expected values? – coderz Mar 08 '20 at 23:30
  • I mean if you want to pass a List as an argument, shouldn't you know the exact number of expected values? I am not sure I understood what you meant. – Mansur Mar 08 '20 at 23:57

1 Answers1

4

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.

Steve Benett
  • 12,843
  • 7
  • 59
  • 79
  • The `Mockito.when(mockObject.someMethod()).thenReturn(something, arrayOfSomething);` is exactly what I want. Thanks! – coderz Mar 09 '20 at 00:41