对可完成未来的测试总是通过

Test on completable future always passing

我有以下测试应该总是失败:

@Test
public void testCompletable() {
    CompletableFuture.completedFuture(0)
        .thenAccept(a -> {
            org.junit.Assert.assertTrue(1==0);
        });
}

而且这个测试总是成功的。我怎样才能使这个测试正确失败?

可以这样做:

@Test
public void testCompletable() throws Exception {
    CompletableFuture completableFuture = CompletableFuture.completedFuture(0)
        .thenAccept(a -> Assert.fail());
    // This will fail because of Assert.fail()
    completableFuture.get();
}

您永远不会尝试检索可完成未来的结果。

completedFuture(0) will return a completable future that is already completed with a result of 0. The consumer added with thenAccept 将被调用并将 return 一个新的可完成的未来。您可以通过在其中放置打印语句来验证它是否被调用:

CompletableFuture.completedFuture(0)
.thenAccept(a -> {
    System.out.println("thenAccept");
    org.junit.Assert.assertTrue(1==0);
});

这将在控制台中打印 "thenAccept"。然而,这个新的可完成未来异常完成,因为 Assert.assertTrue 抛出异常。这并不意味着将异常抛给调用者:它只是意味着我们现在处理一个异常完成的可完成未来。

所以当我们尝试检索值时,调用者将出现异常。使用 get(), a ExecutionException will be thrown and with join(),将抛出 CompletionException。因此,以下

CompletableFuture.completedFuture(0)
.thenAccept(a -> {
    org.junit.Assert.assertTrue(1==0);
}).join();

会失败。