为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

繁星淼淼 2021-04-27 08:38:45
有没有一种方法可以使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 回答

?
元芳怎么了

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());

}


查看完整回答
反对 回复 2021-05-19
  • 1 回答
  • 0 关注
  • 491 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信