2017-07-28 33 views
2

我有一個類,它具有返回列表未來的外部依賴關係。 如何模擬外部依賴?模擬外部依賴關係,返回列表的未來

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

也許'thenAnswer'是你所需要的,而不是'thenReturn'什麼。 [這個答案](https://stackoverflow.com/a/36627077/1744230)解釋了這兩者之間的區別。 – QBrute

+0

可以詳細說明更多 – user304611

回答

2

您可以創建未來並使用thenReturn()返回。在下面的情況下,我使用CompletableFuture創建了一個已完成的Future<List<String>>

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

作爲替代方式,您也可以嘲笑未來。這種方式的好處是能夠定義任何行爲。

比如想要當一個任務被取消測試的情況下:

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