The following is a snippet from my JUnit5 test 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?
CodePudding user response:
As highlighted in the comments section above, an exception is thrown if assertEquals
fails. This prevents any following statements from being reached.
CodePudding user response:
You can use assertAll to assert all tests together:
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")
);
CodePudding user response:
Normally, JUnit will not continue the test after the first failing assertion was encountered. 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 failed assiertion, see here for an answer showing how to achieve this. Anyway, the following other tests (new @Test
annotated methods) will continue to be executed anyway.
Edit:
Highlighted test vs. assertion difference.