代码之家  ›  专栏  ›  技术社区  ›  unknown

如何模拟CompletableFuture.get()抛出异常

  •  0
  • unknown  · 技术社区  · 2 年前

    我有如下代码

    public Object getStatus(CompletableFuture<Object> futureA, CompletableFuture<Object> futureB) {
    CompletableFuture.allOf(futureA, futureB).join();
    try {
    if(futureA.get()!=null) return futureA.get();
    } catch(SomeException e) {
    //log
    }
    try {
    if(futureB.get()!=null) return futureB.get();
    } catch(SomeException e) {
    //log
    }
    }
    

    我的测试如下

    @Test
    public void testException() {
    CompletableFuture<Object> futureA = new CompletableFuture<>();
    CompletableFuture<Object> futureB = CompletableFuture.completedFuture(null);
    CompletableFuture<Object> spy = Mockito.spy(futureA);
    when(spy.get()).thenThrow(new SomeException());
    service.getStatus(futureA, futureB);
    }
    

    试图覆盖捕获块,但这不起作用,它正在等待futureA完成。我该如何测试接球块?

    1 回复  |  直到 2 年前
        1
  •  1
  •   NoDataFound    2 年前

    为什么不使用API提供的功能:

    CompletableFuture<Object> failed = new CompletableFuture<>();
    failed.completeExceptionally(new SomeException());
    

    documentation :

    如果尚未完成,则导致调用get()和相关方法抛出给定的异常。

    然而, get() 将提高 ExecutionException 原因应该是 SomeException ,这意味着你的 getStatus 代码无效:

    try {
      return futureA.get();
    } catch (ExecutionException e) {
      // handle cause, eg: if (e.getCause() instanceof SomeException) ...
    }
    try {
      return futureB.get();
    } catch (ExecutionException e) {
      // handle cause, eg: if (e.getCause() instanceof SomeException) ...
    }
    return null; // or whatever default value/exception