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

use*_*611 8 java junit unit-testing 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")
Run Code Online (Sandbox Code Playgroud)

Tod*_*odd 10

您可以创建未来并使用它返回thenReturn().在下面的例子中,我创建了一个已经完成的Future<List<String>>使用CompletableFuture.

when(f1.methNew(anyString()))
        .thenReturn(CompletableFuture.completedFuture(Arrays.asList("A", "B", "C")));
Run Code Online (Sandbox Code Playgroud)


Dmy*_*nko 7

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

例如,您要测试取消任务的情况:

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);
Run Code Online (Sandbox Code Playgroud)