Automate test using Object Mother pattern for User creation
Preconditions (3)
✅ Expected Result: createUser() returns true for the valid User object created by Object Mother
import static org.junit.jupiter.api.Assertions.assertTrue; import org.junit.jupiter.api.Test; class User { private int id; private String name; private String email; public User(int id, String name, String email) { this.id = id; this.name = name; this.email = email; } // getters omitted for brevity } class UserService { public boolean createUser(User user) { // Simulate user creation logic if (user == null) return false; if (user.email == null || user.email.isEmpty()) return false; return true; } } class UserObjectMother { public static User validUser() { return new User(1, "John Doe", "john.doe@example.com"); } } public class UserServiceTest { @Test void testCreateUserWithValidUser() { UserService userService = new UserService(); User user = UserObjectMother.validUser(); boolean result = userService.createUser(user); assertTrue(result, "User creation should succeed with valid user"); } }
This test uses the Object Mother pattern to create a valid User object with UserObjectMother.validUser(). This keeps test data creation separate and reusable.
The UserService.createUser() method is called with this user. The test asserts that the result is true, meaning the user was created successfully.
Using @Test marks the test method for JUnit 5. The assertion assertTrue checks the expected outcome.
This approach keeps the test clean, focused, and easy to maintain.
Now add data-driven testing with 3 different User objects using Object Mother
Object Mother pattern in JUnit testing?User object?public static so tests can call them without creating an instance.User object with fixed data, matching the pattern.public static Order createOrder() {
return new Order("123", 5, 100.0);
}@Test
void testOrderTotal() {
Order order = ObjectMother.createOrder();
assertEquals(500.0, order.getTotal());
}public static Product createProduct() {
Product p = new Product();
p.setName("Laptop");
return p;
p.setPrice(1200);
}return p; line ends the method, so code after it is unreachable.p.setPrice(1200); after return will never run, causing a compile warning or error.User objects: one active, one inactive, and one admin. How should you design your Object Mother class to best support this?Pass the test and this pattern moves unknown