JUnit 5 – assertAll

I gave a half day JUnit 5 workshop at DevNexus last week. When I covered assertAll(), an interesting piece of code came up. In JUnit 5, there is an assertAll() which runs all of the assertions it contains so you can see all of them that failed at once.  This replaces the need for AssertJ’s SoftAssertions.

So how many assertions do you think this will fail with?

@Test
public void all() {
  assertAll("message", () -> {
    assertEquals(1, 2);
    assertEquals(3, 4);
  });
}

The fact that this is a blog post should get you nice and suspicious. The answer is one:

org.opentest4j.MultipleFailuresError: message (1 failure)
expected: <1> but was: <2>

Why is this? Well, remember that assertAll takes a vararg of Executables (lambdas in this case.) However, the above code only has one lambda. So JUnit runs the two asserts in the same block which makes them happen sequentailly.

To fix this, you need to pass separate lambdas for each assertions.

@Test
public void all() {
  assertAll("message", 
	() -> assertEquals(1, 2), 
	() -> assertEquals(3, 4));
  }
}

Ah this one tells you about both failures.

org.opentest4j.MultipleFailuresError: message (2 failures)
expected: <1> but was: <2>
expected: <3> but was: <4>

Thanks to Steve Kiley for asking the question that led to this blog post!

Leave a Reply

Your email address will not be published. Required fields are marked *