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.
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.
"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 fromProgram.csbut replaces Kestrel with an in-memoryTestServer. 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 testAuthenticationHandlerthat 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
ConfigureTestServicesfor 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."
| 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 |
WebApplicationFactory and one SQL Server container per collection fixture, not per test.Thread.Sleep; poll with a timeout or use FakeTimeProvider.ProblemDetails shape for errors.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.
Checks whether the candidate can build a realistic, isolated integration suite rather than mock-heavy tests.
Green flags
WebApplicationFactory, ConfigureTestServices and Testcontainers.Red flags
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.
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.
| 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 |
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.
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.
Microsoft.AspNetCore.Mvc.Testing; add public partial class Program; to the API.Testcontainers.MsSql and start a container in a collection fixture.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.
ConfigureTestServices.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.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.
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.
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.
Last updated 23 Nov 2026.