我知道,通过在Mockito中创建存根,可以从类似这样的mock返回连续值:
when(mockedObject.doSomething()).thenReturn(1, 1, 1, 1, 5);
或
when(mockedObject.doSomething()).thenReturn(1).thenReturn(1).thenReturn(1).thenReturn(1).thenReturn(5);
是否可以为特定的返回值指定重复编号?类似这样的东西:
when(mockedObject.doSomething()).thenReturn(1, times(4)).thenReturn(5);
您可以使用循环:
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();
}
或者是一个预先计算的数组,但thenReturn
期望第一个返回值作为一个单独的参数,因此这将很难维护:
@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());
}
}