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

Patterns › Factory and data factories

Factory vs Builder and a Page Objects factory

A factory and a Builder both create test data but describe a variation differently. A factory takes parameters in one call, a Builder assembles the object in a chain of domain methods. The choice follows complexity: a literal, a factory, a Builder, moving up only when the current one becomes awkward. A Builder can take its defaults from a factory, and a Page Objects factory in Playwright is usually replaced by fixtures.

Patterns · Factory

A Builder or a factory: when is a three-line function enough and when do you need a class?

A team argues: write a Builder for every object because "it is correct", or get by with functions. Both approaches solve the same task, creating test data, but differ in cost and expressiveness. A separate question is a Page Objects factory: is an App class with getters needed if Playwright has fixtures. This lesson gives a rule for choosing and shows where each option is justified.

How it works and why. A Factory and a Builder differ in how the test describes a variation. A factory takes parameters in one call: createCard({ expiry }). A Builder assembles the object in a chain: .withItems(3).paid(). For one or two changed fields a factory is shorter. When variations and related fields are many (an order with a list of items, discounts and statuses), a chain with domain names reads better than an object with a dozen parameters. The data is the same here; what differs is who carries the complexity: the test or the class.

CriterionFactoryBuilder
Callone functiona chain of methods
Objectsimple or mediumcomplex, many variations
Domain languagethrough parametersthrough methods like paid()
Amount of codeminimalmore boilerplate

What to choose for data

A literal in the test1-3 fields, they are the checkA factory functiona medium object, a few variationsBuildermany fields and states, a domain language
Figure 1. Move up a step only when the current one has become inconvenient.

A default: a constant or a function

Wrong

A shared constant

One object for all tests. A test changes it and the next ones get spoiled data.

Right

A function that returns a new one

Every call gives a fresh object. One test mutating it harms nobody.

Figure 2. A factory always returns a new object.

Example: how they coexist. In practice they are combined: a Builder takes its defaults from a factory. Then defaults live in one place and the Builder adds only domain methods. Four important places are marked.

export class OrderBuilder {
1  private data: Order = defaultOrder();

2  withItems(n: number) {
    this.data.items = Array.from({ length: n }, () => defaultItem());
    return this;
  }

3  paid() {
    this.data.status = 'paid';
    return this;
  }

  build(): Order {
    return structuredClone(this.data);
  }
}

// defaults come from a factory: one source of truth
4const order = new OrderBuilder().withItems(3).paid().build();
  1. Defaults come from a factory: a single source of truth for a valid order.
  2. A method describes a variation that has a parameter: the number of items.
  3. A domain method for a state: paid() instead of withStatus('paid').
  4. The call reads as a description: an order with three items, paid.

A danger shared by both approaches is shown below. A factory that returns one constant instead of a new object makes tests depend on each other:

// one constant: a test changes it and the next ones see the change
export const DEFAULT_CARD: Card = { number: '4111111111111111', cvv: '123' };

test('mutates', async () => {
  DEFAULT_CARD.cvv = '000';
});

// a function: every call returns a new object
export const defaultCard = (): Card => ({ number: '4111111111111111', cvv: '123' });

The first variant works while no test changes the object. The longer a suite lives, the likelier somebody changes it. A function costs nothing, while this mistake shows up only with a particular execution order or a parallel run, when it is hard to find.

A Page Objects factory. Another meaning of the word: a class that creates Page Objects so that new is not written in every test.

export class App {
  constructor(private readonly page: Page) {}

  get login() {
    return new LoginPage(this.page);
  }

  get payments() {
    return new PaymentsPage(this.page);
  }
}

// dynamic: the page appeared inside the test
const [popup] = await Promise.all([
  page.waitForEvent('popup'),
  page.getByRole('link', { name: 'Help' }).click(),
]);
const help = new HelpPage(popup);

In Playwright this role is usually better played by fixtures: they are lazy, cleaned up after the test and typed (see the lesson on fixtures). A separate App class makes sense when pages must be created dynamically inside a test, for example after a new tab opens: we get a new page from the event and the page class is created from it, as in the second half of the example. A getter that creates a new object each time is safe, because a Page Object only holds lazy locators.

Limits and alternatives. A factory and a Builder are not needed if an object is used in one test and its fields are the point of the check: an explicit literal reads better (DAMP, "descriptive and meaningful phrases"). They should also not be added "just in case": a Builder class for a model that appeared yesterday and has three fields costs more than it gives. The right sequence: a literal; a factory once duplication becomes noise; a Builder once variations get complex.

Common mistakes.

  • A Builder for every model "by the rules": hundreds of lines of boilerplate for objects a literal would serve.
  • A factory with a long list of positional parameters (createUser(a, b, c, d, e)): the call cannot be read. Take one Partial object.
  • A shared constant instead of a function: one test's mutation poisons the others.
  • Merging data and side effects in one "factory": it both builds an object and calls the API, and it cannot be used without a network.
  • A separate Page Objects factory class that duplicates fixtures: two ways to do the same thing.

Check yourself

For a model with three fields used in two tests, a 60-line Builder is proposed. What do you advise?

Answer

A factory function with Partial or even a literal: for three fields a Builder costs more than it gives. A Builder is justified when fields and variations are many and a domain language (paid(), failed()) makes the test more expressive.

When does a separate Page Objects factory make sense despite fixtures?

Answer

When pages are created dynamically inside a test: for example, a click opened a new tab and the new page comes from the popup event. A fixture is created before the test, so for such a case the page class is created from the new page by hand or through a small App class.

In an interview. Junior: A Factory is one function for simple variations, a Builder is a fluent API for complex objects with a domain language. I usually replace a Page Objects factory in Playwright with fixtures. Middle/Senior: I choose by complexity: a literal, a factory, a Builder, and I move up a step only when the current one is inconvenient. A Builder takes defaults from a factory so there is one source of truth. A default is always a function returning a new object, never a constant. A separate page class is justified for dynamically created pages, such as a popup.

More articles in this chapter