【问题标题】:Mock external dependency that returns a Future of list模拟返回列表未来的外部依赖项
【发布时间】:2018-01-05 00:13:56
【问题描述】:

我有一个具有外部依赖关系的类,它返回列表的未来。 如何模拟外部依赖?

 public void meth() {
     //some stuff
     Future<List<String>> f1 = obj.methNew("anyString")
     //some stuff
 }

 when(obj.methNew(anyString()).thenReturn("how to intialise some data here, like list of names")

【问题讨论】:

  • 也许 thenAnswer 是您在这里需要的,而不是 thenReturnThis answer 解释了这两者之间的区别。
  • 你能详细说明一下吗

标签: java unit-testing junit mocking mockito


【解决方案1】:

您可以使用thenReturn() 创建未来并将其返回。在下面的例子中,我使用CompletableFuture创建了一个已经完成的Future&lt;List&lt;String&gt;&gt;

when(f1.methNew(anyString()))
        .thenReturn(CompletableFuture.completedFuture(Arrays.asList("A", "B", "C")));

【讨论】:

【解决方案2】:

作为替代方式,您也可以模拟未来。这种方式的好处是能够定义任何行为。

例如你想测试一个任务被取消的情况:

final Future<List<String>> mockedFuture = Mockito.mock(Future.class);
when(mockedFuture.isCancelled()).thenReturn(Boolean.TRUE);
when(mockedFuture.get()).thenReturn(asList("A", "B", "C"));

when(obj.methNew(anyString()).thenReturn(mockedFuture);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-01-18
    • 1970-01-01
    • 2018-01-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-24
    相关资源
    最近更新 更多