Skip to content

API Testing with Aspire

Learn how to write API integration tests using Aspire's DistributedApplicationTestingBuilder.

๐Ÿ“‹ Overview

Property Value
Goal Test API endpoints using Aspire's distributed testing framework
Prerequisites .NET 10 SDK, Aspire project with AppHost
Time 15 minutes

This guide demonstrates how to create integration tests for your API endpoints using the Aspire.Hosting.Testing library.


๐Ÿ“ฆ Required Packages

Add the following NuGet packages to your test project:

<PackageReference Include="Aspire.Hosting.Testing" />
<PackageReference Include="Microsoft.Extensions.Http.Resilience" />
<PackageReference Include="xunit" />

๐Ÿงช Test Structure

Namespaces

using Aspire.Hosting.Testing;
using Microsoft.Extensions.DependencyInjection;
using System.Net;

Test Class

public class ApiTests
{
    // Your test methods go here
}

๐Ÿ“ Example: Testing API Root Endpoint

This test verifies that the root endpoint (/) returns an HTTP 200 OK status code.

Steps

  1. Arrange: Create and configure the distributed application
  2. Act: Send HTTP request to the API
  3. Assert: Verify the response status code

Code

[Fact]
public async Task Get_Root_Returns_OkStatusCode()
{
    // Arrange
    var builder = await DistributedApplicationTestingBuilder
        .CreateAsync<Projects.YourAppHost_AppHost>();

    builder.Services.ConfigureHttpClientDefaults(clientBuilder =>
    {
        clientBuilder.AddStandardResilienceHandler();
    });

    await using var app = await builder.BuildAsync();

    await app.StartAsync();

    // Act
    var httpClient = app.CreateHttpClient("api");

    using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(30));
    await app.ResourceNotifications.WaitForResourceHealthyAsync(
        "api",
        cts.Token);

    var response = await httpClient.GetAsync("/");

    // Assert
    Assert.Equal(HttpStatusCode.OK, response.StatusCode);
}

๐Ÿ”‘ Key Concepts

DistributedApplicationTestingBuilder

The DistributedApplicationTestingBuilder creates an isolated instance of your Aspire AppHost for testing:

var builder = await DistributedApplicationTestingBuilder
    .CreateAsync<Projects.YourAppHost_AppHost>();

HTTP Client Configuration

Configure resilience handlers to handle transient failures during testing:

builder.Services.ConfigureHttpClientDefaults(clientBuilder =>
{
    clientBuilder.AddStandardResilienceHandler();
});

Resource Health Checks

Wait for resources to be healthy before testing:

await app.ResourceNotifications.WaitForResourceHealthyAsync(
    "api",
    cts.Token);

๐Ÿ’ก Best Practices

  1. Use timeouts: Always use CancellationTokenSource to prevent tests from hanging
  2. Wait for health: Use WaitForResourceHealthyAsync before making requests
  3. Configure resilience: Add standard resilience handlers for transient failure handling
  4. Dispose properly: Use await using to ensure proper cleanup