API Testing with Aspire¶
Learn how to write API integration tests using Aspire's DistributedApplicationTestingBuilder.
On this page
๐ 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.
๐ Related Resources¶
๐ฆ Required Packages¶
Add the shared Aspire integration test packages and follow native MTP setup for the runner configuration, central package pins, and test command. API tests also need:
๐งช Test Structure¶
Namespaces¶
Test Class¶
๐ Example: Testing API Root Endpoint¶
This test verifies that the root endpoint (/) returns an HTTP 200 OK status code.
Steps¶
- Arrange: Create and configure the distributed application
- Act: Send HTTP request to the API
- 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:
๐ก Best Practices¶
- Use timeouts: Always use
CancellationTokenSourceto prevent tests from hanging - Wait for health: Use
WaitForResourceHealthyAsyncbefore making requests - Configure resilience: Add standard resilience handlers for transient failure handling
- Dispose properly: Use
await usingto ensure proper cleanup