在mockito中动态链接“thenReturn”

时间:2014-07-29 07:40:41

标签: java unit-testing mockito chaining method-chaining

我有一个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)的所有调用都应该返回字符串serviceRequestKey,并且对tuple.getString(1)的每次调用都应该返回不同的字符串logEntries[i],即。 ith调用tuple.getString(1)返回logEntries数组的第i个元素。

但是,由于一些奇怪的原因,事情变得混乱,第二次调用tuple.getString(1)会返回字符串serviceRequestKey而不是logEntries[1]。我在这里缺少什么?

4 个答案:

答案 0 :(得分:10)

嗯,正确的方法是:

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

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

答案 1 :(得分:3)

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

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

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

如果你想要更复杂的东西,比如根据方法中的参数改变回报,请使用thenAnswer(),如图所示here

答案 2 :(得分:0)

我不确定Mofito能够理解你的例子,但你不想要这样的东西:

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

答案 3 :(得分:0)

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

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