How to Use assertAll in JUnit for Grouped Assertions
assertAll in JUnit to group multiple assertions so they run together and report all failures at once. Wrap each assertion in a lambda inside assertAll to ensure all checks execute even if some fail.Syntax
The assertAll method takes a heading message (optional) and a list of executable assertions wrapped in lambdas. Each lambda contains one assertion. This lets JUnit run all assertions and report all failures together instead of stopping at the first failure.
assertAll("Heading message",
() -> assertEquals(expected1, actual1),
() -> assertTrue(condition),
() -> assertNotNull(object)
);Example
This example shows how to use assertAll to check multiple properties of a string. Even if one assertion fails, the others still run and all failures are reported together.
import static org.junit.jupiter.api.Assertions.*; import org.junit.jupiter.api.Test; class AssertAllExampleTest { @Test void testMultipleAssertions() { String text = "JUnit5"; assertAll("String properties", () -> assertEquals(6, text.length()), () -> assertTrue(text.startsWith("J")), () -> assertTrue(text.endsWith("5")), () -> assertNotNull(text) ); } }
Common Pitfalls
One common mistake is not using lambdas inside assertAll. If you pass assertions directly, only the first assertion runs and others are ignored. Always wrap each assertion in a lambda to ensure all run.
Another pitfall is expecting assertAll to stop on first failure; it actually runs all assertions and reports all failures together.
/* Wrong way - assertions run immediately, only first failure reported */ assertAll( () -> assertEquals(1, 2), () -> assertTrue(false) ); /* Right way - assertions wrapped in lambdas, all run */ assertAll( () -> assertEquals(1, 2), () -> assertTrue(false) );
Quick Reference
- Purpose: Group multiple assertions to run together.
- Syntax:
assertAll(String, Executable...)orassertAll(Executable...). - Use lambdas: Wrap each assertion in
() -> {}. - Benefit: See all assertion failures in one test run.