0
0
JUnittesting~10 mins

Builder pattern for test data in JUnit - Test Execution Trace

Choose your learning style9 modes available
Test Overview

This test uses the Builder pattern to create a User object with test data. It verifies that the User object is built correctly with the expected name and age.

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

public class UserTest {

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

        private User(Builder builder) {
            this.name = builder.name;
            this.age = builder.age;
        }

        public String getName() {
            return name;
        }

        public int getAge() {
            return age;
        }

        public static class Builder {
            private String name;
            private int age;

            public Builder setName(String name) {
                this.name = name;
                return this;
            }

            public Builder setAge(int age) {
                this.age = age;
                return this;
            }

            public User build() {
                return new User(this);
            }
        }
    }

    @Test
    public void testUserBuilder() {
        User user = new User.Builder()
                .setName("Alice")
                .setAge(30)
                .build();

        assertEquals("Alice", user.getName());
        assertEquals(30, user.getAge());
    }
}
Execution Trace - 8 Steps
StepActionSystem StateAssertionResult
1Test startsJUnit test runner is ready-PASS
2Creates User.Builder instanceBuilder object with default null name and age 0-PASS
3Calls setName("Alice") on BuilderBuilder object with name = "Alice", age = 0-PASS
4Calls setAge(30) on BuilderBuilder object with name = "Alice", age = 30-PASS
5Calls build() to create User objectUser object created with name = "Alice", age = 30-PASS
6Assert user.getName() equals "Alice"User object with name = "Alice"user.getName() == "Alice"PASS
7Assert user.getAge() equals 30User object with age = 30user.getAge() == 30PASS
8Test ends successfullyTest passed-PASS
Failure Scenario
Failing Condition: Builder sets incorrect age value or name is null
Execution Trace Quiz - 3 Questions
Test your understanding
What does the Builder pattern help with in this test?
ARunning the test faster
BAutomatically generating test reports
CCreating User objects step-by-step with clear values
DFinding elements on a web page
Key Result
Using the Builder pattern for test data helps create clear, readable, and flexible test objects. It avoids long constructors and makes tests easier to maintain.