这是我的第一篇文章,我是 CompletableFuture 的初学者,我想在使用
CompletableFuture.get()
时测试异常(InterruptedException 和 TimeoutException)。
我的代码:
CompletableFuture<ClassA> futureA =
CompletableFuture.supplyAsync(
() -> clientA.post(language, json, a));
CompletableFuture<ClassB> futureB =
CompletableFuture.supplyAsync(
() -> clientB.post(language, json, b));
CompletableFuture<Void> allFuturesResult = CompletableFuture.allOf(futureA, futureB);
try {
allFuturesResult.get(30, TimeUnit.SECONDS); //The part I want to test
} catch (InterruptedException ie) {
log.error("InterruptedException: ", ie);
Thread.currentThread().interrupt();
} catch (ExecutionException | TimeoutException e) {
allFuturesResult.cancel(true);
}
我通过返回
failedFuture
来进行测试,但这并不重要。不考虑超时。 CompletableFuture 正常完成:
@Test
void should_test() {
CompletableFuture completableFuture = Mockito.mock(CompletableFuture.class);
...
when(completableFuture.get(anyLong(), any())).thenReturn(CompletableFuture.failedFuture(new TimeoutException("Timeout occurred")));
}
感谢您的帮助。
您需要模拟在
CompletableFuture
中运行的 lambda 中调用的客户端,例如
clientA = mock(Client.class);
// this should result in an `ExecutionException` in the future
when(clientA.post(any(), any(), any()).thenThrow(new RuntimeException());
对于超时,你可以创建一些永远阻塞的东西;我想不出有什么方法可以轻松创建
InterruptedException
。