import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
public class UserTest {
@Test
void testUserBuilderCreatesCorrectUser() {
User user = new User.Builder()
.name("Alice")
.age(30)
.email("alice@example.com")
.build();
assertEquals("Alice", user.getName(), "User name should be Alice");
assertEquals(30, user.getAge(), "User age should be 30");
assertEquals("alice@example.com", user.getEmail(), "User email should be alice@example.com");
}
}
// User class with Builder pattern
class User {
private final String name;
private final int age;
private final String email;
private User(Builder builder) {
this.name = builder.name;
this.age = builder.age;
this.email = builder.email;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public String getEmail() {
return email;
}
public static class Builder {
private String name;
private int age;
private String email;
public Builder name(String name) {
this.name = name;
return this;
}
public Builder age(int age) {
this.age = age;
return this;
}
public Builder email(String email) {
this.email = email;
return this;
}
public User build() {
return new User(this);
}
}
}This test uses the Builder pattern to create a User object with specific attributes.
The User.Builder class allows setting each attribute step-by-step, making the test data creation clear and flexible.
Assertions check that the User object has the expected name, age, and email.
Each assertion includes a message to help understand failures.
This approach keeps the test clean and focused on verifying the builder functionality.