简体   繁体   English

为什么我的 `assertEquals` 语句没有全部显示?

[英]Why aren't my `assertEquals` statements all displaying something?

The following is a snippet from my JUnit5 test class.以下是我的 JUnit5 测试 class 的片段。

@Test
@DisplayName("This is just a simple JUnit 5 test")
void testSimple() {
    assertEquals(2, 3, "this is the 1st assertEquals");
    assertEquals(4, 5, "this is the 2nd assertEquals");
    assertEquals(5, 6, "this is the 3rd asswerEquals");
}

However, when I run this, I only manage to get the first assert statement to show the message.但是,当我运行它时,我只设法获得第一个断言语句来显示消息。 As all of them clearly fail, shouldn't they all be showing their respective messages?既然他们都明显失败了,他们不应该都展示各自的信息吗?

As highlighted in the comments section above, an exception is thrown if assertEquals fails.正如上面评论部分强调的那样,如果assertEquals失败,则会引发异常。 This prevents any following statements from being reached.这可以防止达到任何以下语句。

Normally, JUnit will not continue after the first failing test was encountered.通常,在遇到第一次失败的测试后,JUnit 将不会继续。 There are a few reasons for this, the most important (IMHO) are:这有几个原因,最重要的(恕我直言)是:

  • If one assertion fails, it's likely for the subsequent ones to fail as well.如果一个断言失败,那么随后的断言也可能失败。 Anyway, the whole test will be considered as failing.无论如何,整个测试将被视为失败。
  • Possible (but not mandatorily), your fist assertions can set up things for the following ones and/or check their prerequisites.可能的(但不是强制性的),您的第一个断言可以为以下断言设置事物和/或检查它们的先决条件。

If you need to continue your tests even after a failure, see here for an answer showing how to achieve this.如果您即使在失败后仍需要继续测试,请参阅此处以获取显示如何实现此目的的答案。

You can use assertAll to assert all tests together:您可以使用assertAll将所有测试断言在一起:

Assertions.assertAll(
            "heading",
            () -> assertEquals(2, 3, "this is the 1st assertEquals"),
            () -> assertEquals(4, 5, "this is the 2nd assertEquals"),
            () -> assertEquals(5, 6, "this is the 3rd assertEquals")
    );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM