Video in progress
How do you prepare data for tests, and what are test data builders and the Object Mother approach for?
Instead of assembling a big object by hand in every test, you use a builder or factory methods with default values: the test changes only the field that matters to it. That keeps tests short, and when a new required field is added, only one place changes.
📖 Answer
The problem: the Order constructor needs 12 arguments, and 80 tests have new Order(...). A new currency field is added, and you fix 80 places.
With a builder:
public class OrderBuilder {
private Long customerId = 1L;
private OrderStatus status = OrderStatus.NEW;
private List<OrderItem> items = List.of(new OrderItem("SKU-1", 1, new BigDecimal("10000")));
public static OrderBuilder anOrder() { return new OrderBuilder(); }
public OrderBuilder paid() { this.status = OrderStatus.PAID; return this; }
public OrderBuilder withItems(OrderItem... items) { this.items = List.of(items); return this; }
public Order build() { return new Order(customerId, status, items); }
}
// the test shows only what matters
var order = anOrder().paid().build();
An Object Mother is a set of ready-made named objects: TestOrders.paidOrderWithTwoItems(). It's simple, but turns into dozens of methods as the variants multiply. In practice I use both together: a builder inside the Mother.
One more rule for integration tests: create the data inside the test, not in a big shared data.sql file. A shared file keeps growing, everyone edits it, and one test's needs break another's.
Random values (Instancio, Datafaker) are useful, just log the seed: you need to be able to reproduce a failing case.
Sign up to mark studied questions and save your progress.