🔧 The Test That Passes Alone and Fails Only When Its Neighbor Runs First
A static field used to cache or hold shared state can make unit tests pass individually and fail unpredictably when run as part of a full suite – not because the tests are flaky, but because static state genuinely persists across test methods running in the SAME process, so one test’s leftover state silently leaks into the next test that happens to run afterward.
🔎 The Problem
public class PricingCalculator
{
private static decimal _lastDiscountApplied; // Static - shared
public decimal Calculate(decimal price, decimal discount)
{
_lastDiscountApplied = discount;
return price - (price * discount);
}
public decimal GetLastDiscount() => _lastDiscountApplied;
}
// Test A sets a 20% discount, asserts GetLastDiscount() == 0.20 - passes.
// Test B never sets a discount at all, but asserts GetLastDiscount() == 0
// - and FAILS, but only if Test A happened to run first in this process,
// because the static field still holds Test A'"'"'s leftover value.
✅ Fix: Remove the Shared Mutable State, or Reset It Explicitly
- The most reliable fix is removing the `static` modifier entirely if the field doesn’t genuinely need to be shared across all instances – an instance field scoped to each `PricingCalculator` object avoids the cross-test leakage completely, since each test typically creates its own instance.
- Where static state is genuinely required (a real application-wide cache, a singleton), an explicit reset method called in each test’s setup/teardown (`[TestInitialize]`/`[TestCleanup]` in MSTest, constructor/`IDisposable` in xUnit) guarantees a clean slate before every test runs, regardless of execution order.
- Running the test suite with randomized test ordering enabled (many test runners support this as a configuration option) surfaces this exact class of bug reliably and early – a test suite that only passes in one specific, unintentional execution order is a strong signal that hidden shared state exists somewhere.
⚠️ Why This Is Maddening to Debug From Inside a CI Pipeline
- Test runners don’t always guarantee execution order, and parallel test execution (common in CI to speed up a suite) can make the exact failure pattern change from run to run – so a report of “this test fails sometimes” is often actually completely deterministic given a specific run order, it’s just that the order itself isn’t visible from the failure alone.
- Running the single failing test in isolation – the very first thing anyone tries when a CI failure needs to be reproduced locally – passes every time for exactly this reason, which is precisely what makes static-field test pollution such a frustrating category of bug to track down without already suspecting it.
A static field doesn’t know it’s being used in a test – it just remembers whatever the last thing to touch it was, and ‘last’ depends entirely on an order nobody guaranteed.
