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

时间:2018-07-09 18:17:08

标签: java spring-boot mockito completable-future

是否有一种方法可以使Mockito在const array1 = [1,2,3,4]; const array2 = [5,6,7,8]; const array3 = [9,10]; const arr = [array1, array2, array3] console.log(arr); const reducer = (accumulator, currentValue) => [...accumulator, ...currentValue]; console.log(arr.reduce(reducer)); 调用上引发异常,而不仅仅是异步方法?

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

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()); } 时,将引发异常,这很有意义。但是,当运行(Spring Boot)应用程序时,相同的异常只会作为返回的service.runAsync()上的ExecutionException原因抛出。

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

1 个答案:

答案 0 :(得分:0)

如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());
}
相关问题