0
0
JUnittesting~5 mins

Object Mother pattern in JUnit

Choose your learning style9 modes available
Introduction

The Object Mother pattern helps create test objects easily and clearly. It avoids repeating code when making objects for tests.

When you need many test objects with similar data in different tests.
When creating test objects is complex and you want to keep tests simple.
When you want to avoid repeating object setup code in multiple test methods.
When you want to improve readability by naming common test objects clearly.
Syntax
JUnit
public class ObjectMother {
    public static YourObject createDefault() {
        return new YourObject("default", 1);
    }

    public static YourObject createWithName(String name) {
        return new YourObject(name, 1);
    }
}

Use static methods to create and return test objects.

Name methods clearly to describe the kind of test object they create.

Examples
This example shows two methods creating different User objects for tests.
JUnit
public class UserMother {
    public static User createDefaultUser() {
        return new User("Alice", 30);
    }

    public static User createTeenUser() {
        return new User("Bob", 15);
    }
}
Using the Object Mother to get a default user in a test.
JUnit
User user = UserMother.createDefaultUser();
assertEquals("Alice", user.getName());
Sample Program

This test class uses the Object Mother pattern to get User objects for tests. It checks the name and age without repeating object creation code.

JUnit
import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.Test;

class User {
    private String name;
    private int age;

    public User(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }
}

class UserMother {
    public static User createDefaultUser() {
        return new User("Alice", 30);
    }

    public static User createTeenUser() {
        return new User("Bob", 15);
    }
}

public class UserTest {
    @Test
    void testDefaultUserName() {
        User user = UserMother.createDefaultUser();
        assertEquals("Alice", user.getName());
    }

    @Test
    void testTeenUserAge() {
        User teen = UserMother.createTeenUser();
        assertTrue(teen.getAge() < 20);
    }
}
OutputSuccess
Important Notes

Object Mother helps keep tests clean and easy to read.

Do not put test logic in Object Mother methods; only create objects.

Use descriptive method names to clarify what kind of object is created.

Summary

Object Mother creates ready-to-use test objects.

It reduces repeated setup code in tests.

Helps tests stay simple and clear.