如何在 CompletableFuture.get() 调用上抛出异常?

jef*_*dio 5 java mockito spring-boot completable-future

有没有办法让 mockito 在CompletableFuture.get()调用时抛出异常而不仅仅是异步方法?

例如,给定以下(不正确的)测试用例:

@Test
public void whenRunnerThrows_thenReturn5xx() throws Exception {
    when(service.runAsync(any(),any())).thenThrow(new Exception(""));

    mvc.perform(post("/test")
            .contentType(MediaType.APPLICATION_JSON)
            .content("{\"name\":\"test\"}"))
            .andExpect(status().is5xxServerError());
}
Run Code Online (Sandbox Code Playgroud)

service.runAsync()在测试期间调用when ,抛出异常,这是有道理的。但是当(Spring Boot)应用程序运行时,同样的异常只会作为ExecutionException返回的原因抛出CompletableFuture::get.

编写这样的测试以便在运行应用程序时在单元测试中同时抛出异常的正确方法是什么?

jef*_*dio 7

正如 Sotirios 所指出的,您可以创建一个CompletableFuture并完成它,但有例外。以下是供他人参考的代码:

@Test
public void whenRunnerThrows_thenReturn5xx() throws Exception {
    CompletableFuture<String> badFuture = new CompletableFuture<>();
    badFuture.completeExceptionally(new Exception(""));
    when(service.runAsync(any(),any())).thenReturn(badFuture);

    mvc.perform(post("/test")
            .contentType(MediaType.APPLICATION_JSON)
            .content("{\"name\":\"test\"}"))
            .andExpect(status().is5xxServerError());
}
Run Code Online (Sandbox Code Playgroud)

  • 从 Java 9 开始,您可以使用 `CompletableFuture.failedFuture (new Exception(""))` 来实现相同的效果。 (3认同)