在测试中模拟 CompletionException
Simulate CompletionException in a test
我有一个 class HttpClient
具有 returns 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
块。
我必须如何编写测试才能执行 exceptionally
代码?
我通过在测试中这样做来实现它:
CompletableFuture<Long> future = new CompletableFuture<>();
future.completeExceptionally(new Exception("HTTP call failed!"));
Mockito.when(mockClient.getSize())
.thenReturn(future);
不确定这是否是最好的方法。
我有一个 class HttpClient
具有 returns 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
块。
我必须如何编写测试才能执行 exceptionally
代码?
我通过在测试中这样做来实现它:
CompletableFuture<Long> future = new CompletableFuture<>();
future.completeExceptionally(new Exception("HTTP call failed!"));
Mockito.when(mockClient.getSize())
.thenReturn(future);
不确定这是否是最好的方法。