QA Interview Hub · Knowledge base · Quizzes · Українська

Patterns

Builder and Test Data Builder

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

Wrong

A 14-field literal in the test

What matters drowns in noise. A new required field means an edit in every test.

Right

A builder with defaults

The test shows only deviations from the norm. A new field is added in one place, the builder.

Figure 1. The test names the significant fields, the builder knows the rest.

One builder chain

new PaymentBuilder()every field valid by default.withAmount(0)only what matters to the test is changed.failed()domain language instead of withStatus.build()a copy: the next call will not mutate this one
Figure 2. Valid defaults, changes only to what matters, a copy of the data on output.

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);
  }
}
  1. Defaults live in an instance field: every new gets its own object.
  2. All values are valid: without any with… call the object passes API validation.
  3. A method changes one field and returns this: this is the fluent chain.
  4. 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.

In an interview. Junior: A builder gives a valid object by default and the test changes only the fields that matter for the scenario. So the test reads better, and I add a new required field in one place. Middle/Senior: A builder separates data into important and irrelevant: the important ones are visible in the test, the builder knows the rest. I create defaults per instance, build() returns a deep copy, and domain methods like failed() replace withStatus. I do not put validation in the builder because negative tests need invalid data. For two or three fields a factory with Partial is enough.

A Builder with faker, determinism and when a Builder is unnecessary

Faker in a builder is needed first of all for uniqueness of data across tests and workers, not for realism. Defaults are created per instance, and values the test asserts on are set explicitly. To reproduce a failure the faker.seed value is written to the report, but one seed for the whole run brings the conflicts back. For an object with two or three fields a Builder is unnecessary.

Patterns · Test Data Builder

A test failed on a name with an apostrophe, and on rerun the data is different. How to reproduce the failure?

A builder with random defaults works well under a parallel run: every test gets a unique user and does not conflict with its neighbours. But randomness has a cost. In an overnight run a bug vanished because the name O'Brien was not generated again, and the investigation came down to the words "it happened once". This lesson shows how to keep random data under control, when faker is needed and when a Builder is not needed at all.

How it works and why. The @faker-js/faker library generates plausible values: names, emails, addresses. Its main benefit in this context is not realism but uniqueness: two tests in different workers will not create two users with the same email, and building data needs no coordination. A fixed email in a builder would give an "already registered" conflict in the second test. The main risk is non-reproducibility: a test that fails only on some values must be rerunnable with the same ones.

Where the default lives

Wrong

A module constant

One email for the whole worker. The second test gets the same one and the system answers that such a user already exists.

Right

A class field

The value is created on every new. Each test has its own user.

Figure 1. Defaults must be created per instance, not per module.

Why a seed is needed

Run 1: seed 481516name "O’Brien": the test is redRerun without a seedanother name: green, the bug vanishedRerun with SEED=481516the same name: red, the bug is visible
Figure 2. A seed recorded in the report turns “it happened once” into a repeatable bug.

Example: a builder on faker. The starting point: defaults made a module constant, supposedly "to be more economical".

// one email for the whole worker: the second test gets "already registered"
const DEFAULT_USER = {
  email: faker.internet.email(),
  firstName: faker.person.firstName(),
};

export class UserBuilder {
  private data = { ...DEFAULT_USER };
  // ...
}

The constant is evaluated once when the module loads. All tests of a worker share the same email and their independence is gone. The fix is a class field. Four important places are marked.

import { faker } from '@faker-js/faker';

export class UserBuilder {
  // a class field: a new value on every new UserBuilder()
1  private data: NewUser = {
2    email: faker.internet.email({ provider: 'example.com' }),
    firstName: faker.person.firstName(),
    password: 'Str0ng!Pass',
  };

3  withEmail(email: string) {
    this.data.email = email;
    return this;
  }

4  build(): NewUser {
    return { ...this.data };
  }
}
  1. A class field is evaluated when an instance is created, so every new gives new values.
  2. The domain example.com is reserved for examples: test emails do not reach real mailboxes. Without the parameter faker takes real mail services.
  3. A test that checks the email sets it explicitly: withEmail.
  4. build() returns a copy so the builder can be reused.

Faker does not fit values the check depends on. If a test checks an amount or a field length, the value is set explicitly and not taken from a generator: otherwise the test checks a random number and fails only sometimes.

Reproducibility. faker.seed(n) makes the sequence of values deterministic: with the same seed and library version the same calls give the same values. That is why the seed is written into the report: then a failure is reproduced with a command that has SEED=….

export const test = base.extend<{ seed: number }>({
  seed: [
    async ({}, use, testInfo) => {
      const seed = Number(process.env.SEED) || Math.floor(Math.random() * 1e9);
      faker.seed(seed);
      // the seed is visible in the report: a failure can be reproduced
      testInfo.annotations.push({ type: 'seed', description: String(seed) });
      await use(seed);
    },
    { auto: true },
  ],
});

Here an auto fixture sets a new random seed before each test and writes it into the report annotations. A failure is reproduced by running only the failed test with its seed: SEED=… npx playwright test -g "test name". The reason for the limit: the fixture calls faker.seed before every test, so with a fixed SEED every test, in one worker or in several, generates the same users and collides on exactly the conflict faker was meant to remove. The values also depend on the faker version, so after a library upgrade an old seed may produce other data.

Limits and alternatives. A builder is not always needed. For an object with two or three fields a function with Partial is enough:

// two or three fields: a function with Partial instead of a class
export const makeUser = (o: Partial<NewUser> = {}): NewUser => ({
  email: 'qa+' + crypto.randomUUID() + '@example.com',
  password: 'Str0ng!Pass',
  ...o,
});

const user = makeUser({ email: 'dup@example.com' });

In TypeScript the object spread (...o) does much of what needs a Builder in Java. In an interview exactly this awareness sounds good, not "I make builders everywhere". Uniqueness does not always need faker: crypto.randomUUID() gives a unique value without a dependency, but a name made from it is unreadable. Faker is justified when data must look real (long names, diacritics, apostrophes), because such values catch form bugs.

Common mistakes.

  • Defaults in a module constant: all tests get one user and parallel runs conflict.
  • A random value in a field the test checks: the test fails only on some values and the cause is hard to find.
  • Generated data not logged and no seed: a failure that showed once cannot be reproduced.
  • A fixed seed for the whole run: every test, even in one worker, generates the same "unique" values and conflicts return.
  • Faker with real mail domains: test emails go to other people's mailboxes. Use example.com.

Check yourself

A builder creates a user with faker.internet.email() in a class field. A test failed on a specific value. How to guarantee that a rerun gives the same data?

Answer

Record the seed: call faker.seed(seed) before the test and print the seed into the report or annotations, and on rerun pass the same seed. Without a record, random values cannot be reproduced. Rerun only this test: with a fixed seed every test generates the same data.

For an object with two fields a developer wrote a 40-line Builder class. What to replace it with and why?

Answer

A function with Partial: makeUser({ email }). It is shorter and fully typed, and a spread with overrides gives the same as fluent methods. A Builder is justified for objects with many fields and variations where a domain language is needed.

In an interview. Junior: For unique fields I use faker, and values the test checks I set explicitly. I log the data so a failure can be reproduced. For simple objects I take a factory function with Partial, because a Builder is excessive there. Middle/Senior: Defaults per instance, not per module. I write the seed into the report and can repeat a failure with SEED, running only the failed test: with one seed for the whole run the tests collide again. I use a reserved domain for emails. A Builder is justified only for complex objects with domain methods.