CodePark/ questions / Databases, Testcontainers & test data
START PRACTICINGPRACTICE
Backend question · Backend testing › Databases, Testcontainers & test data

For test data, what is the difference between shared fixtures and factories or builders? Which do you prefer?

Prefer factories or builders for most tests. Keep shared fixtures only for stable reference data.

Shared fixtures are a fixed dataset that many tests load and reuse. Examples are a seed script or a JSON dump loaded before the tests. They are quick to start with. But the tests become coupled to the data, which means they depend on its exact values. For example, someone edits user 3 for a new test, and five unrelated tests break. Also, a reader can't see which values matter to a test.

Factories or builders are functions that create the data each test needs. They fill in sensible defaults, and the test overrides only what it cares about:

  • await createUser({ role: 'admin' })
  • anOrder().withItems(2).build()

With factories, each test:

  • shows the fields that matter to it
  • generates unique values for unique columns
  • stays independent of other tests

Keep fixtures for stable reference data the app needs, like countries or plans. If you use a fake-data library, give it a fixed seed, so a failing test produces the same data again and you can reproduce the failure.

  • Fixtures are shared, fixed data, and tests become coupled to that data.
  • Factories and builders create data per test, with defaults and overrides.
  • With factories, each test shows only the fields that matter to it.
  • Use fixtures for stable reference data, and seed any random data.