java - 在测试中模拟 CompletionException

标签 java exception mockito completable-future

我有一个 HttpClient 类,它有一个返回 CompletableFuture 的函数:

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!");
    }
}

这个测试失败了。 exceptionally 中的代码永远不会执行。但是,如果我正常运行源代码并且 HTTP 调用确实失败,它会转到 exceptionally block 就好了。

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

最佳答案

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

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

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

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

关于java - 在测试中模拟 CompletionException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45657008/

相关文章:

Java Wicket 1.5.6 : File name on download is url encoded, 将空格转换为加号

java - 如何查找java程序中有多少个方法及其名称使用了我的变量?

java - 带有 Intellij 的 Maven WebApp - 程序

c# - 配置错误异常 : This element is not currently associated with any context

python - 如何检查 TypeError 是否针对 NoneType

java - 函数的 Junit 测试

java - 使用 Mockito 调用模拟方法时出现 NullPointerException

java - 使用 Thrift 进行离线序列化?

java - 为什么 Float.parseFloat() 同时抛出 NumberFormatException 和 NullPointerException 而 Integer.parseInt() 只抛出 NumberFormatException?

java - 当我为其设置行为时,Mockito 尝试调用方法