Skip to content
  • Home
  • About
  • No Access
  • Privacy Policy
Bits of .NET
Bits of .NET
  • Asp.Net Core
  • C#
  • SQL
  • JavaScript
  • CSS
  • About
  • ErcanOPAK.com
  • No Access
  • Privacy Policy

Bits of .NET

Daily micro-tips for C#, SQL, performance, and scalable backend engineering.

  • Asp.Net Core
  • C#
  • SQL
  • JavaScript
  • CSS
  • About
  • ErcanOPAK.com
  • No Access
  • Privacy Policy
C#

C#: Fix a Static Field That Silently Resets Between Test Runs in the Same Process

- 27.09.26 - ErcanOPAK

🔧 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.

— C# Best Practice

Related posts:

C#: Fix a Multi-Tenant App's Static Field Silently Leaking One Tenant's Data Into Another Because It...

C#: Fix a Multi-Tenant App's Static Field Silently Leaking One Tenant's Data Into Another Because It...

C# Interceptors: Intercept Method Calls Like a Pro

C# Interceptors: Intercept Method Calls Like a Pro

C# Objects Live Longer Than Expected

C# Objects Live Longer Than Expected

Views: 8

Post navigation

Windows 11: Fix a Taskbar That Shows the Same App Icon Duplicated Several Times
Kubernetes: Fix a ResourceQuota That Silently Blocks New Pods From Being Created

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

November 2026
M T W T F S S
 1
2345678
9101112131415
16171819202122
23242526272829
30  
« Oct    

Most Viewed Posts

  • How to make theater mode the default for Youtube (1,068)
  • Get the User Name and Domain Name from an Email Address in SQL (990)
  • How to add default value for Entity Framework migrations for DateTime and Bool (986)
  • Get the First and Last Word from a String or Sentence in SQL (865)
  • How to select distinct rows in a datatable in C# (859)
  • How to enable, disable and check if Service Broker is enabled on a database in SQL Server (661)
  • Add Constraint to SQL Table to ensure email contains @ (619)
  • Average of all values in a column that are not zero in SQL (577)
  • How to use Map Mode for Vertical Scroll Mode in Visual Studio (553)
  • Find numbers with more than two decimal places in SQL (481)

Recent Posts

  • Network Speed Monitor Windows Application v2.5.1
  • Ağ Hızı İzleyici Windows Uygulaması v2.5.1
  • How to make theater mode the default for Youtube
  • The AI Prompt That Audits a Function for Thread-Safety Gaps
  • Ajax: Fix a Fetch Request Caching a Response Despite No-Store
  • WordPress: Fix a Navigation Block Losing Submenu Items After Sync
  • Visual Studio: Fix CodeLens Reference Counts Stuck at Stale Numbers
  • C#: Fix a UTF-8 String Literal Behaving Differently in a Switch
  • Photoshop: Fix a Liquify Mesh Snapping Back on a Smart Object
  • The AI Prompt That Turns a Crash Dump Into a Short Repro Script

Most Viewed Posts

  • How to make theater mode the default for Youtube (1,068)
  • Get the User Name and Domain Name from an Email Address in SQL (990)
  • How to add default value for Entity Framework migrations for DateTime and Bool (986)
  • Get the First and Last Word from a String or Sentence in SQL (865)
  • How to select distinct rows in a datatable in C# (859)

Recent Posts

  • Network Speed Monitor Windows Application v2.5.1
  • Ağ Hızı İzleyici Windows Uygulaması v2.5.1
  • How to make theater mode the default for Youtube
  • The AI Prompt That Audits a Function for Thread-Safety Gaps
  • Ajax: Fix a Fetch Request Caching a Response Despite No-Store

Social

  • ErcanOPAK.com
  • GoodReads
  • LetterBoxD
  • Linkedin
  • The Blog
  • Twitter
© 2026 Bits of .NET | Built with Xblog Plus free WordPress theme by wpthemespace.com