liveBook · Manning

Test isolation

As explained in The Art of Unit Testing 3e

Test isolation is the property that each test runs independently without relying on or altering the state or execution of other tests.

Test isolation means each test runs in its own little world: it neither relies on another test nor changes state that another test needs. Without it, failures can appear or disappear unpredictably, hiding real defects and wasting days of debugging effort. section 8.1.3

Watch for these signs of missing isolation:

  • A test passes or fails depending on which tests ran before it. section 8.1.3
  • Tests share mutable state, such as an in-memory cache or database, without resetting it. section 8.1.3
  • Running one test alone changes the result, revealing that the test suite—not the production code—is coupled. section 8.1.3

Reset shared state before every test

A shared UserCache can make login tests depend on order: one test adds user "a", while another expects the cache to be empty. Reset the cache before each test, then arrange the data each test requires. In Jest-style tests, the pattern is: beforeEach(() => getUserCache().reset()); followed by addDefaultUser() inside tests that need the user.

How The Art of Unit Testing 3e covers it

How deep it goes
Explains order dependence, demonstrates shared-cache failure, and refactors setup with beforeEach; it stops short of broader runner mechanics.
Examples
Uses a shared UserCache, SpecialApp login tests, test.only, and beforeEach reset as concrete artifacts.
What it assumes
Assumes familiarity with tests and shared variables, while introducing constrained test order through a concrete cache example.
What you can do after
Diagnose order-dependent failures and refactor tests to reset shared state and arrange their own required data.
How it connects
Connects shared state, flaky tests, unit testing, test order, and test setup.

Also explained in

Compare how 3 books explain test isolation →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Art of Unit Testing 3e. The section links point to the parts of the book it draws on.