seiggy/lucia-dotnet/aspire-integration-testing

Claude Code and agent skill by seiggy/lucia-dotnet

Trust tier 3
  • community
  • ext:[{"type":"config","description":"Configuration overrides"}]
Source check pending

Checking that the SKILL.md file is still in the repository.

Write integration tests using .NET Aspire's testing facilities with xUnit. Covers test fixtures, distributed application setup, endpoint discovery, and patterns for testing ASP.NET Core apps with real dependencies.

Install

npx vskill@latest install seiggy/lucia-dotnet/aspire-integration-testing

Semi-extensibleMentions customization, but needs skill-specific knowledge. Read the extensible skills standard

SKILL.md

The same SKILL.md was published earlier as seiggy/lucia-dotnet/aspire-integration-testing.

Integration Testing with .NET Aspire + xUnit

When to Use This Skill

Use this skill when:

  • Writing integration tests for .NET Aspire applications
  • Testing ASP.NET Core apps with real database connections
  • Verifying service-to-service communication in distributed applications
  • Testing with actual infrastructure (SQL Server, Redis, message queues) in containers
  • Combining Playwright UI tests with Aspire-orchestrated services
  • Testing microservices with proper service discovery and networking

Core Principles

  1. Real Dependencies - Use actual infrastructure (databases, caches) via Aspire, not mocks
  2. Dynamic Port Binding - Let Aspire assign ports dynamically (127.0.0.1:0) to avoid conflicts
  3. Fixture Lifecycle - Use IAsyncLifetime for proper test fixture setup and teardown
  4. Endpoint Discovery - Never hard-code URLs; discover endpoints from Aspire at runtime
  5. Parallel Isolation - Use xUnit collections to control test parallelization
  6. Health Checks - Always wait for services to be healthy before running tests

High-Level Testing Architecture

┌─────────────────┐ ┌──────────────────────┐
│ xUnit test file │──uses────────────►│ AspireFixture │
└─────────────────┘ │ (IAsyncLifetime) │
└──────────────────────┘
│
│ starts
▼
┌───────────────────────────┐
│ DistributedApplication │
│ (from AppHost) │
└───────────────────────────┘
│ exposes
▼
┌──────────────────────────────┐
│ Dynamic HTTP Endpoints │
└──────────────────────────────┘
│ consumed by
▼
┌─────────────────────────┐
│ HttpClient / Playwright│
└─────────────────────────┘

Required NuGet Packages

xml
<ItemGroup>
<PackageReference Include="Aspire.Hosting.Testing" Version="$(AspireVersion)" />
<PackageReference Include="xunit" Version="*" />
<PackageReference Include="xunit.runner.visualstudio" Version="*" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="*" />
</ItemGroup>

CRITICAL: File Watcher Fix for Integration Tests

When running many integration tests that each start an IHost, the default .NET host builder enables file watchers for configuration reload. This exhausts file descriptor limits on Linux.

Add this to your test project before any tests run:

csharp
// TestEnvironmentInitializer.cs
using System.Runtime.CompilerServices;
namespace YourApp.Tests;
internal static class TestEnvironmentInitializer
{
[ModuleInitializer]
internal static void Initialize()
{
// Disable config file watching in test hosts
// Prevents file descriptor exhaustion (inotify watch limit) on Linux
Environment.SetEnvironmentVariable("DOTNET_HOSTBUILDER__RELOADCONFIGONCHANGE", "false");
}
}

Why this matters: [ModuleInitializer] runs before any test code executes, setting the environment variable globally for all IHost instances created during tests.

Pattern 1: Basic Aspire Test Fixture (Modern API)

csharp
using Aspire.Hosting;
using Aspire.Hosting.Testing;
public sealed class AspireAppFixture : IAsyncLifetime
{
private DistributedApplication? _app;
public DistributedApplication App => _app
?? throw new InvalidOperationException("App not initialized");
public async Task InitializeAsync()
{
// Pass configuration overrides as command-line args (cleaner than Configuration dictionary)
var builder = await DistributedApplicationTestingBuilder
.CreateAsync<Projects.YourApp_AppHost>([
"YourApp:UseVolumes=false", // No persistence - clean slate each test
"YourApp:Environment=IntegrationTest",
"YourApp:Replicas=1" // Single instance for tests
]);
_app = await builder.BuildAsync();
// Phase 1: Start the application (container startup)
using var startupCts = new CancellationTokenSource(TimeSpan.FromMinutes(10));
await _app.StartAsync(startupCts.Token);
// Phase 2: Wait for services to become healthy (use built-in API)
using var healthCts = new CancellationTokenSource(TimeSpan.FromMinutes(5));
await _app.ResourceNotifications.WaitForResourceHealthyAsync("api", healthCts.Token);
}
public Uri GetEndpoint(string resourceName, string scheme = "https")
{
return _app?.GetEndpoint(resourceName, scheme)
?? throw new InvalidOperationException($"Endpoint for '{resourceName}' not found");
}
public async Task DisposeAsync()
{
if (_app is not null)
{
await _app.DisposeAsync();
}
}
}

Pattern 2: Using the Fixture in Tests

csharp
// Define a collection to share the fixture across multiple test classes
[CollectionDefinition("Aspire collection")]
public class AspireCollection : ICollectionFixture<AspireAppFixture> { }
// Use the fixture in your test class
[Collection("Aspire collection")]
public class IntegrationTests
{
private readonly AspireAppFixture _fixture;
public IntegrationTests(AspireAppFixture fixture)
{
_fixture = fixture;
}
[Fact]
public async Task Application_ShouldStart()
{
// Get the web application resource
var webApp = _fixture.App.GetResource("yourapp");
// Get the HTTP endpoint
var httpClient = _fixture.App.CreateHttpClient("yourapp");
// Make a request
var response = await httpClient.GetAsync("/");
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
}
}

Pattern 3: Endpoint Discovery

csharp
public static class DistributedApplicationExtensions
{
public static ResourceEndpoint GetEndpoint(
this DistributedApplication app,
string resourceName,
string? endpointName = null)
{
var resource = app.GetResource(resourceName);
if (resource is null)
throw new InvalidOperationException(
$"Resource '{resourceName}' not found");
var endpoint = endpointName is null
? resource.GetEndpoints().FirstOrDefault()
: resource.GetEndpoint(endpointName);
if (endpoint is null)
throw new InvalidOperationException(
$"Endpoint '{endpointName}' not found on resource '{resourceName}'");
return endpoint;
}
public static string GetEndpointUrl(
this DistributedApplication app,
string resourceName,
string? endpointName = null)
{
var endpoint = app.GetEndpoint(resourceName, endpointName);
return endpoint.Url;
}
}
// Usage in tests
[Fact]
public async Task CanAccessWebApplication()
{
var url = _fixture.App.GetEndpointUrl("yourapp");
var client = new HttpClient { BaseAddress = new Uri(url) };
var response = await client.GetAsync("/health");
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
}

Pattern 4: Testing with Database Dependencies

csharp
public class DatabaseIntegrationTests
{
private readonly AspireAppFixture _fixture;
public DatabaseIntegrationTests(AspireAppFixture fixture)
{
_fixture = fixture;
}
[Fact]
public async Task Database_ShouldBeInitialized()
{
// Get connection string from Aspire
var dbResource = _fixture.App.GetResource("yourdb");
var connectionString = await dbResource
.GetConnectionStringAsync();
// Test database access
await using var connection = new SqlConnection(connectionString);
await connection.OpenAsync();
var result = await connection.QuerySingleAsync<int>(
"SELECT COUNT(*) FROM INFORMATION_SCHEMA.TABLES");
Assert.True(result > 0, "Database should have tables");
}
}

Pattern 5: Combining with Playwright for UI Tests

csharp
using Microsoft.Playwright;
public sealed class AspirePlaywrightFixture : IAsyncLifetime
{
private DistributedApplication? _app;
private IPlaywright? _playwright;
private IBrowser? _browser;
public DistributedApplication App => _app!;
public IBrowser Browser => _browser!;
public async Task InitializeAsync()
{
// Start Aspire application
var appHost = await DistributedApplicationTestingBuilder
.CreateAsync<Projects.YourApp_AppHost>();
_app = await appHost.BuildAsync();
await _app.StartAsync();
// Wait for app to be fully ready
await Task.Delay(2000); // Or use proper health check polling
// Start Playwright
_playwright = await Playwright.CreateAsync();
_browser = await _playwright.Chromium.LaunchAsync(new()
{
Headless = true
});
}
public async Task DisposeAsync()
{
if (_browser is not null)
await _browser.DisposeAsync();
_playwright?.Dispose();
if (_app is not null)
await _app.DisposeAsync();
}
}
[Collection("Aspire Playwright collection")]
public class UIIntegrationTests
{
private readonly AspirePlaywrightFixture _fixture;
public UIIntegrationTests(AspirePlaywrightFixture fixture)
{
_fixture = fixture;
}
[Fact]
public async Task HomePage_ShouldLoad()
{
var url = _fixture.App.GetEndpointUrl("yourapp");
var page = await _fixture.Browser.NewPageAsync();
await page.GotoAsync(url);
var title = await page.TitleAsync();
Assert.NotEmpty(title);
}
}

Pattern 6: Conditional Resource Configuration for Tests

Design your AppHost to support different configurations for interactive development (F5/CLI) vs automated test fixtures. The pattern goes beyond just volumes - it covers execution modes, authentication, external services, and more.

Core Principle
Default to production-like behavior in AppHost. Tests explicitly override what they need to be different. This catches configuration gaps early (e.g., missing DI registrations that only surface in clustered mode).
Configuration Class in AppHost
csharp
// In your AppHost project
public class AppHostConfiguration
{
// Infrastructure settings
public bool UseVolumes { get; set; } = true; // Persist data in dev, clean slate in tests
// Execution mode settings (for Akka.NET or similar)
public string ExecutionMode { get; set; } = "Clustered"; // Full cluster in dev, LocalTest optional
// Feature toggles
public bool EnableTestAuth { get; set; } = false; // /dev-login endpoint for tests
public bool UseFakeExternalServices { get; set; } = false; // Fake Gmail, Stripe, etc.
// Scale settings
public int Replicas { get; set; } = 1;
}
AppHost Conditional Logic
csharp
var builder = DistributedApplication.CreateBuilder(args);
// Bind configuration from command-line args or appsettings
var config = builder.Configuration.GetSection("App")
.Get<AppHostConfiguration>() ?? new AppHostConfiguration();
// Database with conditional volume
var postgres = builder.AddPostgres("postgres").WithPgAdmin();
if (config.UseVolumes)
{
postgres.WithDataVolume();
}
var db = postgres.AddDatabase("appdb");

This is the start of the file. Read the full SKILL.md on GitHub.

Security

  • Security scanPassed, 95 of 100Pattern checks on the skill's files.
  • Model reviewPassed

Quality evaluation

  • Task evaluationNot runNo evaluation yet. Run one in Skill Studio.

Source

Popularity

Repository stars
56
Repository forks
7
7-day trend score
20

Stars and forks are for the whole GitHub repository, not this skill alone. Not refreshed yet.

Extension points

  • configConfiguration overrides

Works with

Any agent vskill installs to: 56 targets in all. These 39 have a page on this site.

  • Claude Code
  • Cursor
  • GitHub Copilot
  • Windsurf
  • Codex
  • Gemini CLI
  • Cline
  • Amp
  • Roo Code
  • Goose
  • Continue
  • Kilo Code
  • Junie
  • Trae
  • OpenHands
  • Qwen Code
  • AI Agent
  • Tabnine Chat
  • Sourcegraph Cody
  • Amazon Q
  • Firebase Genkit
  • Sweep
  • Devin
  • Phind
  • Mentat
  • Claude Desktop
  • Aider
  • GPT Pilot
  • Plandex
  • bolt.new
  • v0
  • Replit Agent
  • Anse
  • TypingMind
  • BetterChatGPT
  • LibreChat
  • Warp AI
  • Pieces
  • Fig AI
Embed badge
vskill VERIFIED badge
[![vskill VERIFIED](https://verified-skill.com/api/v1/skills/seiggy/lucia-dotnet/aspire-integration-testing/badge)](https://verified-skill.com/skills/seiggy/lucia-dotnet/aspire-integration-testing)

Something wrong with this skill or its page? Tell us.