Integration Testing in .NET
Integration tests verify that multiple components of your application work together as expected. Unlike unit tests, they involve real dependencies such as databases, external services, or the full web stack.
When to Use Integration Tests
- Validate end‑to‑end request handling
- Ensure database migrations work correctly
- Test interaction with third‑party APIs
- Catch issues that unit tests cannot see (e.g., serialization, routing)
Setting Up an Integration Test Project
Create a separate test project that references your main application and the required testing packages.
dotnet new xunit -n MyApp.IntegrationTests
cd MyApp.IntegrationTests
dotnet add reference ../MyApp/MyApp.csproj
dotnet add package Microsoft.AspNetCore.Mvc.Testing
dotnet add package FluentAssertions
dotnet add package Newtonsoft.Json
Sample Integration Test with WebApplicationFactory
using System.Net.Http;
using System.Threading.Tasks;
using FluentAssertions;
using Microsoft.AspNetCore.Mvc.Testing;
using MyApp;
using Xunit;
public class WeatherApiTests : IClassFixture<WebApplicationFactory<Startup>>
{
private readonly HttpClient _client;
public WeatherApiTests(WebApplicationFactory<Startup> factory)
{
_client = factory.CreateClient();
}
[Fact]
public async Task Get_Weather_ReturnsSuccessAndCorrectSchema()
{
// Act
var response = await _client.GetAsync("/api/weather/today");
response.EnsureSuccessStatusCode();
var json = await response.Content.ReadAsStringAsync();
// Assert
var weather = Newtonsoft.Json.JsonConvert.DeserializeObject<WeatherDto>(json);
weather.Should().NotBeNull();
weather.TemperatureC.Should().BeGreaterThan(-50);
}
}
public class WeatherDto
{
public int TemperatureC { get; set; }
public string Summary { get; set; }
}
Running Integration Tests
Use the dotnet test command. For CI pipelines, you may want to spin up a temporary database using Docker.
dotnet test MyApp.IntegrationTests/MyApp.IntegrationTests.csproj
Best Practices
- Keep tests deterministic – seed databases with known data.
- Run tests in parallel only when they are isolated.
- Use
TestServerorWebApplicationFactoryfor in‑process hosting. - Limit integration tests to critical paths to keep suite fast.