0
0
JunitHow-ToBeginner ยท 3 min read

How to Use assertAll in JUnit for Grouped Assertions

Use 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.

java
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.

java
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)
        );
    }
}
Output
Test passed with all assertions successful.
โš ๏ธ

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.

java
/* 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...) or assertAll(Executable...).
  • Use lambdas: Wrap each assertion in () -> {}.
  • Benefit: See all assertion failures in one test run.
โœ…

Key Takeaways

Use assertAll to group multiple assertions and run them all together.
Wrap each assertion inside a lambda to ensure all execute.
assertAll reports all failures at once instead of stopping at the first failure.
Do not pass assertions directly; always use lambdas inside assertAll.
assertAll improves test feedback by showing all assertion results in one run.