为什么Mockito不支持thenReturn方法中的集合?

我想要

// 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);


因为expectedValues的计数是任意的。

最佳答案

方法thenReturn支持varargs,但不支持Collections:

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

OR

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


另一种方法是链接thenReturn调用:

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


两者都会在第一次调用something1时返回mockObject.someMethod(),在第二次调用等时返回something2

09-26 06:34