Lesson 91 of 93 · 6 min read · Updated

System Testing a Distributed App with .NET Aspire: AppHost and Aspire.Hosting.Testing

Testcontainers tests build their infrastructure by hand in a fixture: this container, that connection string, this migration. That is ideal for testing one piece of infrastructure at a time. A distributed application also needs a few tests that start the whole system the way a developer runs it locally. .NET Aspire describes that system in one AppHost project, and Aspire.Hosting.Testing can start the same AppHost from a test. This lesson builds a small AppHost and two end-to-end system tests on top of it.

Technical Requirements

  1. .NET 11 SDK
  2. Docker
  3. Aspire 17.0.0: Aspire.Hosting.AppHost, Aspire.Hosting.Dotnet, Aspire.Hosting.PostgreSQL, Aspire.Hosting.Redis and Aspire.Hosting.Testing
  4. The Aspire CLI, installed with dotnet tool install -g Aspire.Cli or from https://get.aspire.dev
  5. xUnit 2.9.3 and FluentAssertions 7.2.2

The AppHost: One Description of the System

The AppHost is the application's resource graph: which containers run, which connection strings the API receives, and who waits for whom.

M10.AppHost/AppHost.cs

var builder = DistributedApplication.CreateBuilder(args);

// The image tags match the Testcontainers fixture and are PINNED: no "latest".
var postgres = builder.AddPostgres("postgres")
.WithImageTag("17-alpine");

var ticketsDb = postgres.AddDatabase("tickets");

var redis = builder.AddRedis("redis")
.WithImageTag("7-alpine");

// The API receives its connection strings under their existing names ("Postgres", "Redis"),
// so Program.cs needs no Aspire-specific code.
// The API project has no launchSettings.json; we define the HTTP endpoint EXPLICITLY here.
// Project v2: the project is added by its PATH relative to the AppHost, not via a generated Projects.* type.
// AddDotnetProject is still experimental (ASPIREDOTNETPROJECT001); the warning is disabled for this statement only.
#pragma warning disable ASPIREDOTNETPROJECT001
builder.AddDotnetProject("api", "../M10.ContainerApi/M10.ContainerApi.csproj")
.WithHttpEndpoint()
.WithReference(ticketsDb, connectionName: "Postgres")
.WithReference(redis, connectionName: "Redis")
.WithEnvironment("Database__MigrateOnStartup", "true")
.WithHttpHealthCheck("/health")
.WaitFor(ticketsDb)
.WaitFor(redis);
#pragma warning restore ASPIREDOTNETPROJECT001

builder.Build().Run();

A few lines deserve attention. WithReference(..., connectionName: "Postgres") injects the connection string as ConnectionStrings__Postgres, the name the API already reads, so the API has no dependency on Aspire. WaitFor makes the API start only after PostgreSQL and Redis are healthy. WithHttpHealthCheck("/health") tells Aspire how to decide that the API itself is healthy.

The AppHost uses the Aspire 17 "Project v2" model. The project file is a plain Microsoft.NET.Sdk project with an explicit Aspire.Hosting.AppHost package, instead of the older Aspire.AppHost.Sdk:

M10.AppHost/M10.AppHost.csproj

<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<OutputType>Exe</OutputType>
<UserSecretsId>m10-apphost-7c2f4e1a</UserSecretsId>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Aspire.Hosting.AppHost" />
<PackageReference Include="Aspire.Hosting.Dotnet" />
<PackageReference Include="Aspire.Hosting.PostgreSQL" />
<PackageReference Include="Aspire.Hosting.Redis" />
</ItemGroup>

</Project>

Package versions come from central package management, so the project file lists names only. The API is not a ProjectReference here; AddDotnetProject points to its .csproj by path.

Pitfall: in this model the orchestrator (DCP) and the dashboard come from the Aspire CLI bundle. If the CLI is not installed, the AppHost does not build. Install it on every developer machine and on every CI runner before the build step.

Letting the API Migrate Its Own Database

With Testcontainers, the test fixture applied the migrations. Under Aspire the database starts as an empty container, so the API applies migrations at startup when a flag is set. The AppHost sets it with Database__MigrateOnStartup=true:

M10.ContainerApi/Program.cs

// With Aspire the database arrives as an empty container.
// Applying migrations at application startup is enabled only by this flag;
// Testcontainers tests run the migration in their own fixture.
if (app.Configuration.GetValue<bool>("Database:MigrateOnStartup"))
{
await using var scope = app.Services.CreateAsyncScope();
await scope.ServiceProvider.GetRequiredService<TicketDbContext>().Database.MigrateAsync();
}

The double underscore in the environment variable maps to the : separator in .NET configuration.

Starting the Whole AppHost from a Test

The test project references the AppHost project and uses DistributedApplicationTestingBuilder. The fixture starts everything once per test class, with a time limit:

M10.AppHost.Tests/AppHostSystemTests.cs

/// <summary>
/// The AppHost is EXPENSIVE: it is started ONCE per class.
/// Startup and the wait for health are done with a TIME LIMIT,
/// so the test does not hang forever if a Docker image cannot be pulled.
/// </summary>
public sealed class AppHostFixture : IAsyncLifetime
{
private static readonly TimeSpan StartupTimeout = TimeSpan.FromMinutes(3);

public DistributedApplication App { get; private set; } = null!;

public async Task InitializeAsync()
{
using var cts = new CancellationTokenSource(StartupTimeout);

var builder = await DistributedApplicationTestingBuilder
.CreateAsync<Projects.M10_AppHost>(cts.Token);

App = await builder.BuildAsync(cts.Token);
await App.StartAsync(cts.Token);

// Observable condition: wait until the API passes its /health check.
// Thanks to WaitFor in the AppHost, the API only starts when PostgreSQL and Redis are ready.
await App.ResourceNotifications
.WaitForResourceHealthyAsync("api", cts.Token);
}

public async Task DisposeAsync()
{
if (App is not null)
{
await App.DisposeAsync();
}
}
}

The same CancellationTokenSource limits the build, the start and the health wait together. On a CI runner with a slow network, the test fails after three minutes with a cancellation instead of blocking the pipeline. WaitForResourceHealthyAsync("api") is the observable condition: no sleeps, no polling loops in the test.

Projects.M10_AppHost is a type generated from the test project's reference to the AppHost project; the dot in the project name becomes an underscore. Three minutes is generous on purpose: the first run on a clean machine pulls the PostgreSQL and Redis images before anything can start.

The tests themselves call the API over real HTTP:

M10.AppHost.Tests/AppHostSystemTests.cs

[Trait("Kapsam", "Sistem")]
public class AppHostSystemTests(AppHostFixture fixture) : IClassFixture<AppHostFixture>
{
[Fact]
public async Task CreatedTicket_CanBeReadBack_ThroughTheWholeStack()
{
// Arrange: a unique business key, so tests on the shared AppHost do not pollute each other.
using var client = fixture.App.CreateHttpClient("api");
var reference = $"DST-{Random.Shared.Next(1000, 9999)}";

// Act: the write goes to PostgreSQL, the first read to the database + Redis, over real HTTP.
var created = await client.PostAsJsonAsync("/api/tickets", new
{
reference,
subject = "Aspire uçtan uca",
customerEmail = "musteri@ornek.com",
priority = 2,
tags = new[] { "aspire" },
});
var read = await client.GetAsync($"/api/tickets/{reference}");

// Assert
created.StatusCode.Should().Be(HttpStatusCode.Created);
read.StatusCode.Should().Be(HttpStatusCode.OK);

var body = await read.Content.ReadFromJsonAsync<TicketDto>();
body!.Reference.Should().Be(reference);
body.Subject.Should().Be("Aspire uçtan uca");
}

private sealed record TicketDto(string Reference, string Subject);
}

CreateHttpClient("api") returns a client whose base address points to the API's endpoint, wherever Aspire placed it. The class carries a trait so the pipeline can select or exclude these slower system tests. A second test in the class simply checks that /health returns 200.

Testcontainers or Aspire?

Testcontainers testsAspire system tests
What startsThe containers the test asks forThe whole AppHost graph (containers and projects)
Where the setup livesIn the test fixture, by handIn the AppHost, the same as local development
SpeedFast (shared fixture)Slower
When to useInfrastructure behaviour, query fidelityA small number of end-to-end system tests

They answer different questions, and they can catch different bugs. A Testcontainers test finds that a query behaves differently on PostgreSQL. An Aspire test finds that the API reads the wrong connection string name, or that it starts before the database is ready. Keep many of the first kind and a few of the second.

Summary

  1. An Aspire AppHost describes containers, projects, connection strings and startup order in one place.
  2. Aspire.Hosting.Testing starts that same graph from a test, so system tests use the local development setup.
  3. Limit startup with a CancellationTokenSource and wait for WaitForResourceHealthyAsync instead of sleeping.
  4. Aspire 17 "Project v2" uses Microsoft.NET.Sdk, AddDotnetProject by path, and needs the Aspire CLI installed.
  5. Use Testcontainers for focused infrastructure tests and Aspire for a few end-to-end system tests.