0
0
JUnittesting~5 mins

assertAll for grouped assertions in JUnit

Choose your learning style9 modes available
Introduction

assertAll helps check many things at once. It shows all errors together, not just the first one.

When testing multiple parts of one feature in a single test.
When you want to see all mistakes in one run, not stop at the first error.
When checking several values or conditions that belong together.
When you want clearer test reports with grouped checks.
Syntax
JUnit
assertAll("group name",
    () -> assertEquals(expected1, actual1),
    () -> assertTrue(condition),
    () -> assertNotNull(object)
);

Use lambda expressions () -> for each assertion inside assertAll.

The first argument is a name for the group of assertions.

Examples
Checks two things about numbers together.
JUnit
assertAll("numbers",
    () -> assertEquals(5, sum),
    () -> assertTrue(sum > 0)
);
Checks user name is not null and role is 'admin' in one group.
JUnit
assertAll("user checks",
    () -> assertNotNull(user.getName()),
    () -> assertEquals("admin", user.getRole())
);
Sample Program

This test checks four things about numbers and text together. If any fail, all failures show at once.

JUnit
import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.Test;

class SampleTest {
    @Test
    void testMultipleAssertions() {
        int a = 5;
        int b = 3;
        int sum = a + b;
        String text = "hello";

        assertAll("grouped assertions",
            () -> assertEquals(8, sum),
            () -> assertTrue(sum > 0),
            () -> assertEquals("hello", text),
            () -> assertNotNull(text)
        );
    }
}
OutputSuccess
Important Notes

assertAll runs all checks even if some fail.

Use it to save time and get full error info in one test run.

Summary

assertAll groups many assertions in one test.

It shows all failures together, not just the first.

Use lambda expressions for each check inside assertAll.