我有一个Tuple mock类,其getString(0)和getString(1)方法应该被调用n次。 而不是写一些像,

when(tuple.getString(0)).thenReturn(logEntries[0]).thenReturn(logEntries[1])...thenReturn(logEntries[n - 1])

手动,我尝试了以下内容:

OngoingStubbing stubbingGetStringZero = when(tuple.getString(0)).thenReturn(serviceRequestKey);
OngoingStubbing stubbingGetStringOne = when(tuple.getString(1)).thenReturn(logEntries[0]);
for (int i = 1; i < n; i++) {
stubbingGetStringZero = stubbingGetStringZero.thenReturn(serviceRequestKey);
stubbingGetStringOne = stubbingGetStringOne.thenReturn(logEntries[i]);
}

预期的结果是对tuple.getString(0)的所有调用都应该返回String serviceRequestKey,并且每次调用tuple.getString(1)都应该返回不同的String logEntries[i] ie。 ith调用tuple.getString(1)返回logEntries数组的第i个元素。

然而,由于一些奇怪的原因,事情变得混乱,第二次调用tuple.getString(1)返回String serviceRequestKey而不是logEntries[1]。 我在这里错过了什么?

那么,正确的方法是:

import org.mockito.AdditionalAnswers;
String[] logEntry = // Some initialization code
List logEntryList = Arrays.asList(logEntry);
when(tuple.getString(1)).thenAnswer(AdditionalAnswers.returnsElementsOf(logEntryList));

在每次调用时,都会返回logEntry数组的连续元素。因此,第x次调用tuple.getString(1)返回logEntry数组的第i个元素。

PS:returnElementsOf文档中的示例(截至本文撰写时)未更新(它仍使用ReturnsElementsOf示例):http://docs.mockito.googlecode.com/hg/1.9.5/org/mockito/AdditionalAnswers.html #returnsElementsOf(java.util.Collection中)它

如果我理解得很好,你希望你的mock根据调用返回不同的结果(意思是第一次调用时的result1,第二次调用时的result2等) - 这可以用这样的东西来完成

Mockito.when(tuple.getString(0)).thenReturn(serviceRequestKey,logEntries[0],logEntries[1])

有了这个,你将在第一次调用时获得serviceRequestKey,在第二次调用时获得logEntries [0]等...

如果你想要更复杂的东西,比如根据方法中的param更改返回,请使用thenAnswer(),如下所示

好吧,你的答案是正确的,本质上是多个thenReturn的简写版本。唯一的问题是我的调用次数有点大~15-20。所以,我将不得不为thenReturn编写那么多参数。希望找到一个使用for循环或其他东西的解决方案。

thenReturn方法加入String [],因此您可以根据需要在循环中创建数组,然后传递它。

thenReturn()只接受多个String参数,而不是数组。请参阅:docs.mockito.googlecode.com/hg/org/mockito/stubbing/。无论如何,你的评论帮我看了正确的方向。谢谢!

@gjain,varargs只是数组顶部的语法糖,所以String []会运行良好。有关详细信息,请参阅stackoverflow.com/questions/2925153/。

@MikaelOhlson问题是你需要使用Mockito的语法进行长距离漫步,因为你需要从数组中删除第一个参数以便拟合:thenReturn(T值,T ...值),然后是subList,它是一个一塌糊涂。

我知道帖子比较旧,但也许有帮助:

OngoingStubbing whenCollectionHasNext = when(mockCollectionStream.hasNext());
for (int i = 0; i < 2; i++) {
whenCollectionHasNext = whenCollectionHasNext.thenReturn(true);
}
whenCollectionHasNext = whenCollectionHasNext.thenReturn(false);

我不确定我是否理解Mockito足以理解你的例子,但是你不想要这样的东西:

Mockito.when(tuple.getString(0)).thenReturn(serviceRequestKey);
for(int i = 0;i < logEntries.length;i++) {
Mockito.when(tuple.getString(i+1)).thenReturn(logEntries[i]);
}

我已进一步澄清了这个问题。实际上,我希望每次调用tuple.getString(1)时得到不同的结果。请注意,它始终是tuple.getString(1),索引不会更改。