0
0
JUnittesting~10 mins

Object Mother pattern in JUnit - Test Execution Trace

Choose your learning style9 modes available
Test Overview

This test uses the Object Mother pattern to create a ready-to-use User object. It verifies that the User object created by the Object Mother has the expected default values.

Test Code - JUnit 5
JUnit
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;

class User {
    private String name;
    private int age;

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

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }
}

class UserObjectMother {
    public static User createDefaultUser() {
        return new User("Alice", 30);
    }
}

public class UserTest {

    @Test
    void testDefaultUserCreation() {
        User user = UserObjectMother.createDefaultUser();
        assertEquals("Alice", user.getName());
        assertEquals(30, user.getAge());
    }
}
Execution Trace - 5 Steps
StepActionSystem StateAssertionResult
1Test startsJUnit test runner initializes the test class UserTest-PASS
2Calls UserObjectMother.createDefaultUser() to get a User objectUser object with name 'Alice' and age 30 is created-PASS
3Calls user.getName() and asserts it equals 'Alice'User object is accessible with name 'Alice'assertEquals("Alice", user.getName())PASS
4Calls user.getAge() and asserts it equals 30User object is accessible with age 30assertEquals(30, user.getAge())PASS
5Test completes successfullyAll assertions passed-PASS
Failure Scenario
Failing Condition: UserObjectMother.createDefaultUser() returns a User with incorrect name or age
Execution Trace Quiz - 3 Questions
Test your understanding
What does the Object Mother pattern help with in this test?
AAutomatically generating test reports
BRunning tests faster by skipping assertions
CCreating ready-to-use test objects with default values
DMocking external services
Key Result
Using the Object Mother pattern helps create consistent test objects easily, reducing duplication and making tests clearer.