private <T> CompletableFuture<T> delayedResult(final T t) { return CompletableFuture.supplyAsync(() -> { delay(); return t; }); }
@Test public void recoverWithSuccessInSecond() throws Exception { final CompletableFuture<String> future = failed(new RuntimeException()); final Function<Throwable, CompletionStage<String>> recoverFunction = e -> delayedResult("hi"); final CompletableFuture<String> recoveredFuture = recoverWith(future, recoverFunction); final String actual = recoveredFuture.join(); assertThat(actual).isEqualTo("hi"); }
@Test public void recoverWithSuccessInFirst() throws Exception { final String actual = recoverWithTestWithSuccessfulResult(successful("hello"), successful("hi")); assertThat(actual).isEqualTo("hello"); }
@Test public void sequence() { final CompletableFuture<Integer> two = delayedResult(2); final List<CompletableFuture<Integer>> completableFutures = asList(successful(1), two, successful(3)); final CompletionStage<List<Integer>> sequence = CompletableFutureUtils.sequence(completableFutures); final List<Integer> actual = sequence.toCompletableFuture().join(); assertThat(actual).isEqualTo(asList(1, 2, 3)); }
@Test public void sequenceErrorCase() { final RuntimeException exception = new RuntimeException("failed"); final List<CompletableFuture<Integer>> completableFutures = asList(delayedResult(1), failed(exception), successful(3)); final CompletableFuture<List<Integer>> sequence = CompletableFutureUtils.sequence(completableFutures); assertThatThrownBy(() -> sequence.join()).hasCause(exception); }