Create and verify a User object using Builder pattern
Preconditions (2)
✅ Expected Result: User object is created correctly with the specified attributes
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.
Now add data-driven testing with 3 different User inputs using JUnit 5 parameterized tests
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