如何使用 Java 中的 Mockito 模拟循环中的函数,为每次迭代返回不同的值

1 java unit-testing mocking mockito

我刚开始使用 Mockito。在我的逻辑中,我需要模拟循环内部的函数,并且对于每次迭代,它应该返回不同的值。

例子 :

for(value : values )
{
int i = getValue(value);
i=i+1;
}
if(i=somevalue)
{
some code
}
else
{
 Some other code
}
Run Code Online (Sandbox Code Playgroud)

因此,如果我模拟 getValue() 方法来返回特定值。每次,它都返回相同的值,并且只覆盖 if else 的一部分。您能否建议我一种方法,以便每次在循环中 getValue() 返回不同的值。

谢谢 !

Mil*_*lgo 5

由于您在 getValue() 中有一个输入,因此您可以使用它。

when(mockFoo.getValue(value1).thenReturn(1);
when(mockFoo.getValue(value2).thenReturn(2);
when(mockFoo.getValue(value2).thenReturn(3);
Run Code Online (Sandbox Code Playgroud)

但如果您不在乎,您可以按序列返回不同的值。

when(mockFoo.getValue(any()))
    .thenReturn(0)
    .thenReturn(1)
    .thenReturn(-1); //any subsequent call will return -1

// Or a bit shorter with varargs:
when(mockFoo.getValue())
    .thenReturn(0, 1, -1); //any subsequent call will return -1
Run Code Online (Sandbox Code Playgroud)

另请注意,这if(i=somevalue)始终是正确的,您可能想使用if (i == somevalue).