Test Fixture
A test fixture is the fixed environment and data a test runs against, set up before and torn down after execution.
Definition
A test fixture is the known baseline a test executes against: the objects, database rows, files, and configuration prepared before the test and cleaned up afterward. Good fixtures make tests independent and repeatable by giving each a fresh, predictable state; shared mutable fixtures that persist across tests create order dependence and flakiness. Fixtures range from a single in-memory object to a seeded database and a running container.
Context and scope
Every test needs some starting state; how that state is created and isolated determines whether the suite is reliable and parallelisable.
Common misconceptions
- One shared fixture speeds everything up — a shared mutable fixture couples tests, and a change in one breaks others unpredictably
- Fixtures must use production data — real data is often sensitive and unstable; purpose-built fixtures are safer and clearer
- Setup cost does not matter — slow fixture creation dominates suite time; a fast, reusable fixture is a major optimisation
Anti-patterns
- Mutating a shared fixture in one test so the next test sees altered state
- Depending on insertion order or auto-increment ids across tests
- Copying production data into tests, leaking personal data into the repository
Related concepts
Related examples
Authoritative source
What it is
A fixture is everything a test needs to exist before it runs and to be removed after: in-memory objects, database records, temporary files, environment variables, configured clients. Setup builds the baseline; teardown restores the world. When each test owns or is handed a fresh fixture, tests do not observe each other and can run in any order, or in parallel, without interfering.
Why it matters
Order dependence is one of the most common sources of flaky, confusing tests: a test that passes alone fails in the suite because an earlier test left state behind. Fixtures attack that at the root by making the starting condition explicit and isolated. They also document what a piece of code assumes about its world, turning implicit setup into readable intent.
How to use it well
Create fixtures per test or per scope, and reset shared resources so no state bleeds across. Prefer fast in-memory or containerised fixtures over production data, both for privacy and for determinism. Build fixtures with small factory helpers that make the relevant fields explicit and default the rest, so each test states only what it cares about. Measure and minimise setup cost, since fixture time often dominates the suite.