如何在 Junit 断言中显示所有失败

How to show all the failures in Junit Assertions

我的要求是在Junit测试后显示所有的失败运行。

我尝试了两件事:

Assertions.assertEquals --> 这会在第一次失败后停止执行,在测试报告中我只看到第一次失败。

Assertions.assertEquals(expceted, actual,"Error Message");

assertj.SoftAssertions --> 这里执行了但在测试报告中我没有看到任何失败消息。

SoftAssertions softAssertions = new SoftAssertions();
softAssertions.assertThat(expected).withFailMessage("Error Message", actual) ;
                   

任何其他类型的断言或我可以与这些断言一起使用的任何其他选项的任何想法?

我试过 Junit5 assertAll

for (int index = 0; index < response1.row.size(); index++)
        {
            int finalIndex = index;
            Assertions.assertAll(
                    () ->Assertions.assertEquals(Response1.row.get(finalIndex).field1, Response2.row.get(finalIndex).field1,
                            "Value doesn't match between source and target"),
                    () ->Assertions.assertEquals(Response1.row.get(finalIndex).field2, Response2.row.get(finalIndex).field2,
                            "Value doesn't match between source and target"),
                    () ->Assertions.assertEquals(Response1.row.get(finalIndex).field3, Response2.row.get(finalIndex).field3,
                            "Value doesn't match between source and target")
        }

但这里只显示第一行的失败,而不是所有行的失败。

提前致谢!!!

添加了 JUnit 5 assertAll:

assertAll(
        () -> assertEquals(...),
        () -> assertTrue(...)
        // etc
);

它需要任意数量的 lambda,如果我没记错的话,每个 lambda 甚至可以抛出异常。这意味着您可以委托给方法:

assertAll(
        ...
        complexAssertion(...)
);

...

private void complexAssertion(...) throws IOException {
    String expectedOutput = <read resource>;
    SomeException thrown = assertThrows(SomeException.class, () -> ...);
    assertInstanceOf(SomeOtherException.class, thrown.getCause());
    // nested assertAll can also be used!
}

编辑:在 assertAll 中使用 assertAll,因为索引变得困难:

// assuming that response1.row and response2.row have equal sizes
assertAll(IntStream.range(0, reponse1.row.size())
        .mapToObj(index -> () -> {
            assertAll(
                assertEquals(response1.row.get(index).field1, response2.row.get(index).field1, "message");
                // etc
            );
        })
);

mapToObj 可能需要强制转换为 Execution,可能需要提取到另一种方法。