Search code examples
completable-futureassertj

Idiomatic way of comparing results of two completableFutures with assertj


There are 2 completable futures cf1 and cf2 defined as follows:

CompletableFuture<Boolean> cf1 = CompletableFuture.completedFuture(true);

CompletableFuture<Boolean> cf2 = CompletableFuture.completedFuture(true);

Technically, one could do:

var result1 = cf1.get();
var result2 = cf2.get();

assertThat(result1).isEqualTo(result2);

For example, if there was only one future, we could do the following:

assertThat(cf1)
    .succeedsWithin(Duration.ofSeconds(1))
    .isEqualTo(true);

Is there a more idiomatic way to compare the two futures against each other? Note that while the example here uses CompletableFuture<Boolean>, the Boolean can be replaced with any class.


Solution

  • What about composing the two futures into one that completes successfully with a value of true if and only if both individual futures complete successfully with the same value? You could e.g. use thenCompose followed by thenApply:

    CompletableFuture<Boolean> bothEqual = cf1.thenCompose(b1 -> cf2.thenApply(b2 -> b1 == b2));
    

    If the sequential execution from this solution is problematic, you can parallelize by implementing a helper function alsoApply and use that one instead of thenCompose. See this answer for more details.