Lesson 77 of 93 · 6 min read · Updated

WebApplicationFactory: Running Your ASP.NET Core API In Memory for Integration Tests

WebApplicationFactory<TEntryPoint> starts your real ASP.NET Core application inside the test process. It runs the same Program.cs, builds the same DI container and middleware pipeline, and hosts it on an in-memory TestServer instead of a network port. Tests then talk to it through an ordinary HttpClient. This lesson walks through a complete factory for a Books API, explains each part, and shows the SQLite in-memory trap that breaks many first attempts.

Technical Requirements

  1. .NET 11 SDK
  2. xUnit 2.9.3
  3. Microsoft.AspNetCore.Mvc.Testing 11.0.0
  4. Microsoft.EntityFrameworkCore.Sqlite 11.0.0
  5. WireMock.Net 2.31.0 and Microsoft.Extensions.TimeProvider.Testing 11.0.0 (used by the factory, explained in later lessons)
  6. Docker is not required.

Making Program Visible to the Test Project

The factory needs a type from the application assembly as its generic argument. With top-level statements, the compiler generates a Program class that is internal, so the test project cannot see it. The fix is one line at the end of Program.cs:

M09.IntegrationApi/Program.cs

app.Run();

/// <summary>
/// Entry point for WebApplicationFactory&lt;TEntryPoint&gt;.
///
/// In projects that use top-level statements, the Program class is generated as 'internal'.
/// We redeclare it as partial so the test project can reach it.
/// (Alternative: InternalsVisibleTo.)
/// </summary>
public partial class Program;

The test project references the API project and the ASP.NET Core shared framework:

M09.IntegrationApi.Tests/M09.IntegrationApi.Tests.csproj

<ItemGroup>
<ProjectReference Include="..\M09.IntegrationApi\M09.IntegrationApi.csproj" />
</ItemGroup>

<ItemGroup>
<FrameworkReference Include="Microsoft.AspNetCore.App" />
</ItemGroup>

<ItemGroup>
<!-- WebApplicationFactory and TestServer -->
<PackageReference Include="Microsoft.AspNetCore.Mvc.Testing" />
<PackageReference Include="Microsoft.EntityFrameworkCore.InMemory" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" />
<PackageReference Include="WireMock.Net" />
<PackageReference Include="Microsoft.Extensions.TimeProvider.Testing" />
<PackageReference Include="FluentAssertions" />
</ItemGroup>

Package versions come from central package management, so the .csproj has no Version attributes.

The Factory: Real Startup, Swapped Edges

The factory subclasses WebApplicationFactory<Program>. Everything in Program.cs runs for real: DI registrations, middleware, routing, authorization policies, the hosted service. The factory only replaces the parts that touch the outside world.

PartIn productionIn the test
DatabaseSQLite file books.dbSQLite in-memory
Currency serviceExternal HTTP APIWireMock.Net server
AuthenticationReal schemeTestAuthHandler
ClockTimeProvider.SystemFakeTimeProvider

The production code does not change. All changes live on the test side.

M09.IntegrationApi.Tests/Infrastructure/BooksApiFactory.cs

public sealed class BooksApiFactory : WebApplicationFactory<Program>, IAsyncLifetime
{
private SqliteConnection? _connection;

/// <summary>A REAL HTTP server that imitates the external currency service.</summary>
public WireMockServer CurrencyServer { get; private set; } = null!;

/// <summary>
/// The clock the host uses. Time does not move unless the test calls "Advance",
/// so the background service does not run on its own between other tests.
/// </summary>
public FakeTimeProvider Clock { get; } = new(new DateTimeOffset(2026, 3, 14, 9, 0, 0, TimeSpan.Zero));

public Task InitializeAsync()
{
// Start a real HTTP server on a random port.
CurrencyServer = WireMockServer.Start();
return Task.CompletedTask;
}

public new Task DisposeAsync()
{
CurrencyServer.Stop();
CurrencyServer.Dispose();
_connection?.Dispose();
return Task.CompletedTask;
}

The factory implements xUnit's IAsyncLifetime. xUnit calls InitializeAsync once when it creates the fixture and DisposeAsync when the last test that uses it finishes. The new keyword on DisposeAsync hides the base class method with the same name, so the WireMock server and the SQLite connection are cleaned up with the fixture.

ConfigureWebHost: Where the Swaps Happen

ConfigureWebHost runs before the host is built. Its ConfigureTestServices callback runs after the application's own registrations, which is why the test can remove and replace them.

M09.IntegrationApi.Tests/Infrastructure/BooksApiFactory.cs

protected override void ConfigureWebHost(IWebHostBuilder builder)
{
// Marking the environment as Testing makes it easier to switch off production
// behaviour (HTTPS redirection, real configuration files and so on).
builder.UseEnvironment("Testing");

builder.ConfigureAppConfiguration((_, config) =>
{
// Point the external service address at the WireMock server.
config.AddInMemoryCollection(new Dictionary<string, string?>
{
["Currency:BaseAddress"] = CurrencyServer.Url,
});
});

builder.ConfigureTestServices(services =>
{
// --- Replace the database --------------------------------------
// Remove the production DbContext registration and use SQLite in-memory instead.
services.RemoveAll<DbContextOptions<AppDbContext>>();
services.RemoveAll<AppDbContext>();

_connection = new SqliteConnection("DataSource=:memory:");
_connection.Open(); // If it closes, the database disappears!

services.AddDbContext<AppDbContext>(options => options.UseSqlite(_connection));

// ... clock and authentication swaps (next lesson) ...

// --- Create the schema -------------------------------------------
using var scope = services.BuildServiceProvider().CreateScope();
var db = scope.ServiceProvider.GetRequiredService<AppDbContext>();
db.Database.EnsureCreated();
});
}

Three details are worth noting. First, the test removes both DbContextOptions<AppDbContext> and AppDbContext. AddDbContext registers both, and the options object carries the production connection string. If you remove only the context, the old options can still win. Second, the configuration override uses ConfigureAppConfiguration, so Program.cs reads Currency:BaseAddress as usual and never knows it is under test. Third, the schema is created inside the callback with a temporary service provider. That provider shares the same open connection, so the tables it creates are the tables the application sees.

Pitfall: The SQLite In-Memory Database Lives Only as Long as Its Connection

A SQLite in-memory database belongs to one connection. When that connection closes, the database is deleted. If you register the context with a connection string such as "DataSource=:memory:", EF Core opens and closes a connection per operation, and each operation sees a fresh, empty database without tables. The typical symptom is SQLite Error 1: 'no such table: Books'.

The factory avoids this by creating one SqliteConnection, opening it, and passing the connection object (not a string) to UseSqlite. The connection stays open for the lifetime of the factory and is disposed in DisposeAsync. The schema is created once with EnsureCreated.

Helpers for Arrange and Assert

Tests often need to put data in the database or read it back without going through HTTP. The factory exposes small helpers that use the application's own service provider:

M09.IntegrationApi.Tests/Infrastructure/BooksApiFactory.cs

/// <summary>Context used by tests to prepare and verify data.</summary>
public AppDbContext CreateDbContext()
{
var scope = Services.CreateScope();
return scope.ServiceProvider.GetRequiredService<AppDbContext>();
}

/// <summary>Clears the data at the START of each test — isolation between tests.</summary>
public async Task ResetDatabaseAsync()
{
await using var db = CreateDbContext();
await db.Reservations.ExecuteDeleteAsync();
await db.Books.ExecuteDeleteAsync();
}

/// <summary>Adds scenario data (only what is needed!).</summary>
public async Task SeedAsync(params Book[] books)
{
await using var db = CreateDbContext();
db.Books.AddRange(books);
await db.SaveChangesAsync();
}

Services is the host's real service provider, so the context the test gets is configured exactly like the one the endpoints get. A test then looks like this: reset, seed only what the scenario needs, call factory.CreateClient(), send a request, assert on the response. CreateClient returns an HttpClient whose handler sends requests straight into the TestServer. No socket is opened, which keeps the tests fast and free of port conflicts.

Summary

  1. WebApplicationFactory<Program> runs the real startup path in memory on a TestServer.
  2. Add public partial class Program; so the test project can use the top-level Program type.
  3. Replace only the edges (database, external services, authentication, clock) in ConfigureTestServices; production code stays unchanged.
  4. Keep one SQLite in-memory connection open for the factory's lifetime, or the database disappears.
  5. Give the factory reset and seed helpers so each test controls its own data.