How to mock the function in a loop using Mockito in Java to return different value for each iteration

huangapple go评论82阅读模式
英文:

How to mock the function in a loop using Mockito in Java to return different value for each iteration

问题

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

示例:

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

所以如果我模拟getValue()方法返回特定的值。每次都返回相同的值,只覆盖了if else的一部分。
请问您能否建议我一种方法,使得在循环中每次调用getValue()时返回不同的值。

谢谢!

英文:

I am new to using Mockito. In my logic I need to mock a function that is inside the loop and for every iteration, it should return different value.

Example :

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

So if I mock getValue() method to return a particular value. Everytime, it is returning the same value and only one part of if else is covered.
Can you please suggest me a way such that everytime in the loop getValue() is returned different value.

Thank you !

答案1

得分: 5

由于您在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); // 任何后续调用都将返回 -1

// 或者使用可变参数更简洁:
when(mockFoo.getValue())
    .thenReturn(0, 1, -1); // 任何后续调用都将返回 -1

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

英文:

Since you have an input in getValue() you can use that.

when(mockFoo.getValue(value1).thenReturn(1);
when(mockFoo.getValue(value2).thenReturn(2);
when(mockFoo.getValue(value2).thenReturn(3);

But if you just don't care you can return different values in a sequence.

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

Also please note, that if(i=somevalue) will always be true, you might want to use if (i == somevalue).

huangapple
  • 本文由 发表于 2020年9月23日 13:44:38
  • 转载请务必保留本文链接:https://go.coder-hub.com/64021732.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定