Video in progress

Strong Middle 🧭 Design patterns

How do you use the Test Data Builder and Object Mother patterns to create objects in tests?

An Object Mother gives you ready-made samples: Orders.paidOrder(). A Test Data Builder starts from sensible defaults, and the test changes only the field that matters to it. I prefer the builder, because the test shows only what it is actually checking.

📖 Answer

The problem is familiar: at the start of every test there are 25 lines of new Order(...), setCustomer(...), setAddress(...). Add one required field to the constructor and 140 tests stop compiling. Worst of all, what the test is checking gets lost in that noise.

An Object Mother is a factory of ready-made objects:

class Orders {
    static Order paidOrder() { ... }
    static Order cancelledOrder() { ... }
}

It's convenient at first, but every new case adds a new method: paidOrderWithDiscountFromTashkent(). A year later there are 60 methods and nobody dares use them.

Test Data Builder:

class OrderBuilder {
    private Customer customer = aCustomer().build();
    private OrderStatus status = OrderStatus.NEW;
    private List<OrderLine> lines = List.of(aLine().build());

    static OrderBuilder anOrder() { return new OrderBuilder(); }
    OrderBuilder paid() { this.status = OrderStatus.PAID; return this; }
    OrderBuilder withLines(OrderLine... l) { this.lines = List.of(l); return this; }
    Order build() { return new Order(customer, status, lines); }
}

var order = anOrder().paid().withLines(aLine().price("120000").build()).build();

Whoever reads the test sees right away what matters: the paid state and the price of one line. Everything else is "some valid value".

Practical rules: defaults should always produce a valid object; the builder lives in test code, not in the production class; and combining the two patterns is fine, with the Object Mother returning a builder (Orders.paid() → OrderBuilder) that the test then tweaks further.