Lesson 54 of 93 · 7 min read · Updated

Getting Legacy Code Under Test with Characterization Tests and Safe Refactoring

Legacy code is code you need to change but are afraid to touch, often because it has no tests and is hard to test. This lesson takes a small legacy report generator with three classic problems, records its current behavior with characterization tests, opens seams for time and state, and refactors it in small steps. The result is a class that is safe to test in parallel, with tests that prove the output format did not change.

Technical Requirements

  1. .NET 11 SDK
  2. xUnit 2.9.3
  3. FluentAssertions 7.2.2 (Apache-2.0; 8.x is commercial)
  4. Microsoft.Extensions.TimeProvider.Testing 11.0.0 (provides FakeTimeProvider)

The Starting Point

Here is the legacy class. It produces a line such as 20260314-0001 | MART RAPORU | 1234,50: a date stamp, a running number, the title in upper case and the total.

M06.BestPractices/Legacy/LegacyReportGenerator.cs

public sealed class LegacyReportGenerator
{
// static mutable state: the number one source of order dependence.
private static int _runCount;

public string Generate(string title, decimal total)
{
_runCount++;

// Hidden time dependency.
var stamp = DateTime.Now.ToString("yyyyMMdd");

return $"{stamp}-{_runCount:D4} | {title.ToUpperInvariant()} | {total:0.00}";
}

/// <summary>A temporary door opened so tests can reset the counter.</summary>
public static void ResetCounterForTests() => _runCount = 0;
}

It has three problems that make it hard to test:

  1. Static mutable state. _runCount is shared by every instance, so tests affect each other. The tests for this class must reset the counter through ResetCounterForTests and must run with DisableParallelization = true, as shown in the lesson on order dependence.
  2. A hidden time dependency. DateTime.Now returns a different value on every run, so you cannot assert on the full output.
  3. Mixed responsibilities. Formatting, numbering and the business format are all in one method. There is also a hidden culture dependency: {total:0.00} uses the current culture of the machine.

Step 1: Characterize the Current Behavior

A characterization test (also called a golden master test) records what the code does today, not what it should do. Its goal is not to prove correctness. Its goal is to make any change in behavior visible while you refactor. If the legacy code has a quirk that users rely on, the characterization test keeps that quirk until you decide to change it on purpose.

The strategy has four steps:

  1. Characterize the current behavior.
  2. Open seams where the code reaches out to time, I/O or static state.
  3. Refactor in small steps, keeping the characterization tests green.
  4. Only then, with the tests as a safety net, change the behavior.

For this class, the recorded format is: yyyyMMdd-NNNN | TITLE IN UPPER CASE | total with two decimals. You capture it by running the legacy code with known inputs and copying the output into an assertion. With DateTime.Now still inside the class, the stamp part changes every day, so at first you can only pin the stable parts, such as the -0001 | sequence segment and the title. That is enough to start; the next step removes the problem.

Step 2: Open the Seams

A seam is a place where you can change what the code does without editing it, usually by passing a dependency in. The refactored class takes the clock and the counter through its constructor:

M06.BestPractices/ReportGenerator.cs

/// <summary>Boundary (seam) for producing report numbers.</summary>
public interface IReportSequence
{
int Next();
}

/// <summary>Counter used in production; increments per instance.</summary>
public sealed class InMemoryReportSequence : IReportSequence
{
private int _current;
public int Next() => Interlocked.Increment(ref _current);
}

public sealed class ReportGenerator(TimeProvider timeProvider, IReportSequence sequence)
{
/// <summary>
/// The report culture is set EXPLICITLY.
/// If you do not pin the culture, the test passes on YOUR machine and breaks in CI.
/// </summary>
private static readonly CultureInfo ReportCulture = CultureInfo.GetCultureInfo("tr-TR");

public string Generate(string title, decimal total)
{
ArgumentException.ThrowIfNullOrWhiteSpace(title);

var stamp = timeProvider.GetLocalNow().ToString("yyyyMMdd", CultureInfo.InvariantCulture);
var number = sequence.Next();

return string.Create(
ReportCulture,
$"{stamp}-{number:D4} | {title.ToUpper(ReportCulture)} | {total:0.00}");
}
}

Three things changed. Time comes from TimeProvider, so a test can fix it. The counter is no longer static; it is behind the IReportSequence boundary, and each instance has its own. The culture is pinned in code, so the output no longer depends on the machine. The class itself holds no shared state, which makes it safe for parallel tests.

Step 3: Prove the Behavior Stayed the Same

With the seams in place, the characterization tests can pin the full output:

M06.BestPractices.Tests/CharacterizationTests.cs

/// <summary>Proves that the refactored class produces the SAME format as the legacy one.</summary>
[Fact]
public void RefactoredGenerator_ProducesTheSameFormatAsLegacy()
{
// Step 1: we recorded the format produced by the legacy code as the "golden copy":
// yyyyMMdd-NNNN | TITLE (UPPER CASE) | amount (2 decimals)
var clock = new FakeTimeProvider(new DateTimeOffset(2026, 3, 14, 12, 0, 0, TimeSpan.Zero));
var sut = new ReportGenerator(clock, new InMemoryReportSequence());

var line = sut.Generate("mart raporu", 1_234.5m);

line.Should().Be("20260314-0001 | MART RAPORU | 1234,50");
}

[Fact]
public void RefactoredGenerator_IncrementsSequencePerInstance()
{
var clock = new FakeTimeProvider(new DateTimeOffset(2026, 3, 14, 12, 0, 0, TimeSpan.Zero));
var sut = new ReportGenerator(clock, new InMemoryReportSequence());

sut.Generate("A", 1m).Should().Contain("-0001 |");
sut.Generate("B", 1m).Should().Contain("-0002 |");
sut.Generate("C", 1m).Should().Contain("-0003 |");
}

The first test pins the whole line: date stamp, sequence number, upper-cased title and total with a comma as the decimal separator. The second test pins the numbering rule. Neither test needs to reset anything, because each one builds its own sequence.

The real payoff of the refactoring is the next test. The legacy tests had to run one at a time. The refactored class can be used from 50 parallel calls without interference:

M06.BestPractices.Tests/CharacterizationTests.cs

[Fact]
public void RefactoredGenerator_IsNowSafeToRunInParallel()
{
// The MAIN GAIN of the refactoring: each test can build its own instance,
// there is no static state, and parallelism does not have to be disabled.
var clock = new FakeTimeProvider(new DateTimeOffset(2026, 3, 14, 12, 0, 0, TimeSpan.Zero));

var results = new System.Collections.Concurrent.ConcurrentBag<string>();

Parallel.For(0, 50, _ =>
{
var isolated = new ReportGenerator(clock, new InMemoryReportSequence());
results.Add(isolated.Generate("Parallel", 1m));
});

// Each instance has its own counter, so all of them produce -0001.
results.Should().HaveCount(50).And.OnlyContain(x => x.Contains("-0001 |"));
}

With the legacy static counter, the same loop would produce numbers from 1 to 50 in an unpredictable order, and possibly duplicates, because _runCount++ is not thread-safe.

Step 4: Change Behavior on Purpose

Once the safety net is in place, you can change behavior deliberately. The refactored class now rejects a blank title, which the legacy code accepted. Because this is a new rule, it gets its own explicit test:

M06.BestPractices.Tests/CharacterizationTests.cs

[Fact]
public void RefactoredGenerator_RejectsBlankTitle()
{
// New behavior ADDED during refactoring is also tested explicitly.
var sut = new ReportGenerator(TimeProvider.System, new InMemoryReportSequence());

var act = () => sut.Generate(" ", 1m);

act.Should().Throw<ArgumentException>();
}

Keep behavior changes separate from structural changes, ideally in separate commits. If a characterization test fails during a pure refactoring, you broke something. If it fails during a deliberate behavior change, you update it and say so in the commit message.

A pitfall to watch for is culture. The legacy code used ToUpperInvariant() and the machine's current culture for the decimal separator. The refactored code uses the tr-TR culture for both. For a title like mart raporu, the output is the same. But culture-sensitive casing differs for some letters: in Turkish, i upper-cases to İ, while ToUpperInvariant() gives I. A characterization test only protects the inputs you recorded, so include inputs that hit the risky parts, such as a title containing i and a total with decimals. Pinning the culture in code is what makes the test pass the same way on a developer machine and on a CI agent with different regional settings.

Summary

  1. A characterization test records what legacy code does today; its purpose is to detect change, not to prove correctness.
  2. Work in order: characterize, open seams, refactor in small steps with green tests, then change behavior on purpose.
  3. Replace DateTime.Now with TimeProvider and static counters with an injected boundary such as IReportSequence.
  4. After refactoring, tests no longer need reset hooks or disabled parallelism.
  5. Test new behavior added during refactoring explicitly, and keep it separate from structural changes.
  6. Pin the culture in code and record inputs that exercise culture-sensitive formatting and casing.