📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

You inherit a ten-year-old .NET codebase with almost no tests, and you need to change a core billing calculation safely. How do you get it under test? Explain characterisation tests, seams, and the dependency-breaking techniques you would use first.

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.

Senior Theory Advanced characterisation-tests legacy-code refactoring seams testing verify

🎯 Key points

  • Legacy code here means code without an effective safety net (Feathers: 'code without tests'); it may have some tests, but not ones you can rely on for this change
  • Characterisation tests pin current behaviour, bugs included, before changing anything
  • Golden master / approval tests with Verify capture many outputs cheaply across a grid of inputs
  • Seams: places to change behaviour without editing the code there (object seams via virtual / interfaces, parameterised constructors, link seams)
  • Safe, mechanical first refactorings (extract method, extract interface, parameterise constructor) done with IDE tooling, one per commit
  • Tightly coupled code: characterise from a higher level (HTTP, public entry point) first, then break dependencies underneath
  • Sprout method / sprout class and wrap method add new behaviour in tested code without touching untested code
  • Scope to the change and explain the up-front cost to stakeholders; record known bugs separately, don't fix them silently

⏱ 30-second answer

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.

🗣 Full answer (senior)

How I would answer this in an interview

"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 static SqlHelper, or news up an SmtpClient in the middle. That's where seams come in. For example, at [company] we had a [12,000-line] InvoiceService that 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."


Key terms

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

Dependency-breaking techniques, safest first

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

What to test first

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

Production example

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.

🔍 What the interviewer is checking

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

  • Characterisation tests that pin current behaviour, bugs included
  • Names seams and specific dependency-breaking refactorings, done mechanically
  • Uses golden master / Verify for calculations
  • Scopes the work to the change and tracks pinned bugs and temporary seams separately

Red flags

  • "Rewrite it properly first"
  • Writes tests for intended behaviour and fixes bugs along the way
  • Plans to hit 80% coverage across the whole codebase before changing anything

📚 Learn in depth

1. Why legacy code resists tests

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.

2. Seams and enabling points

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.

3. The legacy code change algorithm

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.

4. Golden master testing in practice

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.

5. Sprout and wrap

When you can't get the old method under test in time:

  • Sprout method: write CalculateGstAdjustment(lines) as a new, fully tested method, and call it from the old code with one line.
  • Sprout class: same, but a new class when the old one can't even be constructed in a test.
  • Wrap method: rename 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.

6. Static and ambient dependencies

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.

7. Knowing when to stop

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.

Try it yourself

  1. Take a method that uses DateTime.Now and a static helper; get it under test using only IDE automated refactorings.
  2. Build a golden master with Verify over 200 input combinations; change one rounding rule and read the diff.
  3. Practise sprout class: add a discount rule to an untestable class via a new tested class and a one-line call.
  4. Run Stryker.NET with --since:main on the changed files and check the mutation score of your new tests.
  5. Write down two bugs your characterisation tests pinned and open separate issues instead of fixing them inline.

💻 Code

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);
    }
}

⚠ Common mistakes

  • Mistake: Starting with a big refactor "so it becomes testable". Why it is wrong: you change behaviour with no safety net, which is the risk you were trying to avoid. Instead: only small, automated refactorings before tests exist; one per commit.
  • Mistake: Trying to unit test a class that is tangled with half the system. Why it is wrong: you end up with huge setups or dozens of mocks, and the dependency-breaking needed is too big to do safely without tests. Instead: characterise from a higher level first (HTTP endpoint or public entry point against a containerised database), then do the larger isolation refactoring under that net.
  • Mistake: Writing tests for what the code should do. Why it is wrong: they fail on day one and tell you nothing about what your change broke. Instead: characterisation tests that pin current behaviour, then change deliberately.
  • Mistake: Silently fixing bugs found while characterising. Why it is wrong: downstream reports, integrations or customers may depend on the old behaviour. Instead: pin it, log an issue, fix it as a separate, visible change.
  • Mistake: Aiming for coverage across the whole legacy codebase. Why it is wrong: huge cost for code nobody is changing. Instead: cover the area you are changing; improve as you touch more.
  • Mistake: Mocking every collaborator with a library to get a class running. Why it is wrong: tests mirror the implementation and break on every refactor. Instead: characterise through public outputs; use simple hand-written fakes for the one or two hard dependencies.
  • Mistake: Non-deterministic golden masters (unsorted collections, current dates, GUIDs). Why it is wrong: snapshots fail randomly and people start accepting diffs blindly. Instead: fix the clock, sort, and scrub volatile values.
  • Mistake: Leaving temporary seams forever (the parameterless constructor, static setters). Why it is wrong: two ways to construct the class and hidden globals remain. Instead: remove them once callers move to DI; track them as follow-up work.
  • Mistake: Adding new logic inside the untested method. Why it is wrong: the untested area grows. Instead: sprout a new tested method or class and call it.

🏛 Senior insight: trade-offs

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.

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions mocking dependencies to get legacy classes under test Why: Checks they know the risk of mock-heavy tests that lock in implementation details during refactoring.
    How to answer

    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.

  2. When: Candidate mentions Verify or golden master snapshots Why: Checks they can make snapshot tests deterministic and manage accepted changes in CI.
    How to answer

    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.

  3. When: Candidate says they would characterise first and then refactor Why: Checks they can judge the strength of a safety net, not just its existence.
    How to answer

    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.

🛠 Real-world problems: how you handle them

GST change to an untested billing module
Situation
A [ten-year-old] .NET Framework billing module, about [12,000] lines with [3%] coverage, needed a change to how GST was applied to discounted lines. Invoices for [n thousand] business customers ran monthly; an error would mean reissuing invoices.
Signals
Previous changes in the module had caused [two] invoice reissues in a year; developers avoided the code; estimates for any change were padded heavily.
Investigation
I mapped the change point (one method) and its dependencies: a static `SqlHelper`, `DateTime.Now`, and a configuration singleton. I checked which refactorings Rider could do automatically and planned them as separate commits. I ran the calculation for a sample of last month's real invoice inputs in a sandbox, using synthetic customer details, to understand the range of values.
Resolution
Immediate: extracted the rate lookup and clock behind an interface and `TimeProvider` with a parameterised constructor, keeping the old constructor. Then built a Verify golden master over [2,400] input combinations. Made the GST change; the diff showed the intended changes plus [37] unexpected ones caused by a shared rounding helper, which we fixed before release. The monthly run produced no reissues.
Prevention
Kept the golden master in CI, added Stryker.NET on the module for changed files, logged [5] pinned bugs as separate issues, and tracked removal of the temporary constructor once DI reached the module.

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.

↩ Usually asked after

More in Senior Testing Topics

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me