【问题标题】:Java mockito - how to add return statement in a loop?Java mockito - 如何在循环中添加返回语句?
【发布时间】:2018-02-07 17:16:31
【问题描述】:
when(/* some method call*/).thenReturn(mockFetchReturn).thenReturn(mockFetchReturn2)
            .thenReturn(mockFetchReturn3);

这工作正常,我可以用不同的输出调用模拟方法三次。但是我的输出列表可以针对每个测试场景进行更改,我找不到如何根据不同的返回在循环中完成此操作。 例如如果我传递 10 个 mockFetchReturn3 对象的列表,那么应该有 10 个返回语句。

【问题讨论】:

  • when 返回一个对象(可能称为 Expectation 或类似名称)。由于每个方法返回相同的对象,您可以执行 thenReturn 方法链接。保存对象,你可以循环调用它。

标签: junit mockito


【解决方案1】:

只需为评论中提供的答案编码:

OngoingStubbing stubbing = when(/* some method call*/);
for (int i = 0; ...) {
   stubbing = stubbing.thenReturn(mockFetchReturn(i));
}

或者,您可以将列表传递给

List<String> answers = Arrays.asList(mockFetchReturn, mockFetchReturn, ...);
when(/* some method call*/).thenAnswer(AdditionalAnswers.returnsElementsOf(logEntryList));

另见similar questions

【讨论】:

  • 第一个示例在 mockito 3.11.2 中返回 org.mockito.exceptions.base.MockitoException: Incorrect use of API detected˙
  • 如果您发现问题,请随时修复代码。无论如何,第一个例子可能是解决这个问题的最糟糕的方法。
猜你喜欢
  • 1970-01-01
  • 2012-06-07
  • 1970-01-01
  • 2023-03-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-08-23
  • 1970-01-01
相关资源
最近更新 更多