Why Independence Matters
Test isolation means every test can run on its own, in any order, alongside any subset of the suite, and produce the same result every time. Independence is the corollary property: no test's outcome should depend on another test having run first, in a particular order, or at all. When these properties break down, the suite becomes a fragile web where deleting or reordering one test silently changes the result of another, and 'run the failing test alone to debug it' stops working because the failure only reproduces in the full run.
Cricket analogy: It's like each net session for a batter needing a freshly reset bowling machine rather than inheriting whatever speed and line the previous batter's session left it on - otherwise results aren't comparable.
Sources of Hidden Coupling
The most common leaks are shared database state (tests writing rows that later tests read or that violate later tests' uniqueness assumptions), shared singletons or module-level caches that persist in memory across tests within the same process, and shared fixtures with mutable state that one test mutates and a sibling test reads. Test frameworks that reuse a class instance across multiple test methods (rather than instantiating fresh per test) are a frequent culprit, as are static/class-level fields in xUnit-family frameworks and Python module-level globals.
Cricket analogy: It's like a scoreboard operator forgetting to zero the tally between two unrelated matches, so the second match starts showing runs it never actually scored.
# BAD: module-level mutable state shared across tests
_user_cache = {}
def test_creates_user():
_user_cache['id1'] = create_user('Ada')
assert _user_cache['id1'].name == 'Ada'
def test_user_count_is_zero():
# fails only if the previous test ran first
assert len(_user_cache) == 0
# GOOD: fresh fixture per test, no shared global
import pytest
@pytest.fixture
def user_cache():
return {}
def test_creates_user(user_cache):
user_cache['id1'] = create_user('Ada')
assert user_cache['id1'].name == 'Ada'
def test_user_count_is_zero(user_cache):
assert len(user_cache) == 0Patterns That Guarantee Isolation
Use fresh fixtures per test (function-scoped, not module- or session-scoped, unless the resource is genuinely expensive and read-only) so each test starts from a known state. Wrap database-touching tests in a transaction that rolls back after the test, or use a dedicated test database that is reset via migrations or truncation between runs. Prefer dependency injection over global singletons in production code itself - not just tests - because injectable dependencies can be swapped for isolated test doubles trivially. Finally, treat any test that only passes when run after another specific test as a bug to fix immediately, not a quirk to document.
Cricket analogy: It's like the groundstaff re-rolling and re-marking the pitch between innings rather than letting the second innings play out on whatever wear the first innings left behind.
A quick smoke test for independence: run your suite with a single test filtered to run alone, then run the full suite, then run the suite in reverse or randomized order. If results differ across these three runs, you have hidden coupling somewhere in fixtures, globals, or shared external resources.
Session-scoped or class-scoped fixtures (shared across many tests for performance) are a common place isolation quietly breaks. If you must share an expensive resource, make sure the tests only read from it and never mutate it, or explicitly reset the mutable parts between tests.
- Isolated tests can run alone, in any order, or alongside any subset of the suite with identical results.
- Hidden coupling most often comes from shared databases, singletons, module-level globals, or mutable shared fixtures.
- Prefer function-scoped fixtures over module- or session-scoped ones unless the resource is expensive and read-only.
- Wrap database tests in rollback transactions or reset the test database between runs.
- Dependency injection in production code makes isolated test doubles easy to substitute.
- Any test that only passes in a specific order relative to another test is a bug, not a quirk.
- Validate isolation by running tests alone, in full-suite order, and in randomized order, comparing results.
Practice what you learned
1. What does it mean for a test suite to have 'independent' tests?
2. Which fixture scope is generally the safest default for guaranteeing isolation?
3. A test only fails when run after a specific other test. What should this be treated as?
4. What is a reliable technique for keeping database-touching tests isolated?
5. Why does dependency injection in production code help with test isolation?
Was this page helpful?
You May Also Like
Flaky Tests and How to Fix Them
Learn what makes automated tests flaky, how to systematically diagnose the root cause, and proven techniques to make your test suite deterministic and trustworthy.
Arrange-Act-Assert Pattern
Master the three-phase structure - Arrange, Act, Assert - that keeps unit tests readable, focused, and easy to debug when they fail.
Testing Legacy Code
Learn practical techniques - characterization tests, seams, and incremental refactoring - for safely adding automated tests to code that has none.
Related Reading
Related Study Notes in Software Engineering
Browse all study notesMicroservices Study Notes
Software Architecture · 30 topics
Software EngineeringDesign Patterns Study Notes
Software Design · 30 topics
Software EngineeringSoftware Engineering Study Notes
Python · 40 topics
Software EngineeringGit & Version Control Study Notes
Bash · 40 topics
Software EngineeringSystem Design Study Notes
Architecture · 40 topics