Testing a distributed .NET application can be challenging when multiple services depend on databases, caches, message brokers, and external APIs. A unit test can verify individual methods, but it cannot always prove that the complete application works correctly when all these components communicate with one another.
For example, a catalog API may pass all its unit tests but fail when connecting to PostgreSQL. A background worker may process messages correctly in isolation but fail when communicating with RabbitMQ. These problems often appear only when the application runs with its actual infrastructure.
.NET Aspire provides a testing approach that allows developers to start the complete distributed application during integration tests. Instead of replacing every dependency with a mock, tests can use real infrastructure resources such as PostgreSQL, Redis, and message brokers running in containers.
The Aspire.Hosting.Testing package provides the DistributedApplicationTestingBuilder class, which creates a test environment from an existing AppHost project.
In this article, we will explore how to configure Aspire integration tests, start real dependencies, test API behavior, verify database persistence, manage test resources, and avoid common testing problems.
Why Use Real Dependencies in Integration Tests?
Consider an ASP.NET Core application with the following architecture:
Commerce Application
│
├── Commerce.AppHost
│
├── Commerce.Api
│
├── Commerce.Worker
│
├── PostgreSQL
│
├── Redis
│
└── RabbitMQThe API uses PostgreSQL to store orders, Redis to cache frequently accessed information, and RabbitMQ to communicate with background workers.
A unit test can mock the database repository and verify that the API calls the expected method. However, this does not verify whether:
- The database connection string is correct.
- Entity Framework Core can connect to PostgreSQL.
- Database migrations execute successfully.
- Redis is reachable.
- Messages can be published and consumed.
- Services can discover one another.
- The complete application starts successfully.
Integration tests help verify these interactions using actual dependencies.
.NET Aspire makes this easier because the test project can reuse the same AppHost resource definitions used during development.
Understanding Aspire Integration Testing
Aspire integration testing uses the Aspire.Hosting.Testing NuGet package.
This package provides DistributedApplicationTestingBuilder, which creates a testable version of the AppHost.
The testing process generally follows these steps:
- Create a test builder using the AppHost project.
- Build the distributed application.
- Start the application and its dependencies.
- Wait for the required resources to become healthy.
- Send requests to application endpoints.
- Verify responses and application behavior.
- Dispose of the application and its resources.
Unlike traditional in-memory integration tests, Aspire tests launch the distributed application components as separate processes. Infrastructure resources can run in real containers.
This means the tests exercise actual networking, configuration, resource dependencies, and service communication.
Creating an Aspire Integration Test Project
Let's create an integration test project for a solution containing an ASP.NET Core API and PostgreSQL database.
A typical solution structure looks like this:
Commerce/
│
├── Commerce.AppHost/
│ └── Program.cs
│
├── Commerce.Api/
│ └── Program.cs
│
├── Commerce.Tests/
│ └── CatalogApiTests.cs
│
└── Commerce.slnThe integration test project needs a reference to the AppHost and the Aspire testing package.
You can create the project using the .NET CLI:
dotnet new xunit -n Commerce.Tests
dotnet add Commerce.Tests package Aspire.Hosting.Testing
dotnet add Commerce.Tests reference Commerce.AppHostUse an Aspire.Hosting.Testing package version compatible with the Aspire packages used by the AppHost.
The test machine must also have the required container runtime available when the AppHost uses containerized resources.
For example, Docker or another supported container runtime must be running before tests that require PostgreSQL containers can execute.
Configuring the AppHost for Integration Tests
The AppHost should define the same application resources that developers use during local development.
For example, the following AppHost defines PostgreSQL and the Commerce API:
var builder = DistributedApplication.CreateBuilder(args);
var postgres = builder.AddPostgres("postgres")
.WithDataVolume();
var database = postgres.AddDatabase("commerce");
builder.AddProject<Projects.Commerce_Api>("commerce-api")
.WithReference(database)
.WaitFor(database);
builder.Build().Run();The AppHost defines the database resource and connects it to the API through WithReference.
WaitFor establishes the startup dependency so the API waits for the database resource to become ready.
The API can consume the database through the Aspire PostgreSQL Entity Framework Core integration:
var builder = WebApplication.CreateBuilder(args);
builder.AddNpgsqlDbContext<CommerceDbContext>("commerce");
builder.Services.AddControllers();
var app = builder.Build();
app.MapControllers();
app.Run();The Commerce.Api project must reference the corresponding Aspire PostgreSQL integration package.
The same AppHost configuration can now be used by the development environment and the integration test project.
This reduces the chance that tests use a different infrastructure configuration from the application developers actually run.
Writing Your First Aspire Integration Test
The following example demonstrates how to start the AppHost and send an HTTP request to the Commerce API.
Create CatalogApiTests.cs in the test project:
using System.Net;
using Aspire.Hosting;
using Aspire.Hosting.Testing;
using Xunit;
public class CatalogApiTests
{
[Fact]
public async Task CatalogApi_ReturnsSuccessfulResponse()
{
using var timeout =
new CancellationTokenSource(TimeSpan.FromMinutes(2));
await using var builder =
await DistributedApplicationTestingBuilder
.CreateAsync<Projects.Commerce_AppHost>(
timeout.Token);
await using var app =
await builder.BuildAsync(timeout.Token);
await app.StartAsync(timeout.Token);
using var client =
app.CreateHttpClient("commerce-api");
using var requestTimeout =
new CancellationTokenSource(TimeSpan.FromMinutes(1));
using var response =
await client.GetAsync(
"/api/catalog",
requestTimeout.Token);
Assert.Equal(
HttpStatusCode.OK,
response.StatusCode);
}
}The test creates a testing builder using the generated AppHost project type.
The BuildAsync method builds the distributed application, and StartAsync starts its resources.
The CreateHttpClient method creates an HTTP client for the named Aspire resource. Aspire resolves the resource endpoint, so the test does not need to hardcode a localhost address or manually select a port.
The test then sends a request to the catalog endpoint and verifies that the API returns HTTP 200.
The endpoint in this example must exist in the Commerce API. The test validates the real API and its configured dependencies rather than invoking an internal controller method directly.
The application and builder use asynchronous disposal to clean up their resources after the test finishes.
Waiting for Resources to Become Healthy
Starting the application does not always mean that every service is immediately ready to handle requests.
A database container may need additional time to initialize. An API may need to complete its startup process and become healthy before the test sends requests.
Use Aspire resource notifications to wait for the required resource:
await app.ResourceNotifications.WaitForResourceHealthyAsync(
"commerce-api",
timeout.Token);You can place this statement after StartAsync and before creating the HTTP client.
For this approach to work correctly, the resource must have an appropriate health-check configuration. A running process alone does not necessarily mean that the API can serve requests successfully.
A typical ASP.NET Core application using Aspire ServiceDefaults can expose health endpoints through:
var builder = WebApplication.CreateBuilder(args);
builder.AddServiceDefaults();
var app = builder.Build();
app.MapDefaultEndpoints();
app.MapControllers();
app.Run();ServiceDefaults provides common health-check functionality in the standard Aspire project structure.
Waiting for resource health makes integration tests more reliable than using arbitrary delays such as Task.Delay.
Testing Real Database Persistence
A successful HTTP response does not necessarily prove that the database is working correctly.
A more useful integration test performs an operation that writes data and then retrieves the same data.
For example, assume the Commerce API exposes these endpoints:
- POST /api/catalog to create a product.
- GET /api/catalog/{id} to retrieve a product.
The integration test can verify the complete database interaction:
using System.Net;
using System.Net.Http.Json;
using Aspire.Hosting;
using Aspire.Hosting.Testing;
using Xunit;
public class CatalogPersistenceTests
{
[Fact]
public async Task Product_CanBeCreatedAndRetrieved()
{
using var timeout =
new CancellationTokenSource(TimeSpan.FromMinutes(2));
await using var builder =
await DistributedApplicationTestingBuilder
.CreateAsync<Projects.Commerce_AppHost>(
timeout.Token);
await using var app =
await builder.BuildAsync(timeout.Token);
await app.StartAsync(timeout.Token);
await app.ResourceNotifications.WaitForResourceHealthyAsync(
"commerce-api",
timeout.Token);
using var client = app.CreateHttpClient("commerce-api");
var product = new CreateProductRequest
{
Name = "Mechanical Keyboard",
Price = 2499
};
using var createResponse = await client.PostAsJsonAsync(
"/api/catalog",
product,
timeout.Token);
Assert.Equal(
HttpStatusCode.Created,
createResponse.StatusCode);
var createdProduct =
await createResponse.Content.ReadFromJsonAsync<ProductResponse>(
cancellationToken: timeout.Token);
Assert.NotNull(createdProduct);
using var getResponse = await client.GetAsync(
$"/api/catalog/{createdProduct.Id}",
timeout.Token);
Assert.Equal(
HttpStatusCode.OK,
getResponse.StatusCode);
var savedProduct =
await getResponse.Content.ReadFromJsonAsync<ProductResponse>(
cancellationToken: timeout.Token);
Assert.NotNull(savedProduct);
Assert.Equal(product.Name, savedProduct.Name);
Assert.Equal(product.Price, savedProduct.Price);
}
}
public sealed class CreateProductRequest
{
public string Name { get; set; } = string.Empty;
public decimal Price { get; set; }
}
public sealed class ProductResponse
{
public int Id { get; set; }
public string Name { get; set; } = string.Empty;
public decimal Price { get; set; }
}
Join the conversation! Your thoughts help the community grow.