Skip to content

6.12 — Designing for Testability Through DI

← Roadmap · Section: 6. Dependency Injection Prev: 6.11 Third-party containers · Next: 6.13 DI traps

Markers: ⭐ · Confidence: 🔴 · Last reviewed: —


TL;DR

The practical payoff of DI is that a class can be built with fakes instead of the real thing, so tests run in milliseconds and touch nothing external.

  • A class using new to build its dependencies cannot be unit tested — the test hits the real database and sends real email.
  • Constructor injection means a unit test needs no container at all. Just new the class with test doubles.
  • The things that break testability are static access, DateTime.Now, and new inside a method.

Definitions

Term What it is What it means
Unit test a test Tests one class in isolation, with its dependencies replaced. Milliseconds.
Integration test a test Tests several real components together, usually via WebApplicationFactory.
Test double a stand-in Any fake object used in place of a real dependency.
Stub a test double Returns canned answers. You do not assert on it.
Mock a test double Records calls so you can assert they happened.
Fake a test double A working but simplified implementation — an in-memory repository.
Seam a design term A place where you can substitute behaviour without changing code. An interface is a seam.
TimeProvider an abstract class (.NET 8+) The built-in abstraction over the clock. Makes time testable.
WebApplicationFactory<T> a test class Boots the whole app in memory for integration tests. See 20.7.
NullLogger<T> a class A logger that discards everything. For tests that do not care about logging.

The concept

The argument in one comparison

Without DI:

public class OrderService
{
    private readonly SqlOrderRepository _repo = new("Server=prod;...");
    private readonly SmtpEmailSender _email = new("smtp.company.com");

    public async Task CompleteAsync(Guid id) { /* ... */ }
}

To test CompleteAsync you need a real SQL Server, a real SMTP server, and you will send an actual email every time the test runs. In practice that means nobody tests it.

With DI:

public class OrderService(IOrderRepository repo, IEmailSender email)
{
    public async Task CompleteAsync(Guid id, CancellationToken ct) { /* ... */ }
}
var service = new OrderService(fakeRepo, fakeEmail);

No database, no mail server, no container. Milliseconds, and deterministic.

That is the whole argument, and it is the one to give in an interview — testability is the concrete, everyday benefit of DI, more than the "swap implementations" story people usually lead with.

A picture: a flight simulator. You cannot practise engine failure by breaking a real engine. A simulator lets you substitute the dangerous parts and test the pilot's response safely and repeatedly.

The key insight: unit tests need no container

This surprises people who assume DI means "you need the DI framework in tests".

// No IServiceCollection, no IServiceProvider, no builder
var service = new OrderService(fakeRepo, fakeEmail, NullLogger<OrderService>.Instance);

The container is for composing the application. Tests compose one object by hand, which is simpler and faster. If a test needs a container, that is usually a sign it is an integration test rather than a unit test.


How it works

The simple version — a real unit test

[Fact]
public async Task CompleteAsync_marks_order_complete_and_sends_email()
{
    // Arrange — fakes for both dependencies
    var repo  = Substitute.For<IOrderRepository>();
    var email = Substitute.For<IEmailSender>();

    var order = new Order(Guid.NewGuid()) { CustomerEmail = "ada@example.com" };
    repo.GetAsync(order.Id, Arg.Any<CancellationToken>()).Returns(order);

    var service = new OrderService(repo, email, NullLogger<OrderService>.Instance);

    // Act
    await service.CompleteAsync(order.Id, CancellationToken.None);

    // Assert — both the state change and the side effect
    Assert.Equal(OrderStatus.Complete, order.Status);

    await email.Received(1).SendAsync(
        "ada@example.com", "Order complete", Arg.Any<string>(), Arg.Any<CancellationToken>());
}

NullLogger<T>.Instance is worth knowing — a logger that discards everything, so you do not have to mock ILogger in every test.

⚠️ The three things that break testability

DI alone is not enough. Three habits defeat it.

1. Static access

public class OrderService(IOrderRepository repo)
{
    public async Task CompleteAsync(Guid id, CancellationToken ct)
    {
        var order = await repo.GetAsync(id, ct);
        EmailSender.Send(order.CustomerEmail, "Done");    // ⚠️ static — unsubstitutable
    }
}

The repository is injected and the email is not. You cannot replace a static call, so the test sends a real email. Anything static is a hard dependency (1.5).

2. new inside a method

public async Task ProcessAsync(CancellationToken ct)
{
    var client = new HttpClient();                        // ⚠️ real network call
    var response = await client.GetAsync("https://api.example.com", ct);
}

Injection in the constructor does not help if the method constructs its own dependencies. Inject IHttpClientFactory instead (19.10).

3. DateTime.Now — the sneakiest one

public bool IsExpired(Order order) => order.ExpiresAt < DateTime.UtcNow;    // ⚠️

You cannot test the boundary. A test for "expires in one second" would have to actually wait, and a test written at 23:59 may fail at midnight. Time-dependent logic becomes untestable or flaky.

The fix, since .NET 8, is TimeProvider:

public class OrderService(IOrderRepository repo, TimeProvider timeProvider)
{
    public bool IsExpired(Order order) => order.ExpiresAt < timeProvider.GetUtcNow();
}
builder.Services.AddSingleton(TimeProvider.System);       // production
// In a test — control time exactly
var time = new FakeTimeProvider(new DateTimeOffset(2026, 1, 1, 12, 0, 0, TimeSpan.Zero));
var service = new OrderService(repo, time);

Assert.False(service.IsExpired(order));

time.Advance(TimeSpan.FromDays(31));                      // move time forward instantly

Assert.True(service.IsExpired(order));

FakeTimeProvider comes from Microsoft.Extensions.TimeProvider.Testing. Before .NET 8 you hand-rolled an IClock interface, which is why so many codebases have one. See 20.12.

How it actually works — designing the seams

A seam is somewhere you can substitute behaviour. Interfaces create seams; static calls and new destroy them.

The question to ask when designing a class: what does this touch that I cannot control in a test?

Touches Replace with
Database IRepository or inject DbContext and use SQLite in-memory
HTTP IHttpClientFactory, or a fake HttpMessageHandler
File system IFileStore
Current time TimeProvider
Randomness Inject Random, or an IRandomProvider
Environment variables IConfiguration
The current user ICurrentUser rather than IHttpContextAccessor

⚠️ That last one matters. Injecting IHttpContextAccessor into a service couples it to the web (21.12). A small ICurrentUser abstraction is trivially fakeable and keeps the service usable from a background job too.

The deeper detail — when not to abstract

⚠️ Not everything needs an interface (6.1). A pure function with no external dependencies is already testable:

public static class PriceCalculator
{
    public static decimal WithVat(decimal net, decimal rate) => net * (1 + rate);
}

There is nothing to substitute — the test just calls it. Wrapping it in IPriceCalculator adds a file and an indirection for no benefit.

The test for whether an abstraction is worth it: would I ever want to substitute this? If the answer is no, it is ceremony.

And there is a real cost to over-mocking:

// A test asserting on implementation details rather than behaviour
repo.Received(1).BeginTransaction();
repo.Received(1).GetAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
repo.Received(1).SaveAsync(Arg.Any<Order>(), Arg.Any<CancellationToken>());
repo.Received(1).Commit();

That test breaks whenever you refactor, even if the behaviour is unchanged. Assert on outcomes, not on the sequence of calls — see 20.4.


Code

A service designed to be testable, with every seam deliberate:

public class SubscriptionService(
    ISubscriptionRepository repo,
    IPaymentGateway payments,
    IEmailSender email,
    TimeProvider time,                        // ← not DateTime.UtcNow
    ILogger<SubscriptionService> logger)
{
    public async Task<RenewalResult> RenewAsync(Guid id, CancellationToken ct)
    {
        var subscription = await repo.GetAsync(id, ct)
                           ?? throw new NotFoundException(id);

        var now = time.GetUtcNow();

        if (subscription.ExpiresAt > now.AddDays(7))
            return RenewalResult.NotDue;

        var charge = await payments.ChargeAsync(
            subscription.CustomerId, subscription.Price, ct);

        if (!charge.Succeeded)
        {
            logger.LogWarning("Renewal declined for {SubscriptionId}", id);
            return RenewalResult.PaymentDeclined;
        }

        subscription.ExtendUntil(now.AddMonths(1));
        await repo.SaveAsync(subscription, ct);

        await email.SendAsync(subscription.CustomerEmail, "Renewed", "Thanks!", ct);

        return RenewalResult.Renewed;
    }
}

Every external interaction goes through an injected abstraction — including time. So:

[Fact]
public async Task RenewAsync_returns_NotDue_when_more_than_a_week_remains()
{
    var time = new FakeTimeProvider(new DateTimeOffset(2026, 6, 1, 0, 0, 0, TimeSpan.Zero));

    var subscription = new Subscription(Guid.NewGuid())
    {
        ExpiresAt = new DateTimeOffset(2026, 7, 1, 0, 0, 0, TimeSpan.Zero)   // a month away
    };

    var repo = Substitute.For<ISubscriptionRepository>();
    repo.GetAsync(subscription.Id, Arg.Any<CancellationToken>()).Returns(subscription);

    var payments = Substitute.For<IPaymentGateway>();

    var service = new SubscriptionService(
        repo, payments, Substitute.For<IEmailSender>(),
        time, NullLogger<SubscriptionService>.Instance);

    var result = await service.RenewAsync(subscription.Id, CancellationToken.None);

    Assert.Equal(RenewalResult.NotDue, result);

    // And prove we did NOT charge them
    await payments.DidNotReceive().ChargeAsync(
        Arg.Any<Guid>(), Arg.Any<decimal>(), Arg.Any<CancellationToken>());
}

That test is deterministic and instant. It would run identically in 2030, which a DateTime.UtcNow version would not.


Interview questions

Q: How does dependency injection make code testable?

Because a class declares what it needs rather than constructing it, you can supply test doubles instead of the real implementations. A service that builds its own SQL repository and SMTP client cannot be unit tested at all — the test would need a real database and would send an actual email, so in practice nobody tests it. With constructor injection the test just news up the class with fakes and runs in milliseconds with no external dependencies. Worth noting that unit tests need no container at all — the container composes the application, but a test composes one object by hand.

Q: What breaks testability even when you are using DI?

Three things. Static access, because you cannot substitute a static call — so a service that injects a repository but calls a static EmailSender still sends real email in tests. Constructing dependencies inside a method with new, since constructor injection does not help if the method builds its own HttpClient. And DateTime.Now, which is the sneakiest, because time-dependent logic then either cannot be tested at boundaries or produces tests that fail at midnight. TimeProvider in .NET 8 is the built-in fix for the last one.

Q: What is TimeProvider and why does it matter?

It is an abstraction over the clock added in .NET 8. You inject it and call GetUtcNow instead of DateTime.UtcNow, register TimeProvider.System in production, and in tests use FakeTimeProvider, which lets you set the current time and advance it instantly. That makes expiry logic, scheduling and timeouts genuinely testable — you can assert behaviour a month later without waiting. Before .NET 8 everyone hand-rolled an IClock interface for the same reason, which is why so many codebases have one.

Q: Should every class have an interface so it can be mocked?

No, and doing it reflexively adds files and indirection for nothing. The test is whether you would ever want to substitute it — a pure calculation with no external dependencies is already testable by calling it directly. There is also a cost to over-mocking: tests that assert on the exact sequence of calls rather than on outcomes break whenever you refactor, even when the behaviour is unchanged. I would abstract the things a test cannot control — database, network, file system, time, randomness — and leave pure logic alone.


Traps ⚠️

  • Static calls cannot be substituted. DI in the constructor does not help if a method calls a static.
  • new inside a method defeats constructor injection.
  • DateTime.Now makes time-dependent logic untestable or flaky. Use TimeProvider.
  • Injecting IHttpContextAccessor into a service couples it to the web. Use a small ICurrentUser abstraction.
  • Unit tests should not need a container. If yours does, it is probably an integration test.
  • Interfaces with one implementation and no test double are ceremony.
  • Asserting on call sequences rather than outcomes produces tests that break on every refactor.
  • Mocking IServiceProvider is brittle — a symptom of the service locator pattern (6.9).


Sources