Integration tests in ASP.NET Core
The difference from unit tests
Unit tests (with Moq) test one class in isolation, mocking all the dependencies. Integration tests check how many components work together - e.g. a whole HTTP request through middleware, a controller, a service, all the way to a (real or test) database.
WebApplicationFactory<T> - hosting the application in tests
public class OrdersControllerTests : IClassFixture<WebApplicationFactory<Program>>
{
private readonly HttpClient _client;
public OrdersControllerTests(WebApplicationFactory<Program> factory)
{
_client = factory.CreateClient(); // starts the WHOLE application "in-memory", without a real server
}
[Fact]
public async Task GetOrder_ExistingId_ReturnsOkWithOrder()
{
var response = await _client.GetAsync("/api/orders/1");
response.EnsureSuccessStatusCode();
var order = await response.Content.ReadFromJsonAsync<OrderDto>();
Assert.NotNull(order);
}
}
WebApplicationFactory<Program> starts your whole ASP.NET Core application (Program.cs, the entire middleware pipeline, DI, routing) in the memory of the test process - the _client sends real HTTP requests that pass through the whole real application stack, but without needing to start a separate server/port.
Replacing dependencies for tests - WithWebHostBuilder
public class OrdersControllerTests : IClassFixture<WebApplicationFactory<Program>>
{
private readonly HttpClient _client;
public OrdersControllerTests(WebApplicationFactory<Program> factory)
{
var customFactory = factory.WithWebHostBuilder(builder =>
{
builder.ConfigureServices(services =>
{
// Usuwamy prawdziwy DbContext (skonfigurowany w Program.cs)
var descriptor = services.SingleOrDefault(d => d.ServiceType == typeof(DbContextOptions<AppDbContext>));
if (descriptor != null) services.Remove(descriptor);
// We replace it with an in-memory database (InMemory) for the duration of the tests
services.AddDbContext<AppDbContext>(options => options.UseInMemoryDatabase("TestDb"));
});
});
_client = customFactory.CreateClient();
}
}
This lets you keep the real middleware/routing/DI configuration, but replace specific dependencies that are "inconvenient" in tests (e.g. a real SQL Server database with an in-memory one) - exactly the same idea as mocking in Moq, only at a higher level (the whole application, not a single class).
Testcontainers - integration tests with a REAL database (in a Docker container)
This is a more rigorous approach than an InMemory database - the EF Core InMemory database doesn't behave identically to a real SQL Server (e.g. different behaviour with some queries, transaction limitations) - Testcontainers solves this by starting a real database in a Docker container, just for the duration of the tests.
public class DatabaseFixture : IAsyncLifetime
{
private readonly MsSqlContainer _sqlContainer = new MsSqlBuilder().Build();
public string ConnectionString => _sqlContainer.GetConnectionString();
public async Task InitializeAsync()
{
await _sqlContainer.StartAsync(); // uruchamia PRAWDZIWY SQL Server w kontenerze Docker
}
public async Task DisposeAsync()
{
await _sqlContainer.DisposeAsync(); // zatrzymuje i usuwa kontener po testach
}
}
public class OrderRepositoryIntegrationTests : IClassFixture<DatabaseFixture>
{
private readonly AppDbContext _context;
public OrderRepositoryIntegrationTests(DatabaseFixture fixture)
{
var options = new DbContextOptionsBuilder<AppDbContext>()
.UseSqlServer(fixture.ConnectionString) // PRAWDZIWE zapytania SQL, nie symulacja InMemory
.Options;
_context = new AppDbContext(options);
_context.Database.Migrate(); // applies the migrations to the "fresh" database in the container
}
[Fact]
public async Task SaveOrder_WithItems_PersistsCorrectly()
{
var repository = new OrderRepository(_context);
var order = new Order { CustomerName = "Jan", Items = { new OrderItem { ProductId = 1 } } };
await repository.AddAsync(order);
await _context.SaveChangesAsync();
var saved = await _context.Orders.Include(o => o.Items).FirstAsync(o => o.Id == order.Id);
Assert.Single(saved.Items); // checks the ACTUAL SQL Server behaviour, not a simulation
}
}
The advantage: the tests check the actual behaviour of the database (constraints, data types, SQL Server-specific behaviour), not just the approximate simulation of the InMemory provider.
The cost: slower (starting a Docker container takes a few seconds), requires Docker installed on the CI/CD machine and locally on developers' machines.
The test pyramid - where it all fits
/\
/ \ E2E (end-to-end) - the fewest, the slowest, test the WHOLE system
/----\
/ \ Integration tests (WebApplicationFactory, Testcontainers) - a medium amount
/--------\
/ \ Unit tests (xUnit + Moq) - the most, the fastest, test isolated classes
/------------\
A practical rule: most tests should be unit tests (fast, isolated business logic with Moq), fewer integration tests (checking how the layers work together - controller + DI + database), and the fewest E2E (testing the whole system through the UI, the slowest and most brittle).
Summary - which type of test when
| Type of test | What it checks | Tools | Speed |
|---|---|---|---|
| Unit | One class in isolation | xUnit + Moq | Very fast (ms) |
| Integration (InMemory) | The layers working together, approximate database behaviour | WebApplicationFactory + EF InMemory |
Fast (tens of ms) |
| Integration (Testcontainers) | The layers working together, ACTUAL database behaviour | WebApplicationFactory + Testcontainers |
Slower (seconds, container start) |
| E2E | The whole system, through the real UI/API | Selenium, Playwright | The slowest |