Introduction
The builder pattern helps create test data step-by-step. It makes tests easier to read and change.
The builder pattern helps create test data step-by-step. It makes tests easier to read and change.
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.
Person person = new TestDataBuilder().withName("Alice").withAge(25).build();
Person defaultPerson = new TestDataBuilder().build();
This test class uses the builder to create Person objects with custom and default data. It checks that the fields are set correctly.
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()); } }
Use builder pattern to keep test setup clean and avoid duplication.
It is easy to add more fields to the builder as needed.
Builder pattern helps create test data clearly and flexibly.
It reduces repeated code in tests.
Use chaining methods to set fields step-by-step.
Builder pattern for test data in JUnit tests?User object in JUnit?builder() on the class.User.builder().setName(...).build(). User user = User.builder().setName("Alice").build(); matches this.user.getAge()?
var user = User.builder()
.setName("Bob")
.setAge(30)
.setAge(25)
.build();
setAge(25) overwrites previous age, so final age is 25.Product test data:
var product = Product.builder()
.setName("Book")
.setPrice(-10)
.build();
setName, setPrice, then build() correctly.Order test objects with different status but same customerId and amount. How can you best use the Builder pattern to avoid repeating common fields?Pass the test and this pattern moves unknown