- iOS/Objective-C 元类和类别
- objective-c - -1001 错误,当 NSURLSession 通过 httpproxy 和/etc/hosts
- java - 使用网络类获取 url 地址
- ios - 推送通知中不播放声音
我有一个 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/
我有一个 HttpClient 类,它有一个返回 CompletableFuture 的函数: public class HttpClient { public static Completabl
CompletionStage Javadoc 指出: [...] if a stage's computation terminates abruptly with an (unchecked) e
CompletionStage Javadoc 指出: [...] if a stage's computation terminates abruptly with an (unchecked) e
在不同的 java 次要版本下,我从相同的代码片段中得到了不同的输出。我在 open jdk bug tracker 上找不到相关的票证。 CompletableFuture completableF
这个问题在这里已经有了答案: Play Framework 2.5 JavaAsync throwing CompletionException (2 个答案) 关闭 5 年前。 在示例应用程序上从
我正在使用 Play 2.5 构建一个简单的应用程序。为了获得更好的性能,我将 Akka 分块响应与 Java 8 CompletionStage 策略结合使用。下面是生成分块响应的代码(不使用 Co
已关闭。此问题需要 debugging details 。目前不接受答案。 编辑问题以包含 desired behavior, a specific problem or error, and the
我正在编写一个递归代码,根据像素值相似度来绘制对象轮廓。正如您在下面的代码中看到的,我正在使用四个异步工作的线程,但在运行时我收到以下发布的错误,我不知道如何修复它。 收到错误: Exception
我是一名优秀的程序员,十分优秀!