I have a class HttpClientthat has a function that returns CompletableFuture:
public class HttpClient {
public static CompletableFuture<int> getSize() {
CompletableFuture<int> future = ClientHelper.getResults()
.thenApply((searchResults) -> {
return searchResults.size();
});
return future;
}
}
Then another function calls this function:
public class Caller {
public static void caller() throws Exception {
HttpClient.getSize()
.thenApply((count) -> {
System.out.println(count);
return count;
})
.exceptionally(ex -> {
System.out.println("Whoops! Something happened....");
});
}
}
Now I want to write a test to simulate what ClientHelper.getResults does not work , so for this I wrote this:
@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!");
}
}
This test fails. The code inside exceptionallywill never be executed. However, if I usually run the source code and the HTTP call fails, it fits the block perfectly exceptionally.
How do I write a test so that the code runs exceptionally?
source
share