Ch. 22 · Software Testing

Test Fixtures and Independent State

Test Fixtures and Independent State. Learn the reasoning, a practical example, common mistakes and an interview exercise.

~2 min readintermediateupdated Oct 3, 2026

Fixtures should own the state they create and clean up reliably. Isolation prevents one test’s writes from changing another test’s assumptions.

Before you start

You should understand inputs, expected outputs and the boundaries of the component under test. State the risk a test should detect before choosing a tool or mock. Distinguish controlled dependencies from real integrations so the result does not imply more coverage than the test actually provides.

The practical goal is to reason through this situation: Use a fresh account and transaction boundary for each persistence test. Read the walkthrough first, then try the interview exercise before opening its answer. The important part is explaining the decision and its consequences, rather than remembering a definition alone.

Step-by-step walkthrough

Step 1: Create independent state

Each test gets records or resources it can safely modify.

Step 2: Register cleanup early

Risky setup and failed assertions must not bypass release.

Step 3: Verify no cross-test dependence

Repeated or reordered execution should not change expectations.

Worked scenario

Use a fresh account and transaction boundary for each persistence test.

Two tests share an account; one deletes it while another assumes it exists. Fresh per-test data or a justified transaction isolation strategy removes that order dependency. Cleanup must run after failure as well as success, and should not delete another concurrent test’s records.

Common mistake

Shared mutable records create order-dependent assertions.

Verify the behavior

Force setup and assertion failures and verify owned resources are still released.

Interview exercise

Design cleanup for failure.

Answer and reasoning

Register cleanup before risky operations and ensure it runs after failed assertions as well as successful tests.

Continue learning

Compare the scenario with the Software Testing interview questions and test your understanding with the Software Testing MCQs. For terminology and implementation details, consult the reference material.

More in Software Testing

read ✓Software Testing · hard

Testing Time with an Injected Clock

Inject a clock instead of calling the system time, freeze it in tests, and remove the sleeps that make tests flaky.

~2 min readread →
read ✓Software Testing · mid

Code Coverage and Its Limits

Read line and branch coverage as a signal, not a goal, and avoid the tests that chase the number without checking behavior.

~2 min readread →
read ✓Software Testing · hard

Scoping End-to-End Tests

Reserve end-to-end tests for critical user journeys, use stable selectors, and avoid duplicating coverage the lower tests already have.

~2 min readread →
esc