在mockito中动态链接"thenReturn"

gja*_*ain 10 java unit-testing mockito method-chaining chaining

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

when(tuple.getString(0)).thenReturn(logEntries[0]).thenReturn(logEntries[1])...thenReturn(logEntries[n - 1])
Run Code Online (Sandbox Code Playgroud)

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

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]);
}
Run Code Online (Sandbox Code Playgroud)

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

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

gja*_*ain 13

那么,正确的方法是:

import org.mockito.AdditionalAnswers;

String[] logEntry = // Some initialization code
List<String> logEntryList = Arrays.asList(logEntry);
when(tuple.getString(1)).thenAnswer(AdditionalAnswers.returnsElementsOf(logEntryList));
Run Code Online (Sandbox Code Playgroud)

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

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


Nad*_*dir 5

如果我很了解,您希望您的模拟程序根据调用返回不同的结果(意味着第一次调用result1,第二次调用result2等等)-这可以用这种方法来完成

Mockito.when(tuple.getString(0)).thenReturn(serviceRequestKey,logEntries[0],logEntries[1])
Run Code Online (Sandbox Code Playgroud)

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

如果你想要的)一些更复杂的,像改变取决于该方法使用thenAnswer(帕拉姆返回如图所示这里