Course contentsShow
← Software Engineering
Lesson 458 of 1,93313. Unit Testing in DepthFree lesson

Avoiding Shared Mutable State

Eliminating test dependencies by avoiding static fields, singletons, and shared objects between tests.

Avoiding Shared Mutable State

What you'll learn: How to eliminate hidden test dependencies by preventing tests from sharing changeable data.

The Problem with Shared State

When multiple tests access and modify the same data—like static fields, singleton objects, or shared global variables—they create invisible connections between each other. This is shared mutable state: data that multiple tests can both read and change.

Think of it like roommates sharing a thermostat. If one roommate changes the temperature before leaving, the next roommate arrives to an unexpectedly hot or cold room. Your tests work the same way: when Test A modifies shared state, Test B might fail or pass for reasons unrelated to its own logic.

Why This Breaks Test Independence

Test independence means each test should run successfully in any order, alone or with others. Shared mutable state violates this because:

  • Execution order matters: Test B might fail after Test A but pass when run alone
  • Hard to debug: Failures seem random and disappear when you isolate the test
  • Parallel execution fails: Tests can't run simultaneously without interfering

Common Culprits

Watch out for:

  • Static fields that tests modify
  • Singleton instances with changeable state
  • Global configuration objects shared across tests
  • Shared collections that tests add to or clear

The Solution

Each test should create its own data using techniques you've learned like Test Data Builders or Object Mothers. Avoid modifying anything that outlives a single test's execution.

If you must use a singleton or static field, reset it in your test's teardown method—but better yet, redesign your code to accept injected dependencies instead of relying on global state.

Key Takeaway: Tests should never modify shared data that persists between test runs; use isolated, test-local data to maintain true test independence.