有没有一种方法可以使Mockito在CompletableFuture.get()调用上引发异常,而不仅仅是异步方法?例如,给定以下(不正确的)测试用例:@Testpublic 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。编写像这样的测试以使在单元测试中与运行应用程序时同时引发异常的正确方法是什么?
1 回答
![?](http://img1.sycdn.imooc.com/5458471300017f3702200220-100-100.jpg)
元芳怎么了
TA贡献1798条经验 获得超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());
}
添加回答
举报
0/150
提交
取消