Testing legacy .NET code: characterisation (golden master) tests, Michael Feathers' seams, sprout and wrap methods, extract-interface and parameterise-constructor refactorings, snapshotting outputs with Verify, and choosing safe first refactorings.
In Michael Feathers' terms, legacy code is code without tests, so the job is to make this change safe, not to reach a coverage number. First I write characterisation tests: run the code with a range of inputs and assert whatever it currently does, bugs included. For calculations, a golden master with Verify captures hundreds of input combinations in one snapshot. To get the code into a test harness I look for seams, places where behaviour can be swapped without editing that spot: virtual methods, a constructor I can parameterise, an interface I can extract. I make those refactorings small and mechanical, using IDE automated refactorings. New logic goes in a sprout method or class that is tested from the start. The trade-off: some ugly intermediate code (extra constructors, wrapper interfaces) in exchange for a safety net before the real change.
"I start from what I'm actually trying to change, not from the whole codebase. If the task is a change to the billing calculation, I want a safety net around that calculation, and I want it before I touch any logic. So the first tests I write are characterisation tests: I call the code with realistic inputs and assert whatever it returns today, even if it looks wrong. Those tests describe behaviour, not intent. For a calculation with many inputs I use a golden master: generate a grid of combinations, run them all, and snapshot the results with Verify. One test, hundreds of cases, and any change in output shows up as a diff.
The obstacle is usually that the code can't run in a test: it reads
DateTime.Now, calls a staticSqlHelper, or news up anSmtpClientin the middle. That's where seams come in. For example, at [company] we had a [12,000-line]InvoiceServicethat read rates directly from the database inside a loop. I made the smallest safe changes: extract the rate lookup into a method, then into an interface, and add a constructor that takes it while keeping the old constructor for existing callers. Those are mechanical refactorings the IDE does for you, so the risk is low even without tests. Then the calculation could run against an in-memory rate table, and we wrote [around 300] golden-master cases in a day. The actual change took [two days] and the snapshot diff showed exactly the [14] invoices whose totals were meant to change, and nothing else.The mistake I see is fixing bugs you find along the way. A characterisation test that pins a wrong rounding is uncomfortable, but if you silently fix it, some downstream report that depends on the old value breaks. I record those as separate issues and fix them deliberately. First pin it, then change it."
| Term | Meaning |
|---|---|
| Characterisation test | Asserts what the code does now, not what it should do |
| Golden master / approval test | Snapshot of many outputs; change shows as a diff (Verify, ApprovalTests) |
| Seam | A place to alter behaviour without editing that place |
| Enabling point | Where you choose which behaviour the seam uses (constructor, config, link) |
| Sprout method / class | New logic written in new, tested code and called from the old code |
| Wrap method | Rename the old method, create a new one that calls it plus the new behaviour |
| Technique | Use when | Risk |
|---|---|---|
| Extract method | A block hides a dependency | Very low with IDE tooling |
| Parameterise constructor | Class news up its dependencies | Low; keep the old constructor temporarily |
| Extract interface | Need to substitute a concrete class | Low |
| Subclass and override | Can't change the constructor; method is or can be made virtual | Medium; test-only subclass |
| Introduce static setter / ambient context | Static calls everywhere, no DI | Medium; temporary only |
Replace DateTime.Now with TimeProvider |
Time-dependent logic | Low |
| Priority | Why |
|---|---|
| The code you are about to change | It is the risk |
| Its direct callers' observable outputs | Catches changed contracts |
| Known high-value paths (billing, payments) | Business impact |
| Everything else | Only when you next touch it |
On a [ten-year-old] billing module with [3%] test coverage, a golden master of [2,400] input combinations took about a day to build. During the change to GST handling, the snapshot diff flagged [37] invoices whose totals changed unexpectedly because of a shared rounding helper; without it, those would have gone out to customers.
Checks whether the candidate can change untested code safely with a pragmatic, scoped approach rather than a big-bang rewrite or a coverage drive.
Green flags
Red flags
Code is hard to test when it creates its dependencies or reaches out to global state:
InvoiceService.Calculate()
+-- new SqlConnection(ConfigurationManager.ConnectionStrings[...])
+-- DateTime.Now
+-- RateCache.Instance.Get(...) (static singleton)
+-- new SmtpClient().Send(...) (side effect)
None of those can be replaced from a test, so the only way to run the method is with a real database, a real clock and a real mail server. Legacy code often has some tests, but they are usually too coarse, too slow or too brittle to tell you whether a specific change broke something, so in practice you treat the area as unprotected.
Feathers defines a seam as a place where you can alter behaviour without editing in that place. Every seam has an enabling point where the choice is made.
| Seam type | .NET example | Enabling point |
|---|---|---|
| Object seam | Virtual method, interface parameter | Constructor, property or subclass in the test |
| Link seam | Different assembly or InternalsVisibleTo build |
Project references |
| Preprocessing seam | #if TEST |
Build configuration (avoid) |
Constructor injection is usually the best long-term target because it ends in normal DI and makes dependencies explicit. It is not the only option: a settable property (property injection) is a useful temporary seam when changing the constructor would touch hundreds of call sites, and passing a dependency as a method parameter (method injection) suits values that vary per call, such as the current time or a cancellation token. Pick the seam that is safest to introduce now, and move towards constructor injection as callers come under test.
1. Identify change points (where the edit will go)
2. Find test points (where you can observe the effect)
3. Break dependencies (minimal, mechanical refactorings)
4. Write characterisation tests (pin current behaviour)
5. Make the change and refactor (now covered)
Step 3 happens before tests exist, which is why it must use the safest refactorings: automated IDE refactorings (Rider, Visual Studio) that preserve behaviour by construction, and one refactoring per commit so any mistake is easy to find.
When the code is so entangled that no small refactoring isolates it, move the test point up: characterise through the public entry point (an HTTP endpoint with WebApplicationFactory, a console command, a message handler) against a containerised database. That is slower and coarser, but it gives a net under the bigger refactoring needed to reach unit-level seams.
For pure-ish calculations:
inputs = cartesian product of {customer types} x {plans} x {quantities} x {dates}
results = inputs.Select(i => (i, Calculate(i)))
Verify(results) -> stored as InvoiceTests.Calculate.verified.txt
Verify writes a .received. file on mismatch and the diff tool shows exactly which rows changed. Make the output deterministic: fix the clock, sort collections, and scrub GUIDs. Keep the grid small enough to read the diff (hundreds, not millions); pairwise generation helps.
When you can't get the old method under test in time:
CalculateGstAdjustment(lines) as a new, fully tested method, and call it from the old code with one line.Pay() to PayCore(), create a new Pay() that logs or validates and then calls PayCore(). The new behaviour is testable in isolation.The old code stays untested, but the new code is not added to the untested pile.
DateTime.Now becomes TimeProvider. Static helpers become instance classes behind an interface, with the static method delegating to a default instance during the transition. HttpContext.Current (System.Web) becomes IHttpContextAccessor or, better, explicit parameters. During migration from .NET Framework, these seams are also what lets you move code to .NET 10 incrementally.
The aim is enough safety for the change, plus leaving the area better than you found it. Coverage of untouched code is not the target; a mutation score on the changed area (Stryker.NET with --since to limit it to changed files) is a better measure of whether the new tests actually catch regressions.
DateTime.Now and a static helper; get it under test using only IDE automated refactorings.--since:main on the changed files and check the mutation score of your new tests.Legacy code with hidden dependencies, the minimal seams added, and a characterisation test plus a golden master with Verify.
// Before: impossible to test without a database and a fixed date.
namespace Billing.Legacy;
public class InvoiceCalculator
{
public decimal Total(int customerId, decimal amount)
{
var rate = SqlHelper.GetDiscountRate(customerId); // static, hits the database
var lateFee = DateTime.Now.Day > 20 ? 15m : 0m; // hidden clock
return Math.Round(amount * (1 - rate) + lateFee, 2); // banker's rounding by default
}
}
public static class SqlHelper
{
public static decimal GetDiscountRate(int customerId) => throw new NotSupportedException("Needs a database");
}
// After: two mechanical refactorings (extract interface, parameterise constructor).
// Behaviour is unchanged; the old constructor keeps existing callers compiling.
namespace Billing.Legacy;
public interface IDiscountRates
{
decimal For(int customerId);
}
internal sealed class SqlDiscountRates : IDiscountRates
{
public decimal For(int customerId) => SqlHelper.GetDiscountRate(customerId);
}
public class InvoiceCalculator(IDiscountRates rates, TimeProvider time)
{
public InvoiceCalculator() : this(new SqlDiscountRates(), TimeProvider.System) { } // temporary
public decimal Total(int customerId, decimal amount)
{
var rate = rates.For(customerId);
var lateFee = time.GetLocalNow().Day > 20 ? 15m : 0m;
return Math.Round(amount * (1 - rate) + lateFee, 2);
}
}
// Billing.Tests/InvoiceCalculatorCharacterisationTests.cs
using Billing.Legacy;
using Microsoft.Extensions.Time.Testing;
using VerifyXunit;
using Xunit;
namespace Billing.Tests;
public sealed class InvoiceCalculatorCharacterisationTests
{
private sealed class FixedRates(decimal rate) : IDiscountRates
{
public decimal For(int customerId) => rate;
}
// December has 31 days, so every day in the grid below is valid.
private static FakeTimeProvider OnDay(int day)
{
var time = new FakeTimeProvider(new DateTimeOffset(2026, 12, day, 9, 0, 0, TimeSpan.Zero));
time.SetLocalTimeZone(TimeZoneInfo.Utc);
return time;
}
[Fact]
public void PinsCurrentRounding_EvenThoughItLooksWrong()
{
// 10.05 * 0.9 = 9.045. Math.Round uses banker's rounding (to even), so today the code returns 9.04,
// not the 9.05 finance expects. Characterisation: pin it, log issue [#123], fix separately.
var sut = new InvoiceCalculator(new FixedRates(0.10m), OnDay(5));
Assert.Equal(9.04m, sut.Total(1, 10.05m));
}
[Fact]
public Task GoldenMaster_AcrossInputGrid()
{
decimal[] rates = [0m, 0.05m, 0.125m, 0.3m];
decimal[] amounts = [0m, 0.01m, 10.05m, 99.995m, 1_000m];
int[] days = [1, 20, 21, 31];
var rows =
from rate in rates
from amount in amounts
from day in days
select new { rate, amount, day, total = new InvoiceCalculator(new FixedRates(rate), OnDay(day)).Total(1, amount) };
// One snapshot, 80 cases. Any behaviour change shows up as a diff in the .verified.txt file.
return Verifier.Verify(rows);
}
}
Legacy testing is risk management, and seniors scope it ruthlessly. The question is never "how do we test this whole system" but "what is the cheapest safety net that makes this change safe, and what do we leave behind for next time". Golden masters are the highest-leverage tool for calculations; characterisation through HTTP with WebApplicationFactory (or, for .NET Framework, through the deployed endpoint) is the best for request flows where the internals are tangled.
The other senior skill is communicating the trade-off to people who don't read code. The first change in an untested area costs more (say a day of harness building), and the product owner should hear it in business terms: "one extra day now, versus the [n] invoice reissues this module caused last year and the support cost of each". I give options (fast and risky, or one day slower with a safety net that also speeds up the next three changes), make a recommendation, and record the decision. I keep the temporary seams visible as tracked debt so they are removed, not fossilised.
| Approach | When it fits | Cost | When not to |
|---|---|---|---|
| Golden master (Verify) | Calculations, report generators, serialisers | Low; diffs need reading | Highly non-deterministic outputs |
| Characterisation via HTTP | Tangled request flows | Medium; needs a runnable host | Pure computation (too slow and coarse) |
| Seams + unit characterisation | A focused class you'll keep changing | Medium | Code about to be deleted |
| Sprout / wrap | Tight deadline, untestable class | Low | When you have time to get the class under test |
| Rewrite | Small, well-understood, isolated module | High | Core logic with unknown behaviour |
I measure success by escaped defects in the changed area and by mutation score on the new tests, not by global coverage.
Over-mocking is mocking every collaborator of a class, even plain in-process ones, and verifying the calls between them. The tests end up describing how the code works rather than what it does.
That gives the worst of both worlds: false alarms when you refactor without changing behaviour, and missed bugs because the real collaborators never run together.
I test behaviour through a public API: a use case, a handler, or an HTTP endpoint, with real in-process objects and mocks or fakes only at boundaries I don't own (third-party HTTP, Service Bus, email, the clock).
The trade-off: broader tests point less precisely at the failing class, but they survive refactoring and catch integration bugs.
Verify serialises whatever you pass to Verify(...) and compares it with a committed .verified. file next to the test. On a mismatch it writes a .received. file and fails, so you diff and accept the new snapshot deliberately.
It shines for large outputs: API response bodies, generated code, emails, OpenAPI documents. By default it replaces Guids and DateTimes with stable placeholders like Guid_1; other volatile values are scrubbed with ScrubMembers or ignored.
In CI, mismatches must just fail; acceptance happens locally and the .verified. diff is reviewed in the pull request.
The trade-off: one line asserts a whole payload, but careless acceptance turns snapshots into rubber stamps.
Good enough means the tests would notice if your change broke something. Check three things. Coverage of the change area (not the codebase): every branch you'll touch is executed, including the input grid of any golden master, the set of input combinations whose outputs you snapshot, which should include boundary values. Sensitivity: run Stryker.NET on the changed files only (--since) and explain or kill surviving mutants, or break a line by hand and confirm a test fails. Reliability and speed: run the new tests repeatedly to prove they are deterministic, and keep them fast enough to run in the PR pipeline on every commit, because a safety net that is flaky or only runs nightly won't protect the change.
How to tell it (STAR)
**S:** At [company], I had to change GST handling in a [ten-year-old] billing module with almost no tests, where past changes had caused invoice reissues. **T:** Make the change without a single wrong invoice. **A:** I didn't refactor first. I used only IDE automated refactorings to add two seams, for the rate lookup and the clock, then built a golden master of [2,400] input combinations with Verify. When I made the GST change, the diff showed [37] unexpected changes from a shared rounding helper, which we fixed before release. I logged the existing bugs I'd pinned as separate issues. **R:** The next monthly run went out with zero reissues, and later changes to the module took [half] the time because the harness was there.
Last updated 23 Nov 2026.