动态链接“thenReturn"在模拟 [英] Dynamic chaining "thenReturn" in mockito

查看:47
本文介绍了动态链接“thenReturn"在模拟的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 Tuple 模拟类,它的 getString(0) 和 getString(1) 方法预计会被调用 n 次.而不是写类似的东西,

I have a Tuple mock class, whose getString(0) and getString(1) methods are expected to be called n times. Instead of writing something like,

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

手动,我尝试了以下操作:

manually, I tried the following:

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 个元素.

The expected result is that all calls to tuple.getString(0) should return the String serviceRequestKey and each call to tuple.getString(1) should return a different String logEntries[i] ie. ith invocation of tuple.getString(1) returns ith element of logEntries array.

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

However, due to some odd reason, things are getting mixed up, and second invocation to tuple.getString(1) returns the String serviceRequestKey instead of logEntries[1]. What am I missing here?

推荐答案

嗯,正确的做法是:

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) 的第 i 次调用返回 logEntry 数组的第 i 个元素.

On each invocation, successive elements of logEntry array are returned. Thus, ith invocation of tuple.getString(1) returns ith element of logEntry array.

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

P.S: The example in documentation of returnsElementsOf (as of this writing) is not updated (it still uses ReturnsElementsOf example): http://docs.mockito.googlecode.com/hg/1.9.5/org/mockito/AdditionalAnswers.html#returnsElementsOf(java.util.Collection)it

这篇关于动态链接“thenReturn"在模拟的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆