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

📚 Interview question

How do you use dependency injection in tests? Show how you replace services in an ASP.NET Core integration test with WebApplicationFactory and ConfigureTestServices, when you use fakes versus mocks, and why unit tests usually shouldn't need a container at all.

Shows testing with DI: constructor-injected unit tests without a container, WebApplicationFactory with ConfigureTestServices to replace services, RemoveAll and Replace, fakes vs mocks, FakeTimeProvider, and testing the composition root with ValidateOnBuild.

Mid-Level Coding Intermediate aspnet-core dependency-injection integration-testing mocking testing webapplicationfactory

🎯 Key points

  • Unit tests: construct the class directly with fakes; no container needed
  • Integration tests: WebApplicationFactory<Program> boots the real host and container; subclass it and override ConfigureWebHost for shared setup
  • ConfigureTestServices runs after the app's registrations, so replacements win
  • Use RemoveAll<T>() then Add, or Replace, to swap a registration explicitly; keep the original lifetime
  • Resolve scoped services (DbContext for seeding) via factory.Services.CreateScope(), never from the root
  • Fakes (in-memory implementations, FakeTimeProvider from .NET 8+) for state; mocks for verifying interactions at boundaries
  • A composition-root test with ValidateOnBuild and ValidateScopes catches missing registrations; run it in CI on every PR
  • Make Program visible to tests (public partial class Program or InternalsVisibleTo)

⏱ 30-second answer

Good DI makes unit tests container-free: if a class takes its dependencies through the constructor, the test just calls new OrderService(fakeRepo, fakeClock).

For integration tests, WebApplicationFactory<Program> boots the real app and container in memory. In ConfigureTestServices, which runs after Program.cs registrations, you swap external boundaries: services.RemoveAll<IPaymentGateway>(); services.AddSingleton<IPaymentGateway, FakePaymentGateway>();.

Prefer fakes (in-memory implementations, FakeTimeProvider) for state, and mocks only to verify interactions at boundaries.

The trade-off: replacing too much tests your mocks instead of your app; replace only what crosses a process boundary.

🗣 Full answer (senior)

How I would answer this in an interview

"I think about it at two levels. For unit tests, DI's job is to make the container unnecessary. If OrderService takes IOrderRepository and TimeProvider in its constructor, my test constructs it directly with an in-memory repository and FakeTimeProvider. If I find myself building a ServiceCollection in a unit test, it usually means the class has hidden dependencies or does too much.

For integration tests I want the real composition root, because that's where registration bugs live. WebApplicationFactory<Program> runs Program.cs in memory with a TestServer. I override with WithWebHostBuilder(b => b.ConfigureTestServices(services => ...)). ConfigureTestServices runs after the app's own registrations, so a plain Add would already win for single resolution, but I still do RemoveAll<T>() then Add so it's explicit and so IEnumerable<T> consumers don't see both. I replace only things that leave the process: the payment gateway, the email sender, the clock, external HTTP APIs. The database I'd rather run for real in a Testcontainers SQL Server than swap for the EF in-memory provider, which behaves differently.

On fakes versus mocks: fakes are working lightweight implementations, like an in-memory email outbox I can assert against. Mocks verify that a call happened with certain arguments. I use mocks sparingly, at boundaries, because heavy mocking couples tests to implementation details. The mistake I see is integration tests that mock half the app's own services, which then pass while production is broken."


Where DI shows up in each kind of test

Test type Container? How dependencies are supplied
Unit test No new Sut(fake1, fake2)
Composition-root test Yes, the real one Build host with ValidateOnBuild + ValidateScopes, resolve key services
Integration test Yes, the real one WebApplicationFactory + ConfigureTestServices swaps boundaries
End-to-end test Deployed app No swapping; test environment configuration

Fake, stub or mock?

Double What it is Use for
Fake Working simplified implementation (in-memory repo, FakeTimeProvider) State-based assertions; most cases
Stub Returns canned answers Driving a branch
Mock Records and verifies calls Asserting an interaction at a boundary ("sent exactly one email")

Production example

A team's integration tests mocked the repository and the domain service, so they passed while a missing registration for a new validator crashed the endpoint in staging. Switching to the real composition root with only email and payments faked, plus a ValidateOnBuild test, caught the next two missing registrations in CI. The suite went from 40 seconds to 70 seconds, a cost the team accepted.

🔍 What the interviewer is checking

Checks the candidate uses DI to make tests simple and realistic, not to mock everything.

Green flags

  • Unit tests without a container
  • Knows ConfigureTestServices runs after app registrations and uses RemoveAll
  • Replaces only external boundaries and the clock
  • Mentions a composition-root test with validation on

Red flags

  • Mocks the app's own services in integration tests
  • Relies on the EF in-memory provider for database behaviour
  • Builds a container in every unit test

📚 Learn in depth

1. How WebApplicationFactory hooks in

Test ──▶ WebApplicationFactory<Program>
            │ runs Program.cs (top-level statements) via a host factory hook
            │   builder.Services.Add...           ← app registrations
            │   ConfigureTestServices(...)        ← test overrides, run after
            ▼
          TestServer (in-memory, no sockets)
            │
          HttpClient from factory.CreateClient()

Because ConfigureTestServices callbacks run after the app's ConfigureServices, your registrations come last. With top-level statements you expose Program to the test project using public partial class Program; or InternalsVisibleTo.

2. Replacing registrations safely

  • services.RemoveAll<T>() + services.AddX<T, Fake>(): explicit, clears multi-registrations.
  • services.Replace(ServiceDescriptor.Singleton<T, Fake>()): removes only the first registration.
  • For typed HttpClients, replace the primary handler with ConfigurePrimaryHttpMessageHandler or register a stub HttpMessageHandler so no real calls leave.

3. Time and randomness

.NET 8 introduced TimeProvider; Microsoft.Extensions.TimeProvider.Testing provides FakeTimeProvider with Advance(). Inject TimeProvider instead of calling DateTime.UtcNow, then replace it in tests.

4. The composition-root test

using var factory = new WebApplicationFactory<Program>()
    .WithWebHostBuilder(b => b.UseDefaultServiceProvider(o => { o.ValidateOnBuild = true; o.ValidateScopes = true; }));
_ = factory.Services; // builds the host; throws on missing registrations

It catches missing registrations and scoped-in-singleton problems that only appear in non-Development environments where validation is off by default.

5. Why not the container in unit tests

A container in a unit test hides which dependencies matter, makes tests slower, and lets the test pass even if the constructor grows. Direct construction makes the compiler tell you when dependencies change.

Try it yourself

  1. Write a unit test for a service that uses TimeProvider, using FakeTimeProvider.Advance(TimeSpan.FromDays(31)).
  2. Create a WebApplicationFactory test that replaces IEmailSender with an in-memory outbox and asserts one email was "sent".
  3. Use Replace when two IEmailSenders are registered and check which ones IEnumerable<IEmailSender> returns; then use RemoveAll.
  4. Add the composition-root test, delete a registration and watch CI fail.
  5. Swap the EF in-memory provider for a Testcontainers SQL Server and find a query that behaves differently.

💻 Code

An integration test that swaps only external boundaries, and a container-free unit test.

// Program.cs (end of file): expose Program to the test project.
public partial class Program;
namespace Orders.Tests;

using System.Net;
using System.Net.Http.Json;
using Microsoft.AspNetCore.Mvc.Testing;
using Microsoft.AspNetCore.TestHost;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.Time.Testing;
using Xunit;

public sealed class PlaceOrderTests(WebApplicationFactory<Program> factory)
    : IClassFixture<WebApplicationFactory<Program>>
{
    [Fact]
    public async Task Placing_an_order_sends_one_confirmation_email()
    {
        var outbox = new InMemoryEmailSender();
        var clock = new FakeTimeProvider(new DateTimeOffset(2026, 11, 19, 9, 0, 0, TimeSpan.FromHours(11)));

        var client = factory.WithWebHostBuilder(b => b.ConfigureTestServices(services =>
        {
            // Runs after Program.cs registrations; RemoveAll makes the swap explicit.
            services.RemoveAll<IEmailSender>();
            services.AddSingleton<IEmailSender>(outbox);
            services.RemoveAll<TimeProvider>();
            services.AddSingleton<TimeProvider>(clock);
        })).CreateClient();

        var response = await client.PostAsJsonAsync("/orders", new { CustomerEmail = "[email protected]", Total = 99.95m });

        Assert.Equal(HttpStatusCode.Created, response.StatusCode);
        Assert.Single(outbox.Sent);
    }
}

// A fake: a real, simple implementation we can assert against.
public sealed class InMemoryEmailSender : IEmailSender
{
    public List<(string To, string Subject)> Sent { get; } = [];
    public Task SendAsync(string to, string subject, CancellationToken ct)
    {
        Sent.Add((to, subject));
        return Task.CompletedTask;
    }
}
// Unit test: no container, the constructor is the seam.
[Fact]
public void Order_is_overdue_after_30_days()
{
    var clock = new FakeTimeProvider(DateTimeOffset.Parse("2026-10-01T00:00:00Z"));
    var sut = new OverdueChecker(clock);
    clock.Advance(TimeSpan.FromDays(31));
    Assert.True(sut.IsOverdue(DateTimeOffset.Parse("2026-10-01T00:00:00Z")));
}

⚠ Common mistakes

  • Mistake: Building a ServiceCollection in unit tests. Why it is wrong: it hides dependencies and slows tests; the class should be constructible directly. Instead: new Sut(fakes...).
  • Mistake: Replacing your own services in integration tests. Why it is wrong: the test no longer exercises the real wiring, so registration bugs slip through. Instead: replace only external boundaries.
  • Mistake: Using Replace when several implementations are registered. Why it is wrong: it only removes the first, so IEnumerable<T> consumers still get the real one. Instead: RemoveAll<T>() then add the fake.
  • Mistake: Using the EF Core in-memory provider as a database substitute. Why it is wrong: no relational behaviour, transactions or SQL translation, so tests pass on queries that fail in SQL Server. Instead: SQLite in-memory for speed or Testcontainers SQL Server for fidelity.
  • Mistake: Mocking everything with strict mocks and verifying every call. Why it is wrong: tests break on refactors that don't change behaviour. Instead: fakes for state, mocks only for boundary interactions.
  • Mistake: Calling DateTime.UtcNow directly. Why it is wrong: time-dependent logic can't be tested deterministically. Instead: inject TimeProvider and use FakeTimeProvider.
  • Mistake: Never testing the composition root outside Development. Why it is wrong: ValidateOnBuild/ValidateScopes are off by default in other environments. Instead: add a test that builds the host with both enabled.

🏛 Senior insight: trade-offs

The point of DI in tests isn't mocking; it's controlling the boundaries. I aim for many fast unit tests with direct construction, a handful of integration tests per feature through WebApplicationFactory that keep my own code real, and one composition-root test that fails CI on any missing or mis-scoped registration. That mix catches the bugs that actually reach production: wiring, configuration and SQL behaviour.

For shared setup I subclass WebApplicationFactory<Program> and override ConfigureWebHost, calling builder.ConfigureTestServices(...) and UseEnvironment("Testing") there, so every test class gets the same boundaries swapped. Scoped services such as DbContext for seeding are resolved inside using var scope = factory.Services.CreateScope(), keeping lifetimes the same as production. These tests are a quality gate in the PR pipeline, not an optional nightly job: they are the only automated check that the real container, configuration binding and middleware order still work together.

Option When it fits Cost When not to
Direct construction with fakes Unit tests of domain and application logic Very low Testing wiring or middleware
WebApplicationFactory + ConfigureTestServices Endpoint and pipeline behaviour Seconds per test class Pure logic tests
Mocks (Moq, NSubstitute) Verifying boundary interactions Brittle if overused State you can assert on a fake
Testcontainers database Queries, transactions, migrations Docker, slower CI Logic that doesn't touch the database

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions WebApplicationFactory or organising Minimal API endpoints Why: Checks structuring endpoints so they are easy to test
    How to answer

    I'd turn Program.cs back into a composition root and move endpoints into feature folders. Each feature gets one extension method, MapOrderEndpoints(this IEndpointRouteBuilder app), that creates a MapGroup("/orders") and applies shared metadata once: RequireAuthorization, WithTags, endpoint filters, rate limiting. Handlers become named static methods that return Results<Ok<OrderDto>, NotFound> built with TypedResults, so every outcome is compile-time checked and appears in the OpenAPI document. Then testing is easy at two levels: unit tests call the static handler directly and assert the result type, and integration tests use WebApplicationFactory<Program> with ConfigureTestServices to swap the database or external clients. The trade-off: a little more structure up front, in exchange for endpoints that stay readable at 80 or 800.

  2. When: Candidate uses Replace or RemoveAll Why: Checks exact registration semantics when swapping services
    How to answer

    IServiceCollection is just a list of ServiceDescriptors: a service type, an implementation (type, instance or factory delegate) and a lifetime. AddSingleton, AddScoped and AddTransient append to that list.

    • If you register the same service type several times, injecting T gives you the last registration, while injecting IEnumerable<T> gives you all of them in registration order.
    • TryAdd* adds only if nothing is registered for that service type, which is how libraries provide overridable defaults. TryAddEnumerable adds only if that exact implementation isn't already there.
    • Replace swaps the first registration; RemoveAll clears them.

    The trade-off: ordering makes overrides easy but silent, so registration order bugs are easy to write and hard to see.

  3. When: Candidate says DI makes code testable Why: Checks the underlying IoC, DI and DIP concepts
    How to answer

    Inversion of control (IoC) is the broad idea that something else controls the flow and object creation: the framework calls your code, not the other way round. Dependency injection (DI) is a specific IoC technique: a class declares what it needs, usually as constructor parameters, and a caller or container supplies it. The Dependency Inversion Principle (DIP) is the "D" in SOLID: high-level code depends on abstractions it owns, and low-level details implement them.

    In ASP.NET Core you register services on builder.Services in Program.cs (the composition root), and the built-in container builds controllers, endpoints and middleware with their dependencies.

    The trade-off: DI buys testability and replaceable parts at the cost of indirection; it is a tool, DIP is the design goal.

🛠 Real-world problems: how you handle them

Green integration tests, broken endpoint in staging
Situation
An order API at [company] had [n] integration tests using WebApplicationFactory, but the tests replaced the repository, validators and domain service with mocks. A release added a new IValidator<PlaceOrder> implementation.
Signals
CI was green. In staging, POST /orders returned 500 with 'Unable to resolve service for type IValidator<PlaceOrder>' in Application Insights exceptions, affecting 100% of order placements in that environment.
Investigation
Reproduced locally in Production environment mode, where ValidateOnBuild is off by default, so the error only appeared on the first request. Read the test setup and saw ConfigureTestServices replacing the validator with a mock, so the missing registration was never exercised. Enumerated the real IServiceCollection in a quick test and confirmed no registration for the new validator.
Resolution
Immediate: added the missing registration and redeployed staging. Real fix: rewrote the integration tests to keep all in-process services real and replace only the payment gateway, email sender and TimeProvider; added a composition-root test that builds the host with ValidateOnBuild and ValidateScopes enabled.
Prevention
Team guideline: integration tests replace only out-of-process boundaries. The composition-root test runs in CI on every PR. Added a Testcontainers SQL Server fixture for repository behaviour instead of mocks.

How to tell it (STAR)

**S:** At [company] our order API had a green integration suite, yet a release broke order placement in staging with a missing DI registration. **T:** I was asked to work out why the tests didn't catch it and stop it recurring. **A:** I found the tests mocked our own validators and services in ConfigureTestServices, so the new validator's registration was never exercised, and ValidateOnBuild was off outside Development. I rewrote the tests to replace only payments, email and the clock, and added a composition-root test that builds the host with ValidateOnBuild and ValidateScopes on. **R:** The suite got about [30] seconds slower, but it caught the next [two] missing registrations in CI, and we've had [zero] DI-related staging failures since.

↩ Usually asked after

More in DI Core Concepts

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me