0
0
JUnittesting~15 mins

Object Mother pattern in JUnit - Build an Automation Script

Choose your learning style9 modes available
Automate test using Object Mother pattern for User creation
Preconditions (3)
Step 1: Use Object Mother to create a valid User object
Step 2: Call createUser() method with the User object
Step 3: Verify that createUser() returns true indicating successful creation
✅ Expected Result: createUser() returns true for the valid User object created by Object Mother
Automation Requirements - JUnit 5
Assertions Needed:
Assert that createUser() returns true
Best Practices:
Use Object Mother pattern to create test data
Use @Test annotation for test method
Use assertTrue for assertion
Keep test method simple and focused
Automated Solution
JUnit
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.

Common Mistakes - 3 Pitfalls
Creating test data directly inside the test method instead of using Object Mother
Not using assertions to verify the result
Using JUnit 4 annotations or imports in a JUnit 5 project
Bonus Challenge

Now add data-driven testing with 3 different User objects using Object Mother

Show Hint