Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/380.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/unit-testing/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在Java中使用Mockito模拟循环中的函数,以便为每次迭代返回不同的值_Java_Unit Testing_Mocking_Mockito - Fatal编程技术网

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

如何在Java中使用Mockito模拟循环中的函数,以便为每次迭代返回不同的值,java,unit-testing,mocking,mockito,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 } 所以,如果我模拟getValue()方法来返回一个特定的值。每次,它都返回相同的值,并且只包含if-else的一部分。 你能给我一个建议,让每次在循环getValu

我不熟悉使用Mockito。在我的逻辑中,我需要模拟循环中的函数,对于每次迭代,它应该返回不同的值

例如:

for(value : values )
{
int i = getValue(value);
i=i+1;
}
if(i=somevalue)
{
some code
}
else
{
 Some other code
}
所以,如果我模拟getValue()方法来返回一个特定的值。每次,它都返回相同的值,并且只包含if-else的一部分。 你能给我一个建议,让每次在循环getValue()中都返回不同的值吗


谢谢大家!

因为在getValue()中有一个输入,所以可以使用它

when(mockFoo.getValue(value1).thenReturn(1);
when(mockFoo.getValue(value2).thenReturn(2);
when(mockFoo.getValue(value2).thenReturn(3);
但如果你不在乎,你可以按顺序返回不同的值

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

另外请注意,
if(i=somevalue)
始终为真,您可能需要使用
if(i=somevalue)

这是否回答了您的问题?请注意,如果(i=somevalue)始终为true,您可能希望使用if(i==somevalue),如果不向链接答案添加任何内容,则不要从链接答案复制该答案。链接答案没有关于输入参数的信息。