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

有没有一种方法可以使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。


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


繁星淼淼
浏览 492回答 1
1回答

元芳怎么了

正如Sotirios所指出的,您可以创建一个CompletableFuture,并使其具有例外情况。这是供他人参考的代码:@Testpublic void whenRunnerThrows_thenReturn5xx() throws Exception {&nbsp; &nbsp; CompletableFuture<String> badFuture = new CompletableFuture<>();&nbsp; &nbsp; badFuture.completeExceptionally(new Exception(""));&nbsp; &nbsp; when(service.runAsync(any(),any())).thenReturn(badFuture);&nbsp; &nbsp; mvc.perform(post("/test")&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .contentType(MediaType.APPLICATION_JSON)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .content("{\"name\":\"test\"}"))&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .andExpect(status().is5xxServerError());}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java