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

📚 Interview question

How do you write integration tests for an ASP.NET Core API? What do you run for real (database, HTTP pipeline, authentication) and what do you fake, and how do you keep the tests fast, isolated and reliable?

Integration tests for ASP.NET Core 10 APIs: WebApplicationFactory, real SQL Server with Testcontainers, faking third-party HTTP and authentication, and keeping state isolated and the suite fast.

Intermediate Theory Intermediate aspnet-core integration-testing testcontainers testing webapplicationfactory xunit

🎯 Key points

  • WebApplicationFactory<Program> runs the real host in memory via TestServer
  • Run real: middleware, routing, binding, DI, serialisation, EF Core and the database engine
  • Real SQL Server in Testcontainers, not the EF Core in-memory provider
  • Fake what you don't own: third-party HTTP (WireMock.Net or a stub handler), email, clock (FakeTimeProvider)
  • Test authentication handler or real tokens to exercise authorisation policies
  • Reset database state between tests (Respawn) and share one container per collection
  • Assert status codes, response bodies and database side effects
  • Override services with ConfigureTestServices, not by editing Program.cs

⏱ 30-second answer

Use WebApplicationFactory<Program> to start the real app in memory and send real HTTP requests through the whole pipeline: middleware, routing, model binding, validation, DI, authorisation and JSON. Run the things you own for real, including EF Core against a real SQL Server in Testcontainers, because that is where mapping, translation and migration bugs live. Fake the things you don't own: third-party HTTP APIs (WireMock.Net), email and SMS, the clock (FakeTimeProvider), and usually the identity provider via a test authentication handler. Keep tests isolated by resetting data between tests with Respawn and sharing one container per test collection. The trade-off is a few seconds of start-up for far more confidence than mocks give.

🗣 Full answer (senior)

How I would answer this in an interview

"My rule is: run everything I own for real, fake everything I don't. I start the API with WebApplicationFactory<Program>, which builds the real host from Program.cs but replaces Kestrel with an in-memory TestServer. Requests go through the real middleware, routing, model binding, validation, filters, DI and System.Text.Json. That catches the bugs unit tests can't: a missing registration, a wrong route, a renamed JSON property, an authorisation policy that lets the wrong user in.

For data I use a real SQL Server in a Testcontainers container, started once per test collection, with migrations applied at start-up. Between tests I reset the data with Respawn, which deletes rows in foreign-key order in a few milliseconds, so every test starts clean without restarting the container. I don't use the EF Core in-memory provider, because it doesn't translate LINQ to SQL or enforce constraints, so tests pass that would fail in production. What I fake: outbound HTTP to payment or address services with WireMock.Net so I can also simulate 500s and timeouts; email and SMS senders with a recording fake; time with FakeTimeProvider; and authentication with a test AuthenticationHandler that issues the claims each test needs, so I can test 401, 403 and the happy path.

The mistake I see is overriding half the app in the factory until the test no longer resembles production, or sharing data between tests so they fail depending on order. I keep overrides to ConfigureTestServices for external boundaries only, and each test creates the data it needs. A suite like that runs a few hundred tests in a couple of minutes and catches most release-blocking bugs."


Real or fake

Component Real or fake Why
Middleware, routing, binding, filters Real That's what you're testing
DI container and registrations Real Catches missing or wrong lifetimes
EF Core + SQL Server Real (Testcontainers) SQL translation, constraints, migrations
Redis, Service Bus Real container or emulator if behaviour matters, fake if incidental Depends on what the test proves
Third-party HTTP APIs Fake (WireMock.Net / stub handler) You don't own it; need fault simulation
Identity provider Fake auth handler (or real tokens in E2E) Speed and control of claims
Clock FakeTimeProvider Deterministic time
Email / SMS Recording fake No real side effects; assert what was sent

Keeping it fast and isolated

  • One WebApplicationFactory and one SQL Server container per collection fixture, not per test.
  • Apply migrations once at fixture start; reset rows with Respawn before each test.
  • Run collections in parallel with separate databases if the suite grows.
  • Avoid Thread.Sleep; poll with a timeout or use FakeTimeProvider.

What to assert

  • Status code and ProblemDetails shape for errors.
  • Response body (deserialised, or snapshot with Verify).
  • Side effects: the row in the database, the message published, the email recorded.

Production example

A team replaced 400 mock-based controller tests with 120 WebApplicationFactory tests against SQL Server in Testcontainers. CI time went from 3 to 4 minutes, and over the next quarter the number of bugs found after deployment to staging fell from about 9 per sprint to 2, mostly because EF Core translation errors and missing DI registrations were now caught on the PR.

🔍 What the interviewer is checking

Checks whether the candidate can build a realistic, isolated integration suite rather than mock-heavy tests.

Green flags

  • Names WebApplicationFactory, ConfigureTestServices and Testcontainers.
  • Clear rule for what is real and what is faked.
  • Mentions data reset (Respawn or transactions) and fixture sharing.
  • Tests authorisation, not just happy paths.

Red flags

  • Uses the in-memory provider and calls it a database test.
  • Shares mutable data between tests with no reset.
  • Disables authentication to make tests pass.

📚 Learn in depth

1. How WebApplicationFactory works

 WebApplicationFactory<Program>
   |
   | 1. finds the entry point assembly of Program
   | 2. sets content root to the API project folder
   | 3. runs Program.cs up to builder.Build(),
   |    applying your ConfigureWebHost / ConfigureTestServices overrides
   | 4. replaces IServer with TestServer (no sockets)
   v
 CreateClient() -> HttpClient whose handler calls TestServer directly

Because the real Program.cs runs, configuration from appsettings.json and appsettings.Testing.json loads, and builder.Environment can be set with UseEnvironment("Testing"). Overrides added with ConfigureTestServices run after the app's own registrations, so they win.

2. Fixtures and lifetimes in xUnit

 ICollectionFixture<ApiFixture>    -> one per collection (shared container + factory)
 IClassFixture<T>                  -> one per test class
 constructor / IAsyncLifetime      -> per test (reset data here)

A collection fixture implementing IAsyncLifetime starts the SQL Server container in InitializeAsync, builds the factory with the container's connection string, applies migrations, and creates a Respawner. Each test calls ResetAsync() first.

3. Respawn vs transactions

Approach How Pros Cons
Respawn Deletes rows in FK order, skipping __EFMigrationsHistory Works with any code, including code that commits Slight cost per test
Transaction rollback Wrap each test in a transaction and roll back Very fast Breaks when the app opens its own transaction or connection
New database per test Create from template Total isolation Slow

4. Faking authentication

Register a scheme with a custom AuthenticationHandler<AuthenticationSchemeOptions> that builds a ClaimsPrincipal from a header such as X-Test-User. Then set it as the default scheme in ConfigureTestServices. Your real authorisation policies still run, so you can assert 401 (no header), 403 (wrong role) and 200.

5. Faking outbound HTTP

If the app uses typed HttpClients via IHttpClientFactory, point their base address at a WireMock.Net server in tests. You can then return 503s or add a 5-second delay to test your resilience pipeline and timeouts.

Try it yourself

  1. Create an xUnit project referencing the API and Microsoft.AspNetCore.Mvc.Testing; add public partial class Program; to the API.
  2. Add Testcontainers.MsSql and start a container in a collection fixture.
  3. Add Respawn and reset before each test; run the suite twice and confirm it's order-independent.
  4. Add a test auth handler and write 401/403/200 tests for one endpoint.
  5. Point a typed client at WireMock.Net and assert your API returns 502 when the dependency returns 500.

💻 Code

A collection fixture with Testcontainers, Respawn and a test auth handler, plus one test (xUnit v3, .NET 10):

namespace Shop.Tests.Integration;

using System.Data.Common;
using System.Security.Claims;
using System.Text.Encodings.Web;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc.Testing;
using Microsoft.AspNetCore.TestHost;
using Microsoft.Data.SqlClient;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Respawn;
using Shop.Data;
using Testcontainers.MsSql;
using Xunit;

public sealed class ApiFixture : IAsyncLifetime
{
    private readonly MsSqlContainer _sql = new MsSqlBuilder()
        .WithImage("mcr.microsoft.com/mssql/server:2022-latest").Build();
    private Respawner _respawner = null!;
    public WebApplicationFactory<Program> Factory { get; private set; } = null!;

    public async ValueTask InitializeAsync()
    {
        await _sql.StartAsync();
        Factory = new WebApplicationFactory<Program>().WithWebHostBuilder(b =>
        {
            b.UseEnvironment("Testing");
            b.ConfigureTestServices(s =>
            {
                // Real SQL Server, test connection string
                s.RemoveAll<DbContextOptions<ShopDbContext>>();
                s.AddDbContext<ShopDbContext>(o => o.UseSqlServer(_sql.GetConnectionString()));
                // Fake identity provider, real authorisation policies
                s.AddAuthentication(TestAuthHandler.Scheme)
                 .AddScheme<AuthenticationSchemeOptions, TestAuthHandler>(TestAuthHandler.Scheme, _ => { });
            });
        });

        using (var scope = Factory.Services.CreateScope())
            await scope.ServiceProvider.GetRequiredService<ShopDbContext>().Database.MigrateAsync();

        await using var conn = new SqlConnection(_sql.GetConnectionString());
        await conn.OpenAsync();
        _respawner = await Respawner.CreateAsync(conn, new RespawnerOptions
        {
            TablesToIgnore = ["__EFMigrationsHistory"]
        });
    }

    public async Task ResetAsync()
    {
        await using var conn = new SqlConnection(_sql.GetConnectionString());
        await conn.OpenAsync();
        await _respawner.ResetAsync(conn);
    }

    public async ValueTask DisposeAsync()
    {
        await Factory.DisposeAsync();
        await _sql.DisposeAsync();
    }
}

[CollectionDefinition("api")]
public sealed class ApiCollection : ICollectionFixture<ApiFixture>;

public sealed class TestAuthHandler(IOptionsMonitor<AuthenticationSchemeOptions> o, ILoggerFactory l, UrlEncoder e)
    : AuthenticationHandler<AuthenticationSchemeOptions>(o, l, e)
{
    public const string Scheme = "Test";

    protected override Task<AuthenticateResult> HandleAuthenticateAsync()
    {
        // No header = anonymous, so tests can assert 401.
        if (!Request.Headers.TryGetValue("X-Test-Role", out var role))
            return Task.FromResult(AuthenticateResult.NoResult());

        var identity = new ClaimsIdentity([new Claim(ClaimTypes.Name, "test-user"), new Claim(ClaimTypes.Role, role!)], Scheme);
        return Task.FromResult(AuthenticateResult.Success(new AuthenticationTicket(new ClaimsPrincipal(identity), Scheme)));
    }
}
namespace Shop.Tests.Integration;

using System.Net;
using System.Net.Http.Json;
using Xunit;

[Collection("api")]
public sealed class ProductsTests(ApiFixture fixture) : IAsyncLifetime
{
    public async ValueTask InitializeAsync() => await fixture.ResetAsync(); // clean data per test
    public ValueTask DisposeAsync() => ValueTask.CompletedTask;

    [Fact]
    public async Task Create_product_requires_admin_role()
    {
        var client = fixture.Factory.CreateClient();
        client.DefaultRequestHeaders.Add("X-Test-Role", "Customer");

        var response = await client.PostAsJsonAsync("/products", new { name = "Kettle", price = 49m },
            TestContext.Current.CancellationToken);

        Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
    }
}

RemoveAll comes from Microsoft.Extensions.DependencyInjection.Extensions.

⚠ Common mistakes

  • Mistake: Using the EF Core in-memory provider for integration tests. Why it is wrong: no SQL translation, constraints or real transactions, so tests pass that fail in production. Instead: SQL Server in Testcontainers.
  • Mistake: Starting a new container and factory per test. Why it is wrong: each start costs seconds; the suite takes ten minutes. Instead: one per collection fixture and reset data between tests.
  • Mistake: Tests that depend on data left by earlier tests. Why it is wrong: they fail when run alone, in parallel or in a different order. Instead: reset with Respawn and have each test arrange its own data.
  • Mistake: Replacing so many services that the test no longer resembles production. Why it is wrong: you are testing your overrides, not the app. Instead: override only external boundaries in ConfigureTestServices.
  • Mistake: Disabling authorisation in tests with AllowAnonymous everywhere. Why it is wrong: the policies that protect real data are never tested. Instead: a test auth handler and explicit 401/403 tests.
  • Mistake: Calling real third-party sandboxes from CI. Why it is wrong: slow, rate-limited and flaky, and you can't simulate failures. Instead: WireMock.Net with recorded responses and fault cases.
  • Mistake: Only asserting status codes. Why it is wrong: a 200 with the wrong body or no database write passes. Instead: assert the body and the side effect.

🏛 Senior insight: trade-offs

Integration tests in ASP.NET Core are cheap enough now that they should cover every endpoint, but they are not a replacement for unit tests. They cost more per test (tens to hundreds of milliseconds vs single milliseconds), are worse at pinpointing a failure, and get awkward when you need to exercise twenty permutations of a pricing rule. The balance I aim for: business rules and edge cases in fast unit tests, one or a few integration tests per endpoint for wiring, data access, authorisation and contract shape, and a thin layer of E2E tests for configuration and infrastructure. The judgement is in the boundary: run what you own, fake what you don't, and keep overrides minimal so the test remains a faithful copy of production. Respawn plus a shared container gives isolation without paying container start-up per test.

The EF Core in-memory provider still has a narrow use: quick tests of logic that happens to use a DbContext but where SQL behaviour is irrelevant. It should never be what proves your queries, constraints or migrations work, because it is not relational.

Configuration matters too: tests should get their settings from an appsettings.Testing.json plus values injected from the fixture (the container's connection string, the WireMock URL), never from developer user secrets, so the same suite runs identically on a laptop and a CI agent.

Choice When it fits Cost When not to
SQL Server in Testcontainers Default for EF Core apps Container start ~10–20 s once No Docker on CI agents
SQLite in-memory Quick feedback, simple queries Low SQL Server-specific features, JSON columns, collations
Hand-written fake (test double) over a mock Stateful dependencies used by many tests Some code to maintain One-off interaction checks
Fake auth handler Policy and role tests Low Testing token validation itself
Real Entra ID tokens E2E against deployed env High PR-level tests

Measure suite time per test and the number of escaped defects; if CI time grows, parallelise collections before cutting tests.

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions Testcontainers. Why: Checks the practical details of running SQL Server containers in CI.
    How to answer

    Add the Testcontainers.MsSql package. In an xUnit collection fixture that implements IAsyncLifetime, build an MsSqlContainer with a pinned image, await StartAsync() in InitializeAsync, and await DisposeAsync() in teardown (Testcontainers' Ryuk reaper also removes orphaned containers if a CI job dies). Pass GetConnectionString() to a WebApplicationFactory by overriding configuration, apply EF Core migrations once, and reset data between tests with Respawn. If the container fails to start (for example the CI agent has no Docker), fail fast with a clear message rather than skipping. Each run gets a clean, real SQL Server, catching translation and constraint bugs that the in-memory provider hides.

  2. When: Candidate mentions faking third-party HTTP APIs. Why: Checks fault injection with WireMock.Net and resilience pipelines.
    How to answer

    Point the typed HttpClient at a WireMock.Net server in the test and configure it to return 500s, 429s with Retry-After, or delayed responses. Then assert your API's behaviour: the resilience pipeline (AddStandardResilienceHandler) retries the right number of times, the timeout fires, the circuit breaker opens, and the endpoint returns a sensible ProblemDetails (502 or 503) instead of hanging. Use FakeTimeProvider where possible so retries and timeouts don't make the test slow, and check WireMock's request log to count retries.

↩ Usually asked after

More in Test Types

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me