0
0
JUnittesting~15 mins

assertAll for grouped assertions in JUnit - Build an Automation Script

Choose your learning style9 modes available
Verify multiple properties of a User object using grouped assertions
Preconditions (2)
Step 1: Create a User object with name 'Alice', age 30, and email 'alice@example.com'
Step 2: Use assertAll to verify the following:
Step 3: - The name is 'Alice'
Step 4: - The age is 30
Step 5: - The email is 'alice@example.com'
✅ Expected Result: All assertions inside assertAll run and report failures together if any property does not match expected values
Automation Requirements - JUnit 5
Assertions Needed:
assertAll to group multiple assertions
assertEquals to check each property
Best Practices:
Use lambda expressions inside assertAll for lazy evaluation
Group related assertions logically
Avoid stopping test on first failure by using assertAll
Automated Solution
JUnit
import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.Test;

class User {
    private final String name;
    private final int age;
    private final String email;

    User(String name, int age, String email) {
        this.name = name;
        this.age = age;
        this.email = email;
    }

    String getName() { return name; }
    int getAge() { return age; }
    String getEmail() { return email; }
}

public class UserTest {

    @Test
    void testUserProperties() {
        User user = new User("Alice", 30, "alice@example.com");

        assertAll("User properties",
            () -> assertEquals("Alice", user.getName(), "Name should be Alice"),
            () -> assertEquals(30, user.getAge(), "Age should be 30"),
            () -> assertEquals("alice@example.com", user.getEmail(), "Email should be alice@example.com")
        );
    }
}

This test defines a simple User class with three properties: name, age, and email.

In the testUserProperties() method, we create a User object with expected values.

We use assertAll to group three assertions. Each assertion checks one property using assertEquals.

Using lambda expressions inside assertAll ensures all assertions run, and if any fail, JUnit reports all failures together.

This approach helps quickly see all mismatches without stopping at the first failure.

Common Mistakes - 3 Pitfalls
{'mistake': 'Using multiple assertEquals separately without assertAll', 'why_bad': "Test stops at first failure, so you don't see all failing assertions at once.", 'correct_approach': 'Use assertAll to group assertions so all run and report failures together.'}
Passing evaluated expressions instead of lambdas to assertAll
Not providing failure messages in assertions
Bonus Challenge

Now add a second User object with different properties and verify both users' properties using assertAll grouping.

Show Hint