Test Fixtures and Setup Code Without the Mess
Most test suites start tidy and slowly collect clutter. A shared setup block grows by one line at a time until nobody remembers why half of it is there. Tests depend on data created three files away, and changing one fixture breaks fifty tests. The tests still pass on a good day, but they have become hard to read and risky to change.
A fixture is anything a test needs before it can run: objects, data, files, a database connection or a configured service. Good fixtures make tests short and obvious. Bad ones hide the facts a reader needs to understand a test. This article covers practical ways to keep setup under control.
What setup is really for
Every test has three parts: arrange, act and assert. Setup is the arrange part. A useful goal is that a reader can look at a single test and understand what it checks without hunting through other files.
That goal pulls in two directions. You want to avoid copying the same ten lines into every test, but you also do not want the important details buried somewhere else. The techniques below try to balance both.
Keep fixtures small and focused
A fixture should create one thing and do it well. A single fixture that builds a user, an order, a payment and a shipping address is hard to reuse, because each test needs a slightly different combination. Prefer several small fixtures that tests can combine.
import pytest
@pytest.fixture
def user():
return {"name": "Ada", "active": True}
@pytest.fixture
def inactive_user(user):
return {**user, "active": False}
In this Python example using pytest, one fixture builds on another. A test names the fixture it needs as an argument, and the framework provides it. The dependency is visible in the function signature, which is much clearer than values set on a shared object.
Use builders for data with many fields
When objects have many fields, most tests care about only one or two. A builder function with sensible defaults lets each test override just what matters.
def make_order(**overrides):
order = {"id": 1, "items": ["pen"], "status": "new", "country": "CA"}
order.update(overrides)
return order
def test_cancelled_order_cannot_ship():
order = make_order(status="cancelled")
assert can_ship(order) is False
The reader sees at a glance that status is the interesting detail. Everything else is noise that the builder hides. This pattern also makes tests resistant to change, because adding a new field means editing the builder in one place.
Control scope on purpose
Many frameworks let you choose how often a fixture runs: for every test, once per file, or once per whole run. Smaller scope is safer, because each test gets a fresh copy and cannot affect another. Larger scope is faster, which matters for expensive resources such as a database connection or a started server.
A reasonable approach is to use per test scope by default and widen it only for resources that are slow to create and read only in use. If a wider fixture holds mutable state, reset it between tests, or the order in which tests run will start to matter.
Avoid shared mutable state
The most common source of mysterious failures is state that leaks from one test to the next. A test passes alone and fails in the suite, or the other way around. Typical causes:
- A module level list or dictionary that tests modify.
- A database table that keeps rows left by an earlier test.
- Files written to a fixed path.
- Changes to environment variables or the system clock that are never undone.
Fix these by creating fresh data for each test, using temporary folders that the framework cleans up, and wrapping any global change in a fixture that restores it afterwards.
Clean up reliably
Setup that creates something often needs a matching teardown. Most frameworks let a fixture yield a value and run cleanup code afterwards, even if the test failed.
@pytest.fixture
def temp_file(tmp_path):
path = tmp_path / "data.txt"
path.write_text("hello")
yield path
Here tmp_path is a built-in fixture that provides a unique temporary folder and removes it later. Prefer built-in helpers like this to hand written cleanup, because they handle edge cases you might forget.
Be careful with hidden magic
Some setups run automatically for every test without being mentioned in the test itself. Frameworks often allow this, and it is occasionally useful, for example to block real network calls. But used too widely, it makes tests mysterious: a reader cannot tell why something works. Reserve automatic fixtures for protective rules that apply everywhere, and make everything else explicit.
Prefer fakes to heavy mocks
If a test needs a collaborator, a small hand written fake, such as an in memory store with the same methods, is often clearer than a mock with a long list of expected calls. Fakes check behaviour, while strict mocks tie tests to implementation details and break when the code is refactored.
A short checklist
- Can I understand this test without opening another file?
- Does the test show the values that matter to its outcome?
- Would the test still pass if run alone, or in random order?
- Does each fixture have one clear purpose and a clear name?
- Is anything slow created more often than needed?
Frequently Asked Questions
Is it a problem to repeat a few lines of setup in several tests?
Not usually. Some repetition is the price of readable tests. Extract a helper once the same setup appears in many places and the duplication starts to hide differences, but do not abstract after only two uses.
Should fixtures live in one shared file?
Keep fixtures near the tests that use them. Put only genuinely common ones in a shared location. A giant shared file tends to become the same mess you were trying to avoid.
How do I speed up slow test setup?
Widen the scope for expensive, read only resources, use in memory substitutes for databases where that is realistic, and avoid creating data the test does not need. Measure before and after, since guesses about slowness are often wrong.