我有一个 HttpClient
类,它有一个返回 CompletableFuture
的函数:
public class HttpClient {
public static CompletableFuture<int> getSize() {
CompletableFuture<int> future = ClientHelper.getResults()
.thenApply((searchResults) -> {
return searchResults.size();
});
return future;
}
}
然后另一个函数调用这个函数:
public class Caller {
public static void caller() throws Exception {
// some other code than can throw an exception
HttpClient.getSize()
.thenApply((count) -> {
System.out.println(count);
return count;
})
.exceptionally(ex -> {
System.out.println("Whoops! Something happened....");
});
}
}
现在,我想编写一个测试来模拟 ClientHelper.getResults
失败,为此我写了这个:
@Test
public void myTest() {
HttpClient mockClient = mock(HttpClient.class);
try {
Mockito.doThrow(new CompletionException(new Exception("HTTP call failed")))
.when(mockClient)
.getSize();
Caller.caller();
} catch (Exception e) {
Assert.fail("Caller should not have thrown an exception!");
}
}
这个测试失败了。 exceptionally
中的代码永远不会执行。但是,如果我正常运行源代码并且 HTTP 调用确实失败,它会转到 exceptionally
block 就好了。
我必须如何编写测试才能执行异常
代码?
最佳答案
我通过在测试中这样做来让它工作:
CompletableFuture<Long> future = new CompletableFuture<>();
future.completeExceptionally(new Exception("HTTP call failed!"));
Mockito.when(mockClient.getSize())
.thenReturn(future);
不确定这是否是最好的方法。
关于java - 在测试中模拟 CompletionException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45657008/