How-To Guide

How to Design Test Data Builders

Build test data with builders: default every field, override only what matters, and keep the test focused on the behaviour under test.

On this page

  1. Introduction
  2. Default every field to a valid value
  3. Override narrowly in each test
  4. Compose related objects
  5. Keep the builder fixed, not random
  6. Test that the builder is valid and the test is focused
  7. Common pitfalls
  8. Conclusion

Introduction

A test that constructs its input inline must set every field the object requires, so most of the test is data that has nothing to do with the behavior it checks. When a field is added, every such test breaks, and the reader has to scan the whole object to find the one value the test is about. A test data builder fixes both: it produces a valid object with defaults, so the test sets only what matters, and a new field does not break existing tests.

This tutorial designs a builder: defaults for every field, a narrow override, composition of related objects, and readable tests. The examples use a builder in TypeScript, and the pattern applies in any language.

Default every field to a valid value

The builder starts from a complete, valid object with sensible defaults, so a test does not have to specify the fields it does not care about. Defaults are values that are valid and unremarkable, such as a name of ‘test’ or a count of one, chosen to be obviously placeholder so a reader knows the value is not the point of the test. The object the builder produces must pass the same validation the code applies, or the test fails for the wrong reason.

When a required field is added to the object, the builder adds a default for it, and existing tests do not break. This is the maintenance benefit: one place to update for a new field, not every test that happened to build the object. The builder is the single place that knows how to make a valid object.

interface User {
  id: number; email: string; role: 'user' | 'admin'; active: boolean; createdAt: Date;
}

function aUser(overrides: Partial<User> = {}): User {
  return {
    id: 1,
    email: '[email protected]',   // valid, obviously a placeholder
    role: 'user',
    active: true,
    createdAt: new Date('2026-01-01T00:00:00Z'),
    ...overrides,               // only the fields the test cares about
  };
}

Override narrowly in each test

The test calls the builder and overrides only the field that drives its expectation. A test of a role check overrides role to ‘admin’ and says nothing about the other fields, so the reader sees at a glance that the role is what the test is about. This is the readability the builder buys: the test states the one relevant value and inherits the rest.

Override through a named parameter or a method, so the intent is explicit. A builder with a fluent method such as aUser().withRole(‘admin’) reads as prose and documents the variation. Whatever the syntax, the test should make the relevant field stand out and leave the irrelevant ones invisible, which is what focuses the test on the behavior.

it('blocks a deactivated admin', () => {
  const user = aUser({ role: 'admin', active: false });   // only the relevant fields
  expect(canLogin(user)).toBe(false);                     // one expectation, one reason
});

it('allows a normal user', () => {
  const user = aUser();                                    // defaults are a valid user
  expect(canLogin(user)).toBe(true);
});

When the object under test has related objects, the builder builds them too, with their own defaults, so a nested object is valid without the test spelling it out. An order with a customer builds a default customer, and a test that varies the order varies only the order. This keeps the test shallow: the reader does not wade through a nested structure to find the relevant value.

Let the test override a related object when it matters, by passing the built related object into the parent builder. The composition is explicit and the related object’s defaults still apply. This is how a test that needs a specific customer gets one, while a test that does not gets a valid default customer without seeing it.

function anOrder(overrides: Partial<Order> = {}): Order {
  return {
    id: 1,
    customer: aCustomer(),      // a valid related object by default
    items: [anItem()],          // a valid list by default
    total: 100,
    ...overrides,
  };
}
// a test varying the item passes its own: anOrder({ items: [anItem({ qty: 0 })] })

Keep the builder fixed, not random

Use fixed defaults so a test is deterministic and its failure is reproducible. A builder that randomizes a field makes a failure depend on the run, so a failing test is hard to reproduce and a passing one may hide a bug. Randomness belongs in property-based tests, where a seed makes a run reproducible and the assertion is a property, not an exact value.

If a value must be unique, such as an id, generate it deterministically from a counter, so each built object gets a distinct id but the sequence is the same across runs. This gives uniqueness without losing reproducibility. A monotonically increasing counter within a test is deterministic and unique enough for most tests.

Test that the builder is valid and the test is focused

Test that the builder produces a valid object, by running the code’s own validation on the default output, so the builder cannot drift from the schema. Test that a test using the builder names only the relevant field, by reviewing the test for fields that are set but do not matter. Test that adding a field to the object is a one-line builder change, by adding a field and asserting existing tests still pass.

# the builder's default must satisfy the real validation
node -e '
const { aUser } = require("./builders");
const { validate } = require("./schema");
const errs = validate(aUser());
if (errs.length) throw new Error("builder default invalid: " + errs.join(","));
console.log("builder default is valid");
'

Common pitfalls

Building the object inline in every test so a new field breaks them all, a builder that randomizes a field so failures are not reproducible, defaults that fail the real validation so tests fail for the wrong reason, a builder that sets the very field the test is about so the test passes for the wrong reason, and a nested object spelled out in full instead of composed are the recurring mistakes. Defaults for every field, fixed values, valid defaults, narrow overrides, and composition address them.

Conclusion

A test data builder produces a valid object with defaults, so a test sets only the field it is about and a new field does not break every test. Default every field to a valid, unremarkable value, override narrowly, compose related objects, and keep the values fixed and valid. Self-check by asserting the default passes the real validation and that a new field is a one-line change. Then tests read as the one behavior each checks.

Sources: Martin Fowler: Object Mother and Test Data Builders, Growing Object-Oriented Software: Test data builders, xUnit Patterns: Test data builder.

FAQ

Why not construct the object inline?
An inline object must set every field, so the test is cluttered with values that do not matter and breaks whenever a required field is added. A builder sets the defaults once, so a test declares only the field it is about, and a new field does not break every test.
Should builders be random or fixed?
Fixed defaults, so a test is deterministic and its failure is reproducible. Randomness belongs in property-based tests with a seed, not in a builder a unit test uses, because randomness makes a failure hard to reproduce.

Related Examples