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.
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.
DateTime.Now with an injected TimeProvider (.NET 8+); tests use FakeTimeProvider and SetUtcNow/Advance.new SqlConnection: extract an IOrderStore and test the SQL separately with Testcontainers.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.
"The problem with this
OrderServiceis that it reaches out and grabs everything: it readsDateTime.Nowto decide the same-day dispatch cut-off, calls a staticExchangeRates.Getthat hits an HTTP API, news up aSqlConnection, 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 callGetUtcNow(), converting toAustralia/Sydneyfor the cut-off. Tests useFakeTimeProviderfromMicrosoft.Extensions.TimeProvider.Testingand set the time to 2:59 pm and 3:01 pm. For the static, I check whether it's pure. A pureGstMath.Roundstays static;ExchangeRates.Getdoes I/O, so I wrap it in anIExchangeRatesinstance. TheSqlConnectionmoves behind anIOrderStore, 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."
| 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(...) |
| 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 |
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.
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
TimeProvider/FakeTimeProvider rather than inventing an IClockRed flags
DbContext or SqlConnection to test queriesDateTime.Now for business time on a serverA 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
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.
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.
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.
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.
DateTime.UtcNow in your codebase with an injected TimeProvider and write a test with FakeTimeProvider either side of a boundary.Task.Delay(TimeSpan, TimeProvider) in a retry loop and test it with Advance instead of real waiting.FakeTimeProvider.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>();
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.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.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.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 |
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'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.
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.
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.
Last updated 23 Nov 2026.