我有一个 Tuple 模拟类,它的 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)
的调用都应该返回字符串 serviceRequestKey
并且每次调用 tuple.getString(1)
应该返回一个不同的字符串 logEntries[i]
即。 tuple.getString(1) 的第 i 次调用返回 logEntries 数组的第 i 个元素。
然而,由于一些奇怪的原因,事情变得困惑,第二次调用 tuple.getString(1)
返回字符串 serviceRequestKey
而不是 日志条目[1]
。我在这里缺少什么?
最佳答案
嗯,正确的做法是:
import org.mockito.AdditionalAnswers;
String[] logEntry = // Some initialization code
List<String> logEntryList = Arrays.asList(logEntry);
when(tuple.getString(1)).thenAnswer(AdditionalAnswers.returnsElementsOf(logEntryList));
每次调用时,都会返回 logEntry 数组的连续元素。因此,第 i 个 tuple.getString(1)
调用返回 logEntry 数组的第 i 个元素。
P.S:returnsElementsOf 文档中的示例(截至撰写本文时)未更新(它仍然使用 ReturnsElementsOf 示例):http://docs.mockito.googlecode.com/hg/1.9.5/org/mockito/AdditionalAnswers.html#returnsElementsOf(java.util.Collection)it
关于java - mockito 中的动态链接 "thenReturn",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25010390/