Integration Testing ASP.NET Core with WebApplicationFactory
Unit vs Integration
| Type | Tests | Speed |
|---|---|---|
| Unit | One class, with fakes | Very fast |
| Integration | Several parts working together: routing, binding, validation, database | Slower but realistic |
Setup
bash
dotnet add package Microsoft.AspNetCore.Mvc.Testing
csharp
// Program.cs: make the entry point visible to tests (needed for top-level statements)
public partial class Program { }
A Custom Factory
csharp
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc.Testing;
using Microsoft.Data.Sqlite;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
public class ApiFactory : WebApplicationFactory<Program>
{
private readonly SqliteConnection _connection = new("DataSource=:memory:");
protected override void ConfigureWebHost(IWebHostBuilder builder)
{
_connection.Open(); // in-memory DB lives while the connection is open
builder.ConfigureServices(services =>
{
// remove the real DbContext registration
var descriptor = services.Single(d => d.ServiceType == typeof(DbContextOptions<AppDbContext>));
services.Remove(descriptor);
services.AddDbContext<AppDbContext>(o => o.UseSqlite(_connection));
// create tables
using var scope = services.BuildServiceProvider().CreateScope();
scope.ServiceProvider.GetRequiredService<AppDbContext>().Database.EnsureCreated();
});
}
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
_connection.Dispose();
}
}
Write Tests
csharp
using System.Net;
using System.Net.Http.Json;
using Xunit;
public class BooksApiTests(ApiFactory factory) : IClassFixture<ApiFactory>
{
private readonly HttpClient _client = factory.CreateClient();
[Fact]
public async Task Post_ValidBook_ReturnsCreated()
{
var response = await _client.PostAsJsonAsync("/api/books",
new { title = "Clean Code", author = "Robert Martin", price = 40 });
Assert.Equal(HttpStatusCode.Created, response.StatusCode);
var book = await response.Content.ReadFromJsonAsync<BookDto>();
Assert.Equal("Clean Code", book!.Title);
Assert.NotNull(response.Headers.Location);
}
[Fact]
public async Task Post_EmptyTitle_ReturnsBadRequest()
{
var response = await _client.PostAsJsonAsync("/api/books",
new { title = "", author = "X", price = 10 });
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
}
[Fact]
public async Task Get_UnknownId_ReturnsNotFound()
{
var response = await _client.GetAsync("/api/books/99999");
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
}
[Fact]
public async Task Get_Created_CanBeReadBack()
{
var created = await (await _client.PostAsJsonAsync("/api/books",
new { title = "DDD", author = "Evans", price = 55 })).Content.ReadFromJsonAsync<BookDto>();
var read = await _client.GetFromJsonAsync<BookDto>($"/api/books/{created!.Id}");
Assert.Equal("DDD", read!.Title);
}
}
What just happened? No real server port is opened.
WebApplicationFactory starts your whole app in memory, and HttpClient talks to it directly. Routing, middleware, filters and validation all run for real.
Testing Protected Endpoints
Replace authentication in the test host with a fake scheme that always signs in a test user, or call the login endpoint and add the bearer token:
csharp
_client.DefaultRequestHeaders.Authorization =
new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", token);
Tips
- Use a fresh database per test class (or reset between tests) so tests stay independent
- For SQL Server-specific behavior use Testcontainers to start a real database in Docker
- Replace external services (email, payment) with fakes in
ConfigureServices - Keep integration tests focused on important flows; unit tests cover details
SQLite vs SQL Server: They behave differently in some cases such as case sensitivity and some functions. Use Testcontainers when exact production behavior matters.
Conclusion
WebApplicationFactory runs your real application in memory so you can test endpoints end to end. Swap the database and external services, then assert on status codes and JSON.
Quick Summary: WebApplicationFactory + in-memory SQLite + HttpClient.

