【问题标题】:junit 5 run all assert even if there is failed onejunit 5 运行所有断言,即使有一个失败
【发布时间】:2020-07-16 07:30:27
【问题描述】:

即使中间的断言失败,JUnit 5 中是否有任何机制可以在测试中运行所有断言? 例如:

@Test
public void unitForTest_SomeScenario_ShouldReturn() {

    //Act
    var myObj = myServ.getMyObj();
    //Arrange
    assertThat(myObj).isNotNull();
    assertThat(myObj.getName()).isEqualTo("Steve"); //failed assert
    assertThat(myObj.getLastName()).isEqualTo("Gates");
}

我的意图是运行所有断言,并且跟踪失败的只是第二个,而不是第三个和第一个。

【问题讨论】:

  • 您创建了三个独立的测试用例。
  • @Joe 不,抱歉这个问题没有回答我的问题,因为我想使用 JUnit 5 的可能性,而且我知道有类似 glything 的提议
  • @Joe 提出一个 JUnit 4 问题作为 JUnit 5 问题的副本没有多大意义。
  • @Joe 规则在 JUnit 5 中不再存在,因此ErrorCollector 解决方案不再起作用。 JUnit5 中的内置选项是Assertions.assertAll,这些答案均未涵盖。

标签: java junit junit5


【解决方案1】:

您可以使用 JUnit5 的 assertAll

例如:

@Test
public void unitForTest_SomeScenario_ShouldReturn() {
    String name = "y";
    assertAll(
            () -> assertThat(name).isNotNull(),
            () -> assertThat(name).isEqualTo("x"), // failed assert
            () -> assertThat(name).isEqualTo("y"),
            () -> assertThat(name).isEqualTo("z") // failed assert
    );
}

将失败并提供以下详细响应:

Expecting:
 <"y">
to be equal to:
 <"x">
but was not.
Comparison Failure: 
Expected :x
Actual   :y
<Click to see difference>


Expecting:
 <"y">
to be equal to:
 <"z">
but was not.
Comparison Failure: 
Expected :z
Actual   :y
<Click to see difference>

org.opentest4j.MultipleFailuresError: Multiple Failures (2 failures)

注意:由于您的问题中的某些 cmets 暗示,这可能可以通过使用单独的测试(而不是一个具有多个断言的测试)更好地表达,但是,只要多个断言是一个单一的“概念断言”,那么我肯定可以看到使用 assertAll 的案例。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-31
    • 1970-01-01
    • 1970-01-01
    • 2015-01-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多