0
0
JUnittesting~5 mins

Builder pattern for test data in JUnit

Choose your learning style9 modes available
Introduction

The builder pattern helps create test data step-by-step. It makes tests easier to read and change.

When you need to create complex test objects with many fields.
When you want to avoid repeating the same setup code in many tests.
When test data needs small changes for different test cases.
When you want your test code to be clear and easy to understand.
Syntax
JUnit
public class TestDataBuilder {
    private String name = "defaultName";
    private int age = 30;

    public TestDataBuilder withName(String name) {
        this.name = name;
        return this;
    }

    public TestDataBuilder withAge(int age) {
        this.age = age;
        return this;
    }

    public Person build() {
        return new Person(name, age);
    }
}

The builder class has methods to set each field.

Each method returns the builder itself to allow chaining calls.

Examples
This creates a Person with name Alice and age 25.
JUnit
Person person = new TestDataBuilder().withName("Alice").withAge(25).build();
This creates a Person with default values (name: defaultName, age: 30).
JUnit
Person defaultPerson = new TestDataBuilder().build();
Sample Program

This test class uses the builder to create Person objects with custom and default data. It checks that the fields are set correctly.

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

class Person {
    private final String name;
    private final int age;

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

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }
}

class TestDataBuilder {
    private String name = "defaultName";
    private int age = 30;

    public TestDataBuilder withName(String name) {
        this.name = name;
        return this;
    }

    public TestDataBuilder withAge(int age) {
        this.age = age;
        return this;
    }

    public Person build() {
        return new Person(name, age);
    }
}

public class PersonTest {

    @Test
    void testPersonWithCustomData() {
        Person person = new TestDataBuilder()
            .withName("Bob")
            .withAge(40)
            .build();

        assertEquals("Bob", person.getName());
        assertEquals(40, person.getAge());
    }

    @Test
    void testPersonWithDefaultData() {
        Person person = new TestDataBuilder().build();

        assertEquals("defaultName", person.getName());
        assertEquals(30, person.getAge());
    }
}
OutputSuccess
Important Notes

Use builder pattern to keep test setup clean and avoid duplication.

It is easy to add more fields to the builder as needed.

Summary

Builder pattern helps create test data clearly and flexibly.

It reduces repeated code in tests.

Use chaining methods to set fields step-by-step.