我有一个元组模拟类,它的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] ie。对tuple.getString(1)的ith调用返回logEntries数组的ith元素。
但是,由于一些奇怪的原因,事情变得混乱了,第二次对tuple.getString(1)的调用返回字符串serviceRequestKey而不是logEntries[1]。我在这里错过了什么?
发布于 2014-07-29 10:22:16
好吧,正确的方法是:
import org.mockito.AdditionalAnswers;
String[] logEntry = // Some initialization code
List<String> logEntryList = Arrays.asList(logEntry);
when(tuple.getString(1)).thenAnswer(AdditionalAnswers.returnsElementsOf(logEntryList));每次调用时,都会返回logEntry数组的连续元素。因此,对tuple.getString(1)的ith调用返回logEntry数组的ith元素。
P.S: returnsElementsOf文档中的示例(截至本文编写时)未被更新(它仍然使用ReturnsElementsOf示例):http://docs.mockito.googlecode.com/hg/1.9.5/org/mockito/AdditionalAnswers.html#returnsElementsOf(java.util.Collection)it
发布于 2014-07-29 08:22:22
如果我理解得很好,您希望您的模拟根据调用返回不同的结果(第一次调用时意味着result1,第二次调用时返回result2等等)--这可以通过这样的事情来实现。
Mockito.when(tuple.getString(0)).thenReturn(serviceRequestKey,logEntries[0],logEntries[1])这样你就可以得到第一次调用的serviceRequestKey,第二次调用的logEntries等等.
如果您想要更复杂的东西,比如根据方法中的param更改返回,请使用thenAnswer(),如here所示
发布于 2014-07-29 08:21:16
我不确定我是否理解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]);
}https://stackoverflow.com/questions/25010390
复制相似问题