当测试中某个断言失败时,JUnit 会停止执行后续断言。如果您希望确保所有断言都得到检查,而不管个别断言是否失败,请使用 assertAll() 对分组断言进行处理。

使用分组断言,即使断言失败,所有断言也会执行,并且错误消息会分组在一起,以便更好地进行调试:

@Test
@DisplayName("Validate person properties")
void validatePersonProperties() {
    Person person = new Person("John", "Doe", 30);

    assertAll("person properties",
        () -> assertEquals("John", person.getFirstName(), "First name should match"),
        () -> assertEquals("Doe", person.getLastName(), "Last name should match"),
        () -> assertTrue(person.getAge() > 0, "Age should be positive"),
        () -> assertNotNull(person.getEmail(), "Email should not be null")
    );
}

如果这些测试失败,结果将显示所有失败项:

=> org.opentest4j.MultipleFailuresError: person properties (2 failures)
expected: <John> but was: <null>
expected: <null> but was: <test@example.com>
Logo

汇聚全球AI编程工具,助力开发者即刻编程。

更多推荐