模拟返回列表的Future的外部依赖项

时间:2017-07-28 20:15:33

标签: java unit-testing junit mocking mockito

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

 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")

2 个答案:

答案 0 :(得分:8)

您可以创建未来并使用thenReturn()将其返回。在下面的情况中,我使用Future<List<String>>创建了一个已完成的CompletableFuture

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

答案 1 :(得分:4)

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

例如,您希望在取消任务时测试案例:

[1.0, 3.0, 4.0, 5.0, 7.0, 0.0]
[1, 3, 4, 5, 7, 0]
[1, , 3, 4, 5, , 7, sasd, aaa, 0]
[1.0, 3.0, 4.0, 5.0, 7.0, 0.0]