Introduction
The fact that every service in a distributed application can run independently does not prove that the system works correctly. Catalog API may pass its own tests while Order API fails when Catalog is unavailable, SQL Server responds slowly, Redis cannot be reached, or RabbitMQ loses its connection. This lesson connects the observability capabilities from earlier lessons to a practical integration-testing strategy.
We will use two complementary approaches. WebApplicationFactory<TEntryPoint> is useful for running and testing one ASP.NET Core service through a test server. DistributedApplicationTestingBuilder starts the Aspire AppHost and its resources so that the complete application topology can be tested as a closed box. This lets us verify real HTTP calls, real containers, service discovery, and dependency behavior.
Assume that our sample system contains CatalogApi, OrderApi, SQL Server, Redis, and RabbitMQ. We will never use production data in tests. Instead, we will create predictable, isolated, and disposable test data for every test scenario.
1. Separate the testing layers
Integration tests verify that multiple components work together. They are slower and require more infrastructure than unit tests, so they should focus on critical system behavior rather than every method or data permutation.
| Test type | What it verifies | Example |
|---|---|---|
| Unit test | An isolated business rule | Calculating a discount |
| Service integration test | One API's pipeline, persistence, and HTTP behavior | Writing POST /orders data to SQL Server |
| Distributed integration test | The flow between multiple services and real resources | Order API working with Catalog API, Redis, and RabbitMQ |
| Resilience test | Expected behavior when a dependency fails | Bypassing the cache when Redis is unavailable |
A useful test should not assert only 200 OK. It should also consider the response body, database state, published messages, log behavior, and, when appropriate, the trace associated with the operation.
2. Service integration tests with WebApplicationFactory
In the first example, we will run only OrderApi. Add Microsoft.AspNetCore.Mvc.Testing, xUnit, and the required test SDK packages to the test project. The test project must reference the API under test.
dotnet add OrderApi.IntegrationTests package Microsoft.AspNetCore.Mvc.Testing --version 10.0.0
dotnet add OrderApi.IntegrationTests package xunit
dotnet add OrderApi.IntegrationTests package Microsoft.NET.Test.SdkFor applications using minimal hosting, add the following declaration to the API project so that the test project can access the entry point:
public partial class Program { }A basic test class starts the application on TestServer and creates an HttpClient:
using System.Net;
using Microsoft.AspNetCore.Mvc.Testing;
using Xunit;
public sealed class OrderApiTests
: IClassFixture<WebApplicationFactory<Program>>
{
private readonly HttpClient _client;
public OrderApiTests(WebApplicationFactory<Program> factory)
{
_client = factory.CreateClient();
}
[Fact]
public async Task GetOrder_ReturnsNotFoundForUnknownId()
{
using var response = await _client.GetAsync("/orders/does-not-exist");
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
}
}This approach does not automatically start real external resources in containers. You can replace or configure dependencies for the test host, but Aspire testing is a better fit when the goal is to verify the complete distributed topology.
Preparing database test data
Database integration tests should follow three rules: data must be deterministic, tests must not affect one another, and resources must be cleaned up at the end. Applying migrations can be useful, but inserting a small, explicit test dataset is often faster for focused tests.
public static async Task SeedAsync(IServiceProvider services)
{
using var scope = services.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<OrderDbContext>();
await db.Database.EnsureCreatedAsync();
db.Orders.Add(new Order
{
Id = Guid.Parse("11111111-1111-1111-1111-111111111111"),
CustomerId = "test-customer",
Status = OrderStatus.Pending
});
await db.SaveChangesAsync();
}Do not copy production connection strings into the test process. Supply connection information through environment variables, user secrets, or Aspire test configuration.
3. Testing the real application topology with Aspire
The Aspire.Hosting.Testing package starts the AppHost as a test harness. Test code does not directly access internal services of the hosted applications. Instead, the applications run as separate processes and the test observes their behavior through real endpoints. This is more realistic than WebApplicationFactory for service discovery, container dependencies, and cross-service communication.
dotnet add DistributedApp.Tests package Aspire.Hosting.TestingThe following example starts the AppHost, waits for the Order API to become healthy, and sends a request through its endpoint:
using System.Net;
using Aspire.Hosting;
using Aspire.Hosting.Testing;
using Xunit;
public sealed class DistributedOrderTests : IAsyncLifetime
{
private DistributedApplication _app = default!;
public async Task InitializeAsync()
{
var builder = await DistributedApplicationTestingBuilder
.CreateAsync<Projects.Shop_AppHost>();
_app = await builder.BuildAsync();
await _app.StartAsync();
}
public async Task DisposeAsync()
{
await _app.DisposeAsync();
}
[Fact]
public async Task OrderApi_CanReachItsDependencies()
{
using var timeout = new CancellationTokenSource(
TimeSpan.FromSeconds(30));
await _app.ResourceNotifications.WaitForResourceHealthyAsync(
"order-api", timeout.Token);
var client = _app.CreateHttpClient("order-api");
using var response = await client.GetAsync("/orders/health-sample");
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
}
}The resource name must match the name declared in the AppHost. Waiting for the health state is important; a fixed Task.Delay introduces race conditions and makes tests unreliable. Aspire may assign random ports during testing. Because service discovery is used, the test does not need to know a fixed port.
Separating the test environment in the AppHost
Persistent volumes can carry data from one test run into another. The AppHost can read a test argument and disable volumes or use separate resource names for integration tests.
var builder = DistributedApplication.CreateBuilder(args);
var useVolumes = builder.Configuration.GetValue("UseVolumes", true);
var sql = builder.AddSqlServer("sql");
var database = sql.AddDatabase("ordersdb");
if (useVolumes)
{
sql.WithDataVolume();
}
builder.AddProject<Projects.OrderApi>("order-api")
.WithReference(database)
.WaitFor(database);The test can start the AppHost with UseVolumes=false. This gives the resources a clean lifecycle and reduces hidden state between test runs.
4. Distributed failure scenarios
Failure testing is not simply stopping a resource and waiting for a random test failure. First define the expected contract. For example, when Redis is unavailable, the API may fall back to the database. When SQL Server is unavailable, creating an order should fail safely and must not publish an event for data that was never persisted.
Service failure
When Catalog API is stopped, observe the timeout, retry, and circuit-breaker behavior in Order API. The expected result may be a controlled 503 Service Unavailable, a fallback response, or a previously cached result. Keep retry counts and delays small in the test environment so failures complete quickly.
Database failure
When SQL Server becomes unavailable, verify that a write operation is not executed twice. This is especially important when retries are enabled. Check that the idempotency key prevents duplicate order creation. A test may also verify that the error log contains a dependency failure and correlation information, but avoid coupling the test to an exact log sentence.
Redis failure
For many read scenarios, Redis failure can be tolerated by falling back to the primary data store. A cache write failure should not unnecessarily fail the business operation. Stop Redis, repeat the same GET request, and verify that the result still comes from SQL Server. After Redis is restored, verify that a later request can populate the cache again.
RabbitMQ failure
When RabbitMQ is unavailable, consistency between the database transaction and event publication becomes critical. With an outbox design, the order and outbox record should be written in the same transaction, and a separate publisher should deliver the message later. The test must clearly specify whether an order is accepted while RabbitMQ is down. Deleting the outbox entry after a failed publish can create data loss.
5. Evaluating results with logs and traces
When a test fails, an exception message alone is rarely enough. First identify the failed resource, then inspect the spans in the related trace, and finally inspect logs carrying the same trace ID. The Aspire Dashboard combines resource status, console logs, structured logs, and distributed traces to support this investigation.
Never write sensitive data to application logs. Use order IDs, correlation IDs, and safe state information instead of access tokens, connection strings, complete order payloads, or personal customer data. Apply the same discipline to trace attributes.
logger.LogWarning(
"Catalog dependency unavailable for order {OrderId}. TraceId: {TraceId}",
orderId,
Activity.Current?.TraceId.ToString());Collecting resource logs when a test fails is useful in CI pipelines. However, telemetry should support the assertion rather than replace it. The primary assertions should still cover HTTP behavior, persisted data, and message delivery.
6. Common mistakes
- Using fixed delays: Replace
Task.Delay(5000)with resource readiness and health notifications. - Testing distributed behavior only with mocks: Mocks are useful for business logic, but they do not reveal DNS, connection, timeout, or serialization problems.
- Running parallel tests against one database: Use unique test identifiers, isolation, or separate databases.
- Confusing container state with application health: A container can be running while the application cannot connect to its database.
- Making retries too slow: Use controlled timeout and retry values in the test environment.
- Treating a successful HTTP response as sufficient: Also verify persistence, message publication, and cache behavior.
- Writing brittle log assertions: Prefer log levels, event names, or important structured properties over exact message text.
7. Short practice exercise
- Add an xUnit project named
DistributedApp.Testsand reference the AppHost. - Add the
Aspire.Hosting.Testingpackage. - Create a fixture that starts the AppHost once for the test class.
- Wait for Order API to become healthy and create an order with test data.
- Temporarily stop SQL Server and verify that a new order follows the expected error contract.
- Stop Redis and verify that an order query still works through the primary data store.
- Stop RabbitMQ and verify that the outbox record is preserved and published after the broker returns.
- Inspect the failed test's trace and structured logs in the Aspire Dashboard.
Conclusion
Integration tests prove more than whether individual services work in isolation. They show how the system behaves with real infrastructure, real network calls, and realistic failures. WebApplicationFactory is ideal for quickly testing one ASP.NET Core service's pipeline and application behavior. DistributedApplicationTestingBuilder validates the topology composed of the AppHost, services, and container resources using real processes.
A strong distributed testing strategy combines deterministic test data, explicit lifecycle management, health-aware startup, clearly defined failure contracts, and log-trace correlation. With these practices, the application is not merely running; its important distributed behaviors are demonstrated and repeatable, providing a solid foundation for the production and deployment topics that follow.
Sources
- https://learn.microsoft.com/en-us/aspnet/core/testing/integration-testing?view=aspnetcore-10.0
- https://learn.microsoft.com/dotnet/aspire/testing/overview
- https://learn.microsoft.com/dotnet/aspire/testing/write-your-first-test
- https://learn.microsoft.com/dotnet/aspire/testing/manage-app-host
- https://learn.microsoft.com/dotnet/aspire/testing/accessing-resources
- https://learn.microsoft.com/dotnet/aspire/fundamentals/dashboard/explore
- https://learn.microsoft.com/dotnet/aspire/fundamentals/telemetry