Lesson 54 of 93 · 7 min read · Updated
Getting Legacy Code Under Test with Characterization Tests and Safe Refactoring
On this page
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
- .NET 11 SDK
- xUnit 2.9.3
- FluentAssertions 7.2.2 (Apache-2.0; 8.x is commercial)
- 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
It has three problems that make it hard to test:
- Static mutable state.
_runCountis shared by every instance, so tests affect each other. The tests for this class must reset the counter throughResetCounterForTestsand must run withDisableParallelization = true, as shown in the lesson on order dependence. - A hidden time dependency.
DateTime.Nowreturns a different value on every run, so you cannot assert on the full output. - 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:
- Characterize the current behavior.
- Open seams where the code reaches out to time, I/O or static state.
- Refactor in small steps, keeping the characterization tests green.
- 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
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
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
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
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
- A characterization test records what legacy code does today; its purpose is to detect change, not to prove correctness.
- Work in order: characterize, open seams, refactor in small steps with green tests, then change behavior on purpose.
- Replace
DateTime.NowwithTimeProviderand static counters with an injected boundary such asIReportSequence. - After refactoring, tests no longer need reset hooks or disabled parallelism.
- Test new behavior added during refactoring explicitly, and keep it separate from structural changes.
- Pin the culture in code and record inputs that exercise culture-sensitive formatting and casing.