### Question:
Utils { static CompletionStage<?> ifCancelled( CompletionStage<?> stage, Consumer<? super CancellationException> action) { requireNonNull(action); return stage.exceptionally(e -> { cast(e, CancellationException.class).ifPresent(action); return null; }); }    }### Answer:
@Test public void testIfCancelled_pending() { AtomicReference<CancellationException> cancelled = new AtomicReference<>(); CompletableFuture<String> future = new CompletableFuture<>(); Utils.ifCancelled(future, cancelled::set); assertThat(cancelled.get()).isNull(); }
@Test public void testIfCancelled_completed() { AtomicReference<CancellationException> cancelled = new AtomicReference<>(); CompletableFuture<String> future = new CompletableFuture<>(); future.complete("good"); Utils.ifCancelled(future, cancelled::set); assertThat(cancelled.get()).isNull(); }
@Test public void testIfCancelled_exception() { AtomicReference<CancellationException> cancelled = new AtomicReference<>(); CompletableFuture<String> future = new CompletableFuture<>(); future.completeExceptionally(new RuntimeException()); Utils.ifCancelled(future, cancelled::set); assertThat(cancelled.get()).isNull(); }
@Test public void testIfCancelled_cancellationException() { AtomicReference<CancellationException> cancelled = new AtomicReference<>(); CompletableFuture<String> future = new CompletableFuture<>(); CancellationException exception = new CancellationException(); future.completeExceptionally(exception); Utils.ifCancelled(future, cancelled::set); assertThat(cancelled.get()).isSameAs(exception); }
@Test public void testIfCancelled_cancelledWithInterruption() { AtomicReference<CancellationException> cancelled = new AtomicReference<>(); CompletableFuture<String> future = new CompletableFuture<>(); future.cancel(true); Utils.ifCancelled(future, cancelled::set); assertThat(cancelled.get()).isInstanceOf(CancellationException.class); }
@Test public void testIfCancelled_cancelledWithoutInterruption() { AtomicReference<CancellationException> cancelled = new AtomicReference<>(); CompletableFuture<String> future = new CompletableFuture<>(); future.cancel(false); Utils.ifCancelled(future, cancelled::set); assertThat(cancelled.get()).isInstanceOf(CancellationException.class); }
@Test public void testIfCancelled_callbackExceptionIgnored() { CompletableFuture<String> future = new CompletableFuture<>(); future.cancel(false); Utils.ifCancelled(future, e -> {throw new NullPointerException();}); assertThat(future.isCancelled()).isTrue(); }