Test Data Builder: the problem and the solution
A Test Data Builder holds an object with valid defaults and lets you change only what matters for the scenario. The test shows only the difference, not noise. Defaults are created per instance, build() returns a copy, and domain methods such as failed() are more expressive than withStatus. There is no validation in build(), because negative tests need invalid data.
Patterns · Test Data Builder
A payment has fourteen fields, and a test cares about two. How many lines does every test need?
A payment in a fintech system has an amount, a currency, accounts, a status, dates, a risk score and metadata. A test for a zero amount cares only about amount, but without the other fields the request will not pass validation. If every test assembles the object by hand, there are thirteen lines of noise around one important one. And when the API adds a new required field, all tests turn red at once. A Test Data Builder solves both problems: this lesson explains how it is built and why its API is the way it is.
How it works and why. A builder holds an object with valid default values and lets you change only what matters for the scenario. The idea is to split data into important and irrelevant. The test names the important ones explicitly (withAmount(0), failed()), and the irrelevant ones stay with the builder. Then the reader immediately sees what is being checked: the data in a test carries information, not noise. A method returns this, so calls compose into a chain, and build() returns the finished object.
How much a test knows about an object
A 14-field literal in the test
What matters drowns in noise. A new required field means an edit in every test.
A builder with defaults
The test shows only deviations from the norm. A new field is added in one place, the builder.
One builder chain
Example: from a literal to a builder. The starting point: the test knows all the fields.
test('zero amount is rejected', async ({ request }) => {
const payment: Payment = {
amount: 0,
currency: 'EUR',
status: 'pending',
from: 'UA001',
to: 'UA002',
riskScore: 10,
// …eight more fields the test does not care about
};
const res = await request.post('/api/payments', { data: payment });
expect(res.status()).toBe(422);
});
The test checks a zero amount, but the code does not show it: among six fields you have to look for the difference by eye. And if the API adds a required field, it has to be written into every such test so that the request passes validation. Now the same as a builder. Four important places are marked.
export class PaymentBuilder {
// a new object for every builder instance
1 private data: Payment = {
2 amount: 100,
currency: 'EUR',
status: 'pending',
from: 'UA001',
to: 'UA002',
riskScore: 10,
};
withAmount(amount: number) {
this.data.amount = amount;
3 return this;
}
failed() {
this.data.status = 'failed';
return this;
}
build(): Payment {
4 return structuredClone(this.data);
}
}
- Defaults live in an instance field: every
newgets its own object. - All values are valid: without any
with…call the object passes API validation. - A method changes one field and returns
this: this is the fluent chain. build()returns a copy: a repeated call does not return the same mutable object.
The test names only the difference:
test('zero amount is rejected', async ({ request }) => {
const payment = new PaymentBuilder().withAmount(0).build();
const res = await request.post('/api/payments', { data: payment });
expect(res.status()).toBe(422);
});
test('failed payment cannot be refunded twice', async ({ request }) => {
const payment = new PaymentBuilder().failed().build();
// ...
});
The first test reads as a description: "a payment with a zero amount". The second shows the domain language: failed() expresses intent better than withStatus('failed'), because it hides the status string that may change. Named methods for key states make a test look like a description of a scenario.
Why build() returns a copy. If it returned the object itself, the next withAmount call would change an already issued payment, and a test holding it in a variable would break for no visible reason. structuredClone makes a deep copy, so nested objects and arrays are not shared either. A plain spread ({ ...this.data }) copies only the top level: a nested address would stay shared.
Limits and alternatives. A builder can deliberately produce invalid objects too: a zero amount, an empty account, a negative value. That is not a mistake but the purpose, because negative tests need exactly such data. So validation is not added to build(). A builder pays off for objects with many fields and many variations. It adds code: a class, methods, maintenance when the model changes. For an object with two or three fields a factory function with Partial is enough (see the lesson on factories). A mutable builder is simple, but it must not be shared between tests; if a shared "template" with branches is needed, make an immutable variant in which every with… returns a new builder.
Common mistakes.
- A builder for an object with two fields: more code than a literal with no gain in readability.
- Defaults invalid for the API: a test that called no
with…fails on validation and the cause is not obvious. - One builder instance shared by several tests: a change in one test leaks into another.
- Methods by mechanics (
withStatus('failed')everywhere) instead of domain names: when the status encoding changes, the edit touches all tests. - Validation and business logic in
build(): negative tests cannot create an invalid object.
Check yourself
A builder keeps defaults in a module static constant: const DEFAULTS = { amount: 100, … }, the with… methods change DEFAULTS itself, and build() returns it. What goes wrong?
Answer
All builder instances share one object. A change made in one test stays in the constant and reaches the following ones. Defaults must be created for every instance (a class field) and returned as a copy from build().
Why should a builder not validate the object in build()?
Answer
Negative tests need invalid data: a zero amount, an empty account, a too long string. If the builder does not let you create them, you have to bypass it with a literal and the benefit is gone. The check belongs to the system under test.