Sub topic 1
Why test data becomes a problem
Every test needs data. A test for a login rule needs a user. A test for refunds needs an order that belongs to a customer. Most teams write this data casually at first, and it gradually becomes the most expensive part of the test suite to maintain. This chapter explains how that happens and what a fix would need to do. The later chapters build the fix, which is a test data factory.
Prerequisites
This chapter assumes you can:
- Write and run automated tests with a test runner such as pytest.
- Read Python classes and dataclasses. The examples use Python, but the problems apply in any language.
- Recognize a test fixture, meaning a setup step that prepares objects before a test runs.
Where the cost comes from
A test has three parts: setup (arrange), the action (act), and the check (assert). The test's intent lives in the action and the check. The setup is usually the longest part, and it tends to be the part where mistakes hide.
Setup grows for a simple reason. Real objects need many fields, and most of those fields are irrelevant to any single test. A User may need an id, an email, a role, and an active flag, but a test about login only cares about the active flag. The author still has to supply the other three values, because the object will not construct without them.
Teams tend to handle this in one of two ways, and each one fails in a different way.
Failure mode 1: Inline setup copied into every test
The first approach is to build every object by hand inside each test. Here is a small suite for a login rule:
from dataclasses import dataclass
@dataclass
class User:
id: int
email: str
role: str
active: bool
def can_log_in(user):
return user.active
def test_inactive_user_cannot_log_in():
user = User(id=1, email="[email protected]", role="member", active=False)
assert can_log_in(user) is False
def test_active_user_can_log_in():
user = User(id=2, email="[email protected]", role="member", active=True)
assert can_log_in(user) is True
def test_admin_can_log_in():
user = User(id=3, email="[email protected]", role="admin", active=True)
assert can_log_in(user) is TrueThis is readable at three tests. Two problems appear as the suite grows.
The signal is buried in noise. In test_inactive_user_cannot_log_in, the only meaningful value is active=False. The reader has to compare it with the next test to learn that. With 40 tests, the reader must compare 40 constructor calls to find what each one is about.
Schema changes break everything at once. Suppose the product adds a required locale field:
@dataclass
class User:
id: int
email: str
role: str
active: bool
locale: strEvery test that builds a User now fails with an error like TypeError: User.__init__() missing 1 required positional argument: 'locale'. None of the tests is wrong about its own behavior. Yet you must edit every one of them. In a suite with hundreds of constructor calls, a one-line product change turns into a day of mechanical edits. People make mistakes during that work, and some tests end up with a locale that changes what they check.
Failure mode 2: A shared fixture that everyone depends on
The second approach is to build one object up front and reuse it. It looks like it solves the repetition:
from dataclasses import dataclass
@dataclass
class User:
id: int
email: str
role: str
active: bool
def can_log_in(user):
return user.active
def deactivate(user):
user.active = False
SHARED_USER = User(id=1, email="[email protected]", role="member", active=True)
def test_deactivate_user():
deactivate(SHARED_USER)
assert SHARED_USER.active is False
def test_active_user_can_log_in():
assert can_log_in(SHARED_USER) is TrueEach test passes when run alone. Run them in file order and the second one fails, because the first test changed SHARED_USER and the change persisted. Run them in the opposite order and both pass. A test runner that shuffles order, or runs tests in parallel, makes this failure appear and disappear.
Shared fixtures cause four problems:
- Order dependence. A test's result depends on which tests ran before it.
- Action at a distance. The data is defined far from the test that uses it. Reading the test tells you nothing about the user's role or status.
- Pressure to widen the fixture. When one test needs an admin, someone adds an
ADMIN_USER. When another needs an inactive admin, someone addsINACTIVE_ADMIN_USER. The shared set keeps growing. - Changes ripple outward. Editing the shared object to suit a new test can break tests written months ago that nobody remembers.
Fixtures are not always wrong. Read-only reference data, such as a fixed list of country codes, works well as shared setup. The trouble starts when a mutable, domain-specific object is shared across unrelated tests. The next chapter compares fixtures and factories directly.
Failure mode 3: Unique values that collide
Many systems enforce uniqueness, such as one account per email address. Copying a line of setup and forgetting to change the email produces a failure that has nothing to do with the behavior under test:
class UserRepository:
def __init__(self):
self._emails = set()
def add(self, user):
if user.email in self._emails:
raise ValueError(f"duplicate email: {user.email}")
self._emails.add(user.email)
def test_two_members_can_be_stored():
repo = UserRepository()
first = User(id=1, email="[email protected]", role="member", active=True)
second = User(id=2, email="[email protected]", role="member", active=True)
repo.add(first)
repo.add(second)This test raises ValueError: duplicate email: [email protected]. The cause is a copy-paste slip in the setup. It is not a bug in the repository. Against a real database, the same slip appears as an integrity error, and the error message often does not point to the test line that caused it.
Hand-picked ids have the same problem. If one test inserts a row with id 1 and another test inserts 1 into a database that was not cleaned between tests, the second insert fails.
How the problems compound
These problems feed one another, which is why test data gets worse over time instead of staying at a steady cost.
The end state is the one that matters. When failures are noisy or unreproducible, developers start rerunning tests until they pass, or they delete tests they cannot understand. Test data is not the only cause, but it is a common one.
Common errors and what they look like
| Symptom | Likely cause | Where it shows up |
|---|---|---|
| Many tests fail after adding one required field | Constructors are repeated in every test | `TypeError` or a validation error in unrelated tests |
| A test passes alone but fails in the full run | A shared mutable object changed earlier | Assertion failure that depends on test order |
| A test fails only with parallel workers | Shared data or colliding unique values | Intermittent duplicate or integrity errors |
| A reader cannot say what a test is checking | Every field is spelled out, relevant or not | Long setup blocks above a one-line assertion |
| A test passes for the wrong reason | An irrelevant default happens to satisfy the rule | A passing test that would also pass if the code were broken |
The last row is easy to miss. If a test for "inactive users cannot log in" builds a user with role="admin" by accident, and the code under test has a bug where admins bypass the active check, the test fails for a reason unrelated to its name. A test that quietly depends on irrelevant values is hard to trust either way.
What a better approach needs
You can derive the requirements for a solution from the failures above. A good way of producing test data should:
- Return a valid object with no arguments. Tests that do not care about a field should not have to mention it.
- Let a test state only what matters. If the test is about
active=False, that should be the only visible value. - Give each test its own object. Nothing mutable should be shared between tests.
- Generate unique values automatically. Emails and ids should not depend on the author's memory.
- Define object shape in one place. A new required field should be added once.
- Be reproducible. If any value is random, a failing run must be repeatable.
A test data factory is a function or class built to satisfy these requirements. The next chapters introduce it in order: fixtures versus factories, a first factory, defaults, overrides, unique values, relationships, traits, persistence, determinism, libraries, organization, and anti-patterns. The last of these returns to the failures in this chapter, because a factory can reproduce some of them if it is written carelessly.
Exercises
Exercise
A suite has 200 tests that each call User(id=..., email=..., role=..., active=...). A new required field locale is added to User. Which two of the problems from this chapter does this situation show, and why is each one a cost?
Show answer
It shows the schema-change problem and the noise problem. Because constructors are repeated in every test, all 200 tests fail and each needs the same edit, which is slow and error-prone. And since every test already spells out every field, a reader cannot tell which value each test actually depends on, and the new locale value adds more irrelevant detail to each one.
Exercise
A test passes when run by itself but fails in the full suite. The suite uses a module-level SHARED_USER. Describe the most likely cause, and name one way to confirm it without changing the code under test.
Show answer
An earlier test mutated SHARED_USER, and the change persisted into the failing test. To confirm, run the tests in reverse or random order, or run the failing test with only the suspected earlier test. If the result changes with order, the shared mutable object is the cause.