Course contentsShow
← Software Engineering
Lesson 451 of 1,93313. Unit Testing in DepthFree lesson

Object Mother Pattern

Using factory methods to create common test objects with sensible defaults in a centralized location.

Object Mother Pattern

What you'll learn: How to use factory methods in a centralized location to create common test objects with sensible defaults, reducing duplication and making tests easier to maintain.

The Problem with Test Data

You've learned about the challenges of test data setup. When writing multiple tests, you often need to create similar objects over and over. Imagine testing a ShoppingCart class—you might need a User, a Product, and maybe a PaymentMethod in dozens of different tests. Copy-pasting this setup everywhere creates maintenance nightmares: if User requires a new mandatory field, every single test breaks.

What is the Object Mother Pattern?

The Object Mother is a pattern where you create a dedicated class (or set of classes) containing factory methods that build common test objects with reasonable default values. Think of it as a "nursery" that knows how to create all the test data babies your tests need, already dressed and ready to go.

Instead of writing:

const user = { id: 1, name: "Test User", email: "test@example.com", verified: true };

...in every test, you call:

const user = ObjectMother.createUser();

The Object Mother handles all the boilerplate. Need a specific variant? Add parameters:

const unverifiedUser = ObjectMother.createUser({ verified: false });

Benefits

  • Centralized defaults: Change default test data in one place
  • Less duplication: Tests become shorter and clearer
  • Consistency: All tests use similar, valid objects
  • Flexibility: Override specific properties when needed

Key Takeaway: The Object Mother pattern creates reusable factory methods for common test objects, keeping your tests DRY and making them resilient to changes in your data structures.