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());
}
}