模拟完成测试中的异常

我有一个类,它有一个函数,返回:HttpClientCompletableFuture

public class HttpClient {

  public static CompletableFuture<int> getSize() {
      CompletableFuture<int> future = ClientHelper.getResults()
                 .thenApply((searchResults) -> {
                    return searchResults.size();
                });

      return future;
   }
}

然后另一个函数调用此函数:

public class Caller {

   public static void caller() throws Exception {
       // some other code than can throw an exception
       HttpClient.getSize()
       .thenApply((count) -> {
          System.out.println(count);
          return count;
       })
       .exceptionally(ex -> {
          System.out.println("Whoops! Something happened....");
       });
   }
}

现在,我想写一个测试来模拟失败,所以为此我写了这个:ClientHelper.getResults

@Test
public void myTest() {
    HttpClient mockClient = mock(HttpClient.class);

    try {
        Mockito.doThrow(new CompletionException(new Exception("HTTP call failed")))
                .when(mockClient)
                .getSize();

        Caller.caller();

    } catch (Exception e) {
        Assert.fail("Caller should not have thrown an exception!");
    }
}

此测试失败。其中的代码永远不会被执行。但是,如果我正常运行源代码并且HTTP调用失败,它就会很好地进入块。exceptionallyexceptionally

我必须如何编写测试才能执行异常代码?


答案 1

我通过在测试中这样做来使它工作:

CompletableFuture<Long> future = new CompletableFuture<>();
future.completeExceptionally(new Exception("HTTP call failed!"));

Mockito.when(mockClient.getSize())
        .thenReturn(future);

不确定这是否是最好的方法。


答案 2