繁体   English   中英

如何在CompletableFuture.get()调用上引发异常?

[英]How to throw an exception on an CompletableFuture.get() call?

有没有一种方法可以让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());
}

在测试过程中调用service.runAsync()时,将引发异常,这很有意义。 但是当(Spring Boot)应用程序运行时,相同的异常将仅作为ExecutionException原因抛出,返回的CompletableFuture::get会抛出该异常。

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

正如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());
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM