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

πŸ“š Interview question

How do you combine WebApplicationFactory with Testcontainers so each test class gets a real SQL Server database?

Wiring a Testcontainers SQL Server into WebApplicationFactory: container lifecycle with IAsyncLifetime, overriding the connection string, migrating once, resetting with Respawn, and sharing one container across classes with a database per class.

Mid-Level Coding Intermediate ef-core integration-testing sql-server testcontainers testing webapplicationfactory

🎯 Key points

  • Factory derives from WebApplicationFactory<Program> and implements IAsyncLifetime: start the container in InitializeAsync, dispose it (then base) in DisposeAsync
  • Override ConnectionStrings:* with UseSetting in ConfigureWebHost, or replace the DbContext registration in ConfigureTestServices
  • Apply EF Core migrations once per fixture through a scope from factory.Services: tests the real schema
  • Respawn resets rows between tests (ignore __EFMigrationsHistory), far faster than recreating the database
  • IClassFixture = container per class; faster: one shared container with a unique database name per class
  • Pin the image tag (mssql/server:2022-latest or a CU) and give CI Docker; about 5-15 s start-up
  • Ryuk removes orphaned containers if the test run crashes

⏱ 30-second answer

Derive a factory from WebApplicationFactory<Program> and implement IAsyncLifetime. InitializeAsync starts an MsSqlContainer, and DisposeAsync disposes the container and then the factory. In ConfigureWebHost, point the app at the container with UseSetting("ConnectionStrings:Orders", ...). You can also swap the DbContext registration in ConfigureTestServices.

Run EF Core migrations once per fixture, so the tests use the real schema. Then reset rows before each test with Respawn, which deletes data in foreign-key order and keeps the schema.

Use it as an IClassFixture and every class gets its own database. For speed, share one container and give each class a unique database name. The trade-off is that real SQL Server catches what in-memory providers hide (constraints, transactions, SQL translation), at the price of Docker and a few seconds of start-up.

πŸ—£ Full answer (senior)

How I would answer this in an interview

"WebApplicationFactory runs the real API in memory, with the full middleware pipeline, DI and routing, over a TestServer. Testcontainers gives me a real SQL Server in Docker. Together they test the API the way it runs in production, minus the network.

The wiring is short. My ApiFactory derives from WebApplicationFactory<Program> and implements IAsyncLifetime. InitializeAsync starts an MsSqlContainer. Then I touch Services to build the host, create a scope and call Database.MigrateAsync(), so the schema comes from my real migrations, not EnsureCreated. In ConfigureWebHost I call UseSetting("ConnectionStrings:Orders", _container.GetConnectionString()), and the app's normal AddDbContext picks it up. DisposeAsync disposes the container and then the base factory. Testcontainers also starts a small reaper container called Ryuk, which cleans up if the test process crashes.

Between tests I reset with Respawn. It reads the foreign-key graph once and then runs ordered DELETEs, typically 20 to 50 milliseconds, ignoring __EFMigrationsHistory. Used as an IClassFixture, every class gets its own container and database. When the suite grows I share one container and give each class its own database name, which saves 5 to 15 seconds of start-up per class. The mistake I see is using the EF Core in-memory provider instead. It doesn't enforce foreign keys or unique indexes, has no real transactions and doesn't translate LINQ to SQL, so the tests pass and production fails. Real SQL Server in a container is the only database test I trust."


The moving parts

Piece Role
WebApplicationFactory<Program> Hosts the API in memory; CreateClient() returns an HttpClient wired to TestServer
IAsyncLifetime Awaited start-up and cleanup of the container (ValueTask in xUnit v3)
MsSqlContainer (Testcontainers.MsSql) Real SQL Server; GetConnectionString() includes the mapped random port
UseSetting / ConfigureTestServices Point the app at the container, or swap services
Database.MigrateAsync() Real schema, from the same migrations as production
Respawn Fast data reset between tests

Container and database scope

Option Isolation Start-up cost Fits
Container per class (IClassFixture<ApiFactory>) Strongest 5-15 s Γ— classes Small suites
Shared container, database per class Strong One start-up + about 1-3 s migrate per class Most suites
Shared container and database, collection + Respawn Serial inside the collection One start-up Tests that need a known empty state

Production example

In a typical orders API with around 200 endpoint tests across 25 classes, moving from a container per class to one shared container with a database per class cuts the integration stage from about 6 minutes to about 2. It also caught a missing unique index that the in-memory provider had happily ignored.

πŸ” What the interviewer is checking

Checks whether the candidate can wire real infrastructure into in-memory API tests with the right lifecycle, schema and isolation choices.

Green flags

  • Uses IAsyncLifetime to start and stop the container, and disposes in the right order.
  • Overrides configuration with UseSetting or ConfigureTestServices and gets the connection string from the container.
  • Applies real migrations and resets with Respawn or a database per class.
  • Explains why the in-memory provider isn't a substitute, and mentions Docker on CI and image pinning.

Red flags

  • Uses the EF Core in-memory provider or a shared dev database.
  • Has no reset strategy, so tests depend on order.
  • Hard-codes ports or connection strings.

πŸ“š Learn in depth

1. What WebApplicationFactory does

WebApplicationFactory<TEntryPoint> finds your app's entry point (Program), runs its host-building code with a TestServer instead of Kestrel, and lets you hook in before the host is built.

Test ──HttpClient──▢ TestServer (in memory, no sockets)
                      β”‚
                      β–Ό
              your real pipeline: middleware β†’ routing β†’ endpoints β†’ DI
                      β”‚
                      β–Ό
               OrdersDbContext ──TCP──▢ Docker: mcr.microsoft.com/mssql/server:2022
                                            (random host port, started by Testcontainers)

The hooks run in this order: ConfigureWebHost (where UseSetting and ConfigureTestServices live), then your Program's registrations, then the ConfigureTestServices callbacks, so test registrations win. With minimal hosting, Program must be visible to the test project. The usual trick is public partial class Program; at the bottom of Program.cs.

2. Overriding the connection string

UseSetting(key, value) adds a high-priority configuration value, so builder.Configuration.GetConnectionString("Orders") returns the container's string. If the app reads configuration in an unusual way, replace the registration in ConfigureTestServices instead. Since EF Core 8 and later, removing only DbContextOptions<T> is not always enough, because AddDbContext also registers configuration callbacks. Overriding configuration is usually simpler and more robust.

3. Testcontainers lifecycle

MsSqlBuilder().Build() creates a container definition. StartAsync pulls the image if needed, starts it on a random free host port and waits until SQL Server accepts connections. DisposeAsync stops and removes it. Ryuk, a reaper container, watches the test process and removes its containers if the process dies without cleaning up, so killed CI jobs don't leak containers. On CI you need Docker: GitHub-hosted Ubuntu runners have it, and for Azure DevOps use a Linux agent with Docker.

4. Schema: migrations, not EnsureCreated

EnsureCreated builds the schema from the current model and skips migrations entirely, so a broken migration goes unnoticed. MigrateAsync runs the same migrations production will, which makes it a migration test for free.

5. Resetting data

Respawn's CreateAsync inspects the foreign keys once. ResetAsync deletes from child tables before parents. It's faster than dropping and migrating (milliseconds against seconds), and it keeps the schema and __EFMigrationsHistory. Combine it with a serial collection, or give each parallel class its own database so resets can't collide.

6. Speed numbers to expect

Step Typical
Image pull (first time on an agent) 30-90 s; cache it
Container start 5-15 s
Migrations 1-3 s
Respawn reset 20-50 ms
One API test 10-100 ms

Try it yourself

  1. Build the factory below, write one GET test and one POST test, and run them with Docker Desktop open. Watch the container appear and disappear.
  2. Replace MigrateAsync with EnsureCreatedAsync and add a migration with a bug. Notice which version catches it.
  3. Add a unique index and a test that inserts a duplicate. Run it against the EF Core in-memory provider and against SQL Server.
  4. Time the suite with a container per class, then refactor to a shared container with a database per class.
  5. Kill the test process mid-run and check that Ryuk removes the container.

πŸ’» Code

A complete xUnit v3 test class: the API under test, a factory that owns a SQL Server container, migrations once, and Respawn before each test.

// ----- API project: Program.cs (code under test) -----
#nullable enable
using Microsoft.EntityFrameworkCore;

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddDbContext<OrdersDb>(o =>
    o.UseSqlServer(builder.Configuration.GetConnectionString("Orders")));

var app = builder.Build();

app.MapPost("/orders", async (CreateOrder cmd, OrdersDb db, CancellationToken ct) =>
{
    var order = new Order { Id = Guid.NewGuid(), CustomerEmail = cmd.CustomerEmail, Total = cmd.Total };
    db.Orders.Add(order);
    await db.SaveChangesAsync(ct);
    return Results.Created($"/orders/{order.Id}", order);
});

app.MapGet("/orders/{id:guid}", async (Guid id, OrdersDb db, CancellationToken ct) =>
    await db.Orders.FindAsync([id], ct) is { } o ? Results.Ok(o) : Results.NotFound());

app.Run();

public sealed record CreateOrder(string CustomerEmail, decimal Total);

public sealed class Order
{
    public Guid Id { get; set; }
    public required string CustomerEmail { get; set; }
    public decimal Total { get; set; }
}

public sealed class OrdersDb(DbContextOptions<OrdersDb> options) : DbContext(options)
{
    public DbSet<Order> Orders => Set<Order>();

    protected override void OnModelCreating(ModelBuilder b) =>
        b.Entity<Order>().Property(o => o.Total).HasPrecision(18, 2);
}

public partial class Program; // makes Program visible to WebApplicationFactory
// ----- Test project -----
#nullable enable
using System.Net;
using System.Net.Http.Json;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc.Testing;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Respawn;
using Testcontainers.MsSql;
using Xunit;

namespace Orders.Api.Tests;

public sealed class ApiFactory : WebApplicationFactory<Program>, IAsyncLifetime
{
    // Pin the image so CI and laptops run the same engine.
    private readonly MsSqlContainer _sql = new MsSqlBuilder()
        .WithImage("mcr.microsoft.com/mssql/server:2022-latest")
        .Build();

    private Respawner _respawner = null!;

    public async ValueTask InitializeAsync()
    {
        await _sql.StartAsync();

        // Touching Services builds the host, so ConfigureWebHost has already run.
        using (var scope = Services.CreateScope())
        {
            var db = scope.ServiceProvider.GetRequiredService<OrdersDb>();
            // EnsureCreated keeps this sample self-contained; real projects call MigrateAsync().
            await db.Database.EnsureCreatedAsync();
        }

        _respawner = await Respawner.CreateAsync(_sql.GetConnectionString(), new RespawnerOptions
        {
            DbAdapter = DbAdapter.SqlServer,
            TablesToIgnore = ["__EFMigrationsHistory"]
        });
    }

    protected override void ConfigureWebHost(IWebHostBuilder builder) =>
        // Highest-priority config value: the app's own AddDbContext uses it.
        builder.UseSetting("ConnectionStrings:Orders", _sql.GetConnectionString());

    public Task ResetDatabaseAsync() => _respawner.ResetAsync(_sql.GetConnectionString());

    public override async ValueTask DisposeAsync()
    {
        await base.DisposeAsync();  // stop the host first...
        await _sql.DisposeAsync();  // ...then remove the container
    }
}

public sealed class OrdersEndpointTests(ApiFactory factory) : IClassFixture<ApiFactory>, IAsyncLifetime
{
    private readonly HttpClient _client = factory.CreateClient();

    public async ValueTask InitializeAsync() => await factory.ResetDatabaseAsync(); // clean rows per test
    public ValueTask DisposeAsync() => ValueTask.CompletedTask;

    [Fact]
    public async Task Created_order_can_be_read_back()
    {
        var ct = TestContext.Current.CancellationToken;

        var post = await _client.PostAsJsonAsync("/orders", new CreateOrder("[email protected]", 42.50m), ct);
        Assert.Equal(HttpStatusCode.Created, post.StatusCode);

        var get = await _client.GetAsync(post.Headers.Location, ct);
        var order = await get.Content.ReadFromJsonAsync<Order>(ct);

        Assert.Equal(42.50m, order!.Total); // decimal(18,2) round-trips through real SQL Server
    }

    [Fact]
    public async Task Unknown_order_returns_404()
    {
        var response = await _client.GetAsync($"/orders/{Guid.NewGuid()}", TestContext.Current.CancellationToken);
        Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
    }
}

For one shared container with a database per class, build the connection string with new SqlConnectionStringBuilder(sharedConnectionString) { InitialCatalog = $"orders_{Guid.NewGuid():N}" } and pass that to UseSetting. MigrateAsync then creates the database.

⚠ Common mistakes

  • Mistake: Using the EF Core in-memory provider for API tests. Why it is wrong: It doesn't enforce foreign keys or unique indexes, has no real transactions and doesn't translate LINQ to SQL, so production-only bugs pass. Instead: Use SQL Server in a container.
  • Mistake: Calling EnsureCreated in tests of an app that uses migrations. Why it is wrong: It skips the migrations, so a broken migration only fails on deployment. Instead: Call Database.MigrateAsync() once per fixture.
  • Mistake: Starting the container in the constructor or ConfigureWebHost. Why it is wrong: It blocks synchronously and can run more than once, or before the port is known. Instead: Start it in InitializeAsync, then build the host.
  • Mistake: Disposing the container before the host. Why it is wrong: Background services and connection pools throw while shutting down and add noise to the test logs. Instead: Dispose the base factory first, then the container.
  • Mistake: Not pinning the image tag. Why it is wrong: A new image version can change behaviour, and laptops and CI drift apart. Instead: Pin the tag, for example 2022-latest or a specific CU.
  • Mistake: Running Respawn from parallel classes against the same database. Why it is wrong: One class's reset deletes another class's rows mid-test. Instead: Use a database per class, or put the classes in one serial collection.
  • Mistake: Hard-coding a port or connection string. Why it is wrong: Testcontainers maps a random port, so parallel runs on one agent collide. Instead: Always use GetConnectionString().

πŸ› Senior insight: trade-offs

This combination is my default for API integration tests: it's the cheapest way to test the real pipeline, the real SQL and the real migrations together. In a code review I look for three things: migrations rather than EnsureCreated, a reset strategy that matches the parallelism, and a pinned image. Docker is the real cost. CI agents need it, and the first pull is slow, so cache the image or use a pre-warmed agent.

I measure fixture overhead from the TRX report (time per class) and widen the scope only when start-up dominates. If tests start failing intermittently after sharing a database, the cause is almost always two classes resetting or reading each other's rows.

Option When it fits Cost When not to
Testcontainers SQL Server Default for API and repository tests Docker, 5-15 s start-up Agents without Docker or nested virtualisation
SQLite in-memory Fast checks of simple queries Different SQL dialect, types and locking SQL Server-specific features (temporal tables, JSON, rowversion)
EF Core in-memory provider Almost never for data tests False confidence Anything involving constraints or transactions
Shared dev or test SQL database Legacy suites Shared state, flaky, slow Parallel CI runs

πŸ”— Follow-ups the interviewer may ask

  1. When: Candidate mentions the container start-up time or test speed. Why: Checks they know xUnit fixture scopes for sharing the container.
    How to answer

    Wrap the resource in a fixture that implements IAsyncLifetime, so the container starts once in InitializeAsync and is removed in DisposeAsync. Then pick the sharing scope:

    • IClassFixture<T>: one instance per test class.
    • ICollectionFixture<T> with [CollectionDefinition]: one instance for every class in the collection, and those classes run serially.
    • xUnit v3 assembly fixture ([assembly: AssemblyFixture(typeof(T))]): one instance for the whole run, with tests still running in parallel, so the fixture must be thread-safe.

    Share the resource, not the state. Each test creates its own rows with unique keys, or you reset the database between tests with Respawn. Respawn is a small library that deletes data in foreign-key order and keeps the schema. The trade-off is that a wider scope gives a faster suite, but one test can leak data into another.

  2. When: Candidate talks about seeding data for the integration tests. Why: Checks their test data strategy and privacy awareness.
    How to answer

    Choose the data strategy per test level:

    • Unit tests: test data builders with valid defaults, so each test states only the field it cares about.
    • Integration tests: every test creates its own rows with unique keys, and the database is reset with Respawn. No test relies on another test's data.
    • End-to-end and UAT: synthetic data seeded from code, for example Bogus with a fixed seed so runs repeat, and versioned in git.

    Build edge cases in on purpose: Unicode names, boundary amounts, Australian daylight-saving changes. Never copy production PII into lower environments. Under the Privacy Act 1988 (APP 11), a test copy is still personal information you must protect, and a leak can be a notifiable data breach. The trade-off is that synthetic data takes effort to make realistic, but it removes a whole class of privacy risk.

πŸ›  Real-world problems: how you handle them

Integration tests passed on the in-memory provider while production threw unique-key violations
Situation
An orders API [team size, product] tested its endpoints with WebApplicationFactory and the EF Core in-memory provider. After a release, creating an order with a duplicate external reference failed in production on Azure SQL with HTTP 500s.
Signals
Application Insights showed `DbUpdateException` wrapping SqlException 2601 (duplicate key) on POST /orders, about [n] failures per hour. The CI suite was green, and the unique index existed only in a migration.
Investigation
Reproduced the request locally against SQL Server in Docker: the duplicate failed immediately. Confirmed that the in-memory provider ignores unique indexes. Reviewed the test project and found `UseInMemoryDatabase` and `EnsureCreated`, so neither the index nor the migrations were ever exercised. Checked other endpoints for constraint-dependent behaviour.
Resolution
Immediate: mapped the duplicate-key exception to a 409 ProblemDetails and hotfixed. Long term: replaced the in-memory provider with a Testcontainers SQL Server in an `IAsyncLifetime` WebApplicationFactory, applied real migrations with `MigrateAsync`, added Respawn resets and wrote a test for the duplicate case.
Prevention
A Roslyn banned-API rule (BannedSymbols.txt) for `UseInMemoryDatabase` in test projects; the image pinned in the factory; CI on Linux agents with Docker and a cached image; and a checklist item that every unique index has a test that hits it.

How to tell it (STAR)

**S:** Our orders API's tests used the EF Core in-memory provider, and after a release production started returning 500s on duplicate order references. **T:** I needed to stop the errors and work out why a green suite missed them. **A:** I reproduced it against SQL Server in Docker and found the in-memory provider ignores unique indexes and our tests never ran migrations. I hotfixed the endpoint to return 409, then moved the suite to WebApplicationFactory with a Testcontainers SQL Server, real migrations and Respawn resets, and banned `UseInMemoryDatabase` in test projects. **R:** The new suite took [x] minutes longer in CI but found [n] more constraint bugs in the first month, and we had [no further] constraint-related incidents.

↩ Usually asked after

More in .NET Testing Tools

Last updated 23 Nov 2026.

🌐 Sangam's Webring

βͺ Previous 🏠 Main Next ⏩
πŸ’¬ Chat with me