How do I mock and write unit tests for the below function? I am finding it difficult to write unit tests for CompletableFuture. If the function does not cancel the task within 3 minutes, I want to throw an exception in the unit test
private void cancel() throws TimeoutException, ExecutionException, InterruptedException {
try {
CompletableFuture.supplyAsync(() -> {
try {
cancelTask();// function that cancels a task
} catch (ApiException ex) {
Logger.error("Api exception while cancelling a tasks")
}
return null
}).get(3, TimeUnit.MINUTES);
} catch (final InterruptedException | ExecutionException | TimeoutException e) {
throw e;
}
}
To force CompletableFuture.supplyAsync to return a Timeout Exception in the unit test case after cancelTask() is called, you have to override your cancelTask when you test this case. You can do this in several way:
BusinessClass
Test class:
BusinessClasses
Test Class