微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

是否有 JUnit5 的 ErrorCollector 规则模拟

如何解决是否有 JUnit5 的 ErrorCollector 规则模拟

JUnit4 中有 ErrorCollector 规则,现在我们必须在迁移到 junit5 期间切换到扩展。此处描述了 ErrorCollector 的用法https://junit.org/junit4/javadoc/4.12/org/junit/rules/ErrorCollector.html junit5 中是否有类似的扩展?我在 assert-j https://www.javadoc.io/doc/org.assertj/assertj-core/latest/org/assertj/core/api/junit/jupiter/SoftAssertionsExtension.html 中找到了一个,但 JUnit 5 中是否仍然支持相同的内容作为扩展?

注意:我想在系统测试级别使用它。所以我会有 Step 1 -> assertion -> Step 2-> assertion->... assertAll 在我看来是更糟糕的选择,因为我必须存储验证值并在测试结束时断言它们,而不是在某些地方我从哪里得到这些值。

assertAll(() -> {{Some block of code getting variable2}
                    assertEquals({what we expect from variable1},variable1,"variable1 is wrong")},{Some block of code getting variable2}
        assertEquals({what we expect from variable2},variable2,"variable2 is wrong"),{Some block of code getting variable3}
        assertEquals({what we expect from variable3},variable3,"variable3 is wrong"));

这种方法看起来不清晰,看起来比这里描述的更糟糕https://assertj.github.io/doc/#assertj-core-junit5-soft-assertions

解决方法

木星的 aasertAll 最接近:https://junit.org/junit5/docs/current/user-guide/#writing-tests-assertions

它允许执行多个断言语句并一起报告它们的结果。例如:

@Test
void groupedAssertions() {
    // In a grouped assertion all assertions are executed,and all
    // failures will be reported together.
    assertAll("person",() -> assertEquals("Jane",person.getFirstName()),() -> assertEquals("Doe",person.getLastName())
    );
}
,

目前我认为最好的方法是像这样使用 assert-j

@ExtendWith(SoftAssertionsExtension.class)
public class SoftAssertionsAssertJBDDTest {

    @InjectSoftAssertions
    BDDSoftAssertions bdd;

    @Test
    public void soft_assertions_extension_bdd_test() {
        //Some block of code getting variable1
        bdd.then(variable1).as("variable1 is wrong").isEqualTo({what we expect from variable1});
        //Some block of code getting variable2
        bdd.then(variable2).as("variable2 is wrong").isEqualTo({what we expect from variable2});
        //Some block of code getting variable3
        bdd.then(variable3).as("variable3 is wrong").isEqualTo({what we expect from variable3});
        ...
    }
}

@ExtendWith(SoftAssertionsExtension.class)
public class SoftAssertionsAssertJTest {

    @Test
    public void soft_assertions_extension_test(SoftAssertions softly) {
        //Some block of code getting variable1
        softly.assertThat(variable1).as("variable1 is wrong").isEqualTo({what we expect from variable1});
        //Some block of code getting variable2
        softly.assertThat(variable2).as("variable2 is wrong").isEqualTo({what we expect from variable2});
        //Some block of code getting variable3
        softly.assertThat(variable3).as("variable3 is wrong").isEqualTo({what we expect from variable3});
        ...
    }
}

在一行中写许多带有验证的步骤看起来更容易理解

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。