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

📚 Interview question

Show me in code how you break the dependencies that stop a legacy OrderService from being unit tested: DateTime.Now, a static helper, new SqlConnection inside a method and a sealed third-party client. Which seams and techniques would you use, and how does TimeProvider help?

Demonstrates dependency-breaking techniques on a legacy order service: TimeProvider and FakeTimeProvider for the clock, wrapping statics behind an instance, extracting a data-access dependency, adapting a sealed SDK client, and choosing between object seams, constructor parameterisation and integration tests.

Senior Coding Advanced code-quality legacy-code refactoring seams timeprovider unit-testing

🎯 Key points

  • A seam is a place to change behaviour without editing the code there; object seams (constructor/interface) are the default in C#
  • Parameterise Constructor, keeping the old constructor chaining to the new one with real implementations so existing callers and behaviour are untouched
  • Clock: inject TimeProvider (in the BCL since .NET 8, the standard abstraction in .NET 10), test with FakeTimeProvider and SetUtcNow/Advance
  • Static with side effects or I/O: wrap behind an instance interface (adapter); pure static helpers can stay static
  • new SqlConnection in a method: extract a store interface for unit tests, and cover the real SQL with Testcontainers integration tests
  • Sealed third-party SDK client: adapt it behind your own narrow interface, plus a few contract tests against the provider's sandbox
  • Use safe, compiler-checked IDE refactorings to create seams before tests exist, then add characterisation tests
  • Business time in Australia: convert UTC with TimeZoneInfo (Australia/Sydney) rather than DateTime.Now on the server

⏱ 30-second answer

Michael Feathers calls the place you can change behaviour without editing the code a seam; in C# the workhorse is the object seam: a dependency passed through the constructor behind an interface or abstract class.

  • Clock: replace DateTime.Now with an injected TimeProvider (.NET 8+); tests use FakeTimeProvider and SetUtcNow/Advance.
  • Static helper: if it's pure, leave it; if it does I/O or holds state, wrap it in an instance class behind an interface.
  • new SqlConnection: extract an IOrderStore and test the SQL separately with Testcontainers.
  • Sealed SDK client: adapt it behind your own narrow interface.

Do the first steps with safe, mechanical IDE refactorings (Parameterise Constructor, Extract Interface) because there are no tests yet. The trade-off: each seam adds an abstraction, so add only the ones a test needs.

🗣 Full answer (senior)

How I would answer this in an interview

"The problem with this OrderService is that it reaches out and grabs everything: it reads DateTime.Now to decide the same-day dispatch cut-off, calls a static ExchangeRates.Get that hits an HTTP API, news up a SqlConnection, and uses the payment provider's sealed client. None of that can be replaced in a test, so the only test is a full environment.

My approach is Feathers': find seams, and in C# that means object seams, getting each dependency passed in through the constructor. Because there are no tests yet, the first edits have to be ones I trust without tests, so I use IDE refactorings like Introduce Parameter and Extract Interface, and I keep the old constructor chaining to the new one so existing callers don't change.

For the clock, .NET 8 added TimeProvider, so I inject that and call GetUtcNow(), converting to Australia/Sydney for the cut-off. Tests use FakeTimeProvider from Microsoft.Extensions.TimeProvider.Testing and set the time to 2:59 pm and 3:01 pm. For the static, I check whether it's pure. A pure GstMath.Round stays static; ExchangeRates.Get does I/O, so I wrap it in an IExchangeRates instance. The SqlConnection moves behind an IOrderStore, and I test that store's SQL against a real SQL Server in Testcontainers rather than mocking ADO.NET. The sealed SDK client gets an adapter, IPaymentGateway, with just the two calls we use, in our own vocabulary.

For example, at [company] a [billing/order] service like this had [no] unit tests; after introducing [four] seams over [n] small PRs we had [n] fast tests around the cut-off and currency logic, and the next change to the cut-off rules took [time] instead of [time].

The mistake I see is wrapping everything in an interface, including pure maths. Seams are for things that are slow, non-deterministic or have side effects."


Dependency → technique

Hard dependency Why it blocks tests Technique Test with
DateTime.Now / DateTime.UtcNow Non-deterministic Inject TimeProvider FakeTimeProvider.SetUtcNow, Advance
Static with I/O (ExchangeRates.Get) Can't replace a static call Wrap static in instance + interface Stub / fake implementation
Pure static (GstMath.Round) It doesn't Leave it Call it directly
new SqlConnection(...) in method Needs a database Extract store interface (Parameterise Constructor) Fake store in unit tests; Testcontainers for the SQL
Sealed third-party client Can't mock or subclass Adapter behind own interface Fake adapter; contract/WireMock tests for the real one
Config read via ConfigurationManager Global state Inject IOptions<T> Options.Create(...)

Kinds of seam in .NET

Seam How When
Object seam Constructor injection of interface/abstract class Default choice
Subclass and override Make a method protected virtual, override in a test subclass Quick seam in a big class before you can extract
Delegate seam Inject Func<DateTimeOffset> Tiny one-off; prefer TimeProvider for time
Link seam Swap an assembly/package at build time Rare in .NET; avoid

Production example

In an order service, introducing TimeProvider and three adapters took 6 PRs, none over 150 lines. The cut-off logic went from untestable to 14 unit tests running in 40 ms, and a later daylight-saving bug (cut-off an hour early in October) was reproduced with FakeTimeProvider in a test before it was fixed.

🔍 What the interviewer is checking

Checks that the candidate can get untested legacy code under test with concrete, modern .NET techniques and good judgement about where seams are worth it.

Green flags

  • Uses the term seam and knows object seams are the C# default
  • Uses TimeProvider/FakeTimeProvider rather than inventing an IClock
  • Leaves pure statics alone; wraps impure ones
  • Adapts third-party types instead of mocking them
  • Sequences safe mechanical refactorings before tests

Red flags

  • Interfaces for everything, including maths
  • Mocks DbContext or SqlConnection to test queries
  • Uses DateTime.Now for business time on a server

📚 Learn in depth

1. Seams and enabling points

A seam is a place where you can alter behaviour without editing the code at that place. Every seam has an enabling point: where you choose which behaviour runs. For an object seam, the enabling point is the constructor call (or DI registration).

  test                    production
   |                          |
   v                          v
 new OrderService(fakeTime, fakeRates, fakeStore, fakeGateway)
                   ^ enabling point: who constructs it
 OrderService.PlaceOrder() -> _time.GetUtcNow()   <- seam

2. The legacy code dilemma

To change code safely you need tests; to add tests you need to change the code. The way out is a small set of refactorings that are safe without tests because they are mechanical and the compiler checks them: Parameterise Constructor, Extract Interface, Introduce Instance Delegator, Subclass and Override Method. Do those, get tests in place, then refactor properly.

3. How TimeProvider works

System.TimeProvider (.NET 8+, and a NuGet package Microsoft.Bcl.TimeProvider for older targets) is an abstract class with virtual GetUtcNow(), LocalTimeZone, GetTimestamp()/TimestampFrequency and CreateTimer(...). TimeProvider.System is the real clock. Because timers go through it too, Task.Delay(delay, timeProvider), CancellationTokenSource(delay, timeProvider) and PeriodicTimer overloads can run on fake time. FakeTimeProvider lets a test set the time and Advance it, firing due timers synchronously, so tests of retries and expiry don't sleep.

 production: TimeProvider.System  -> OS clock
 tests:      FakeTimeProvider     -> SetUtcNow(2026-11-20T03:59Z); Advance(TimeSpan.FromMinutes(2))

Use UTC inside and convert at the edge for business rules: a 3 pm Sydney cut-off is TimeZoneInfo.ConvertTime(utcNow, sydney).TimeOfDay < 15:00, which is correct across daylight saving; DateTime.Now on an Azure App Service gives UTC by default anyway, which is a common source of 'cut-off is 11 hours off' bugs.

4. Wrapping statics

A static method is bound at compile time, so there's no seam. Introduce an instance class that delegates to the static, put an interface on it, and change callers one at a time. When all callers use the instance, move the logic in and delete the static. Pure functions (same input, same output, no side effects) don't need this; testing through them is fine.

5. Don't mock what you don't own

Mocking a third-party client couples tests to its API shape and encodes your assumptions about its behaviour, which may be wrong. An adapter with your own narrow interface keeps the SDK at the edge; unit tests fake the adapter, and a few integration or contract tests (WireMock.Net, the provider's sandbox) check the adapter against reality.

Try it yourself

  1. Replace one DateTime.UtcNow in your codebase with an injected TimeProvider and write a test with FakeTimeProvider either side of a boundary.
  2. Use Task.Delay(TimeSpan, TimeProvider) in a retry loop and test it with Advance instead of real waiting.
  3. Wrap a static that calls HTTP behind an interface and migrate two callers.
  4. Write a Testcontainers test for an extracted store's SQL and compare its run time with the unit tests.
  5. Run a test at 2:30 am on the October daylight-saving change date in Sydney using FakeTimeProvider.

💻 Code

Before: every dependency is grabbed inside the method, so nothing can be replaced.

namespace Orders.Legacy;

using Microsoft.Data.SqlClient;

public static class ExchangeRates
{
    public static decimal Get(string currency) => throw new NotImplementedException("calls an HTTP API");
}

public sealed class PayClient   // third-party SDK type: sealed, no interface
{
    public string Charge(string token, decimal amountAud) => throw new NotImplementedException();
}

public sealed class OrderServiceBefore
{
    public string PlaceOrder(Guid orderId, decimal amount, string currency, string cardToken)
    {
        var aud = currency == "AUD" ? amount : amount * ExchangeRates.Get(currency);   // static I/O
        var sameDay = DateTime.Now.Hour < 15;                                         // server clock
        using var conn = new SqlConnection("Server=...");                             // hard-wired DB
        conn.Open();
        // ... INSERT order with sameDay flag ...
        return new PayClient().Charge(cardToken, aud);                                // sealed SDK
    }
}

After: four object seams, each passed through the constructor.

namespace Orders;

public interface IExchangeRates { Task<decimal> GetAsync(string currency, CancellationToken ct); }
public interface IOrderStore { Task SaveAsync(Guid orderId, decimal amountAud, bool sameDay, CancellationToken ct); }
public interface IPaymentGateway { Task<string> ChargeAsync(string cardToken, decimal amountAud, CancellationToken ct); }

public sealed class OrderService(
    TimeProvider time, IExchangeRates rates, IOrderStore store, IPaymentGateway payments)
{
    private static readonly TimeZoneInfo Sydney = TimeZoneInfo.FindSystemTimeZoneById("Australia/Sydney");
    private static readonly TimeSpan CutOff = new(15, 0, 0);

    public async Task<string> PlaceOrderAsync(Guid orderId, decimal amount, string currency,
        string cardToken, CancellationToken ct)
    {
        var aud = currency == "AUD" ? amount : amount * await rates.GetAsync(currency, ct);
        var sameDay = IsBeforeCutOff();
        await store.SaveAsync(orderId, aud, sameDay, ct);
        return await payments.ChargeAsync(cardToken, aud, ct);
    }

    // Business time, not server time: correct across daylight saving.
    private bool IsBeforeCutOff() =>
        TimeZoneInfo.ConvertTime(time.GetUtcNow(), Sydney).TimeOfDay < CutOff;
}

// Adapter: our narrow interface over the sealed SDK client.
public sealed class PayClientGateway(Legacy.PayClient client) : IPaymentGateway
{
    public Task<string> ChargeAsync(string cardToken, decimal amountAud, CancellationToken ct) =>
        Task.FromResult(client.Charge(cardToken, amountAud));
}

The unit test that was impossible before: fake time either side of the cut-off.

namespace Orders.Tests;

using Microsoft.Extensions.Time.Testing;   // package: Microsoft.Extensions.TimeProvider.Testing
using Orders;
using Xunit;

public sealed class OrderServiceCutOffTests
{
    private sealed class SpyStore : IOrderStore
    {
        public bool? SameDay { get; private set; }
        public Task SaveAsync(Guid id, decimal aud, bool sameDay, CancellationToken ct) { SameDay = sameDay; return Task.CompletedTask; }
    }
    private sealed class FakeRates : IExchangeRates { public Task<decimal> GetAsync(string c, CancellationToken ct) => Task.FromResult(1m); }
    private sealed class FakeGateway : IPaymentGateway { public Task<string> ChargeAsync(string t, decimal a, CancellationToken ct) => Task.FromResult("ch_test"); }

    [Theory]
    [InlineData("2026-11-20T03:59:00Z", true)]   // 2:59 pm AEDT
    [InlineData("2026-11-20T04:01:00Z", false)]  // 3:01 pm AEDT
    public async Task Same_day_dispatch_depends_on_Sydney_cut_off(string utc, bool expected)
    {
        var time = new FakeTimeProvider(DateTimeOffset.Parse(utc));
        var store = new SpyStore();
        var sut = new OrderService(time, new FakeRates(), store, new FakeGateway());

        await sut.PlaceOrderAsync(Guid.NewGuid(), 100m, "AUD", "tok_test", CancellationToken.None);

        Assert.Equal(expected, store.SameDay);
    }
}
// Program.cs
builder.Services.AddSingleton(TimeProvider.System);
builder.Services.AddSingleton<Orders.Legacy.PayClient>();
builder.Services.AddScoped<IPaymentGateway, PayClientGateway>();
builder.Services.AddScoped<OrderService>();

⚠ Common mistakes

  • Mistake: Wrapping every static, including pure helpers, in an interface. Why it is wrong: it adds indirection and DI noise with no testing benefit. Instead: only wrap statics that do I/O, read global state or are non-deterministic.
  • Mistake: Writing a custom IClock interface in new .NET 8+ code. Why it is wrong: TimeProvider is the framework abstraction, works with Task.Delay, timers and CancellationTokenSource, and has a ready-made fake. Instead: inject TimeProvider and use FakeTimeProvider.
  • Mistake: Mocking SqlConnection/SqlCommand or the EF Core DbContext to test SQL. Why it is wrong: the mock proves nothing about the real query, and it's brittle. Instead: extract a store interface for unit tests and test the store against real SQL Server with Testcontainers.
  • Mistake: Mocking the third-party SDK directly. Why it is wrong: tests encode assumptions about code you don't own and break on upgrades. Instead: an adapter with your own narrow interface, plus a few contract tests against the provider's sandbox.
  • Mistake: Changing every caller in one PR when adding constructor parameters. Why it is wrong: a big diff in code without tests. Instead: keep the old constructor chaining to the new one with real implementations, migrate callers gradually.
  • Mistake: Using DateTime.Now for a business cut-off. Why it is wrong: the server is usually in UTC (App Service, containers), so the rule is 10-11 hours off and shifts with daylight saving. Instead: GetUtcNow() converted with TimeZoneInfo for Australia/Sydney.
  • Mistake: Introducing seams with hand edits before any tests exist. Why it is wrong: the first changes are unprotected. Instead: use mechanical IDE refactorings and let the compiler check them.

🏛 Senior insight: trade-offs

Breaking dependencies is a means, not an end: the goal is a fast test around the logic you need to change. I pick the minimum set of seams that lets me test the rule I'm about to touch, and I prefer real infrastructure in a container over mocks for the data layer, because the SQL is where the bugs hide.

The other senior point is sequencing. The first edits on untested code must be the ones you can trust without tests, so they're mechanical and compiler-checked. Only after the characterisation tests are green do I make real design changes.

Technique When it fits Cost When not to
Constructor injection (object seam) Any class you control Constructor parameters, DI registration Pure functions
Subclass and override Huge class, need one seam today Test-only subclass, protected virtual As a permanent design
Adapter over SDK Third-party sealed or wide APIs One small class When the SDK already exposes a good interface
Testcontainers instead of mocking SQL, messaging, cache Slower tests (seconds), Docker in CI Pure business rules

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions characterisation tests for the legacy class Why: Checks they can pin existing behaviour before changing a core calculation
    How to 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.

  2. When: Candidate says the legacy app also uses a service locator or singletons Why: Checks they can introduce DI across a legacy app incrementally
    How to answer

    I'd use a strangler approach, not a rewrite. First, characterisation tests around the code I'll touch first. Then a single composition root (the Generic Host in modern .NET, or ServiceCollection built in the old entry point) and a bridge: the legacy ServiceLocator.Get<T>() delegates to the real IServiceProvider, so old and new code share the same instances.

    From there I convert from the edges inwards: new code and any class I touch takes constructor dependencies; statics get thin adapters behind interfaces. I track locator call count as a metric and block new usages with an analyser.

    The trade-off: for months the codebase is half old, half new, which is uglier than a rewrite plan but keeps shipping.

  3. When: Candidate uses FakeTimeProvider in unit tests Why: Checks they can apply the same fake clock across an integration test host
    How to answer

    Controlling time in an integration test makes results reproducible: a retry delay, a cache expiry and a business cut-off all move together, instead of depending on how fast the CI agent is. Register TimeProvider.System in Program.cs, then in the test call factory.WithWebHostBuilder(b => b.ConfigureTestServices(s => s.AddSingleton<TimeProvider>(fake))) with a FakeTimeProvider. Polly v8 pipelines from Microsoft.Extensions.Resilience, HybridCache and the ASP.NET Core rate limiters resolve TimeProvider from DI, so fake.Advance(...) fires retry delays, expires cache entries and moves your own rules at once. Without it, a retry test waits for real backoff delays (slow), and a cache test either sleeps or never sees an expiry. Code that uses new Timer or DateTime.UtcNow directly won't follow the fake, so ban those APIs with BannedApiAnalyzers: add the Microsoft.CodeAnalysis.BannedApiAnalyzers package and a BannedSymbols.txt (an AdditionalFiles item) listing P:System.DateTime.Now, P:System.DateTime.UtcNow and P:System.DateTimeOffset.UtcNow, which raises RS0030 at build time.

🛠 Real-world problems: how you handle them

Same-day dispatch cut-off wrong after moving to Azure App Service
Situation
An order service for [retailer] decided same-day dispatch with `DateTime.Now.Hour < 15`. After moving from an on-premises Windows server (Sydney time) to Azure App Service in Australia East, it ran in UTC. [n] orders a day were affected.
Signals
Warehouse reports that orders placed after 3 pm were flagged same-day and morning orders were not; customer complaints about missed dispatch; a spike in support tickets after [migration date].
Investigation
Compared order timestamps with dispatch flags in SQL, confirmed the App Service `WEBSITE_TIME_ZONE` was unset (UTC), and found the cut-off logic had no tests because it called `DateTime.Now`, a static rate helper and `new SqlConnection` directly.
Resolution
Immediate: set the cut-off comparison to convert UTC to Australia/Sydney with `TimeZoneInfo`. Real fix: introduced `TimeProvider` and adapters for the static and data access over [n] small PRs, then added `FakeTimeProvider` tests either side of 3 pm and across daylight-saving changes.
Prevention
A banned-API analyser rule for `DateTime.Now`/`DateTime.UtcNow` in domain code (Microsoft.CodeAnalysis.BannedApiAnalyzers), tests for time-zone and DST boundaries, and a migration checklist item for time zones.

How to tell it (STAR)

**S:** After we moved our order service to Azure App Service, the 3 pm same-day dispatch cut-off was wrong, because `DateTime.Now` was now UTC. **T:** I had to fix it fast and make sure time rules could be tested. **A:** I shipped a one-line fix converting UTC to Sydney time the same day. Then, over [n] small PRs, I injected `TimeProvider`, wrapped the static exchange-rate helper and the data access behind interfaces, and wrote `FakeTimeProvider` tests at 2:59 and 3:01 pm and across the October daylight-saving change. I also added a banned-API analyser for `DateTime.Now` in domain code. **R:** Mis-flagged orders went from [n] a day to zero, and when [later rule change] came, it shipped in [time] with tests.

More in Refactoring

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me