Community编程与开发github.com

aspire-integration-testing

使用 .NET Aspire 编写集成测试。

aspire-integration-testing 是什么?

该指南展示了如何使用 .NET Aspire 结合 xUnit 编写针对真实基础设施(如数据库、Redis、消息队列等)的集成测试。它强调了动态端口绑定、通过 IAsyncLifetime 管理测试夹具生命周期以及端点自动发现等核心原则,以避免硬编码 URL。指南提供了基础测试夹具、数据库测试、Playwright UI 测试以及服务间通信的模式,并包含了关键的 Linux 文件描述符修复方案。其文档结构清晰,支持 GitHub Actions CI 集成和 Aspire CLI/MCP 辅助调试,适合在微服务和分布式应用项目中实施可靠、高效的集成测试。

兼容平台~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/Aaronontheweb/dotnet-skills/tree/main/skills/aspire-integration-testing

Installed? Explore more 编程与开发 skills: steipete/bluebubbles, steipete/eightctl, steipete/blucli · View all 6 →

在你喜欢的 AI 中提问

打开一个已预加载此 Agent Skill 的新对话。

文档

使用 .NET Aspire + xUnit 进行集成测试

何时使用此技能

在以下情况下使用此技能:

  • 为 .NET Aspire 应用程序编写集成测试
  • 测试带有真实数据库连接的 ASP.NET Core 应用
  • 验证分布式应用程序中服务到服务的通信
  • 在容器中使用实际基础设施(SQL Server、Redis、消息队列)进行测试
  • 将 Playwright UI 测试与 Aspire 编排的服务相结合
  • 测试具有正确服务发现和网络功能的微服务

参考文件

  • advanced-patterns.md:端点发现、数据库测试、Playwright、条件配置、Respawn、服务通信、消息队列
  • ci-and-tooling.md:CI/CD 集成、自定义资源等待器、Aspire CLI 与 MCP

核心原则

  1. 真实依赖 - 通过 Aspire 使用实际基础设施(数据库、缓存),而非模拟对象
  2. 动态端口绑定 - 让 Aspire 动态分配端口 (127.0.0.1:0) 以避免冲突
  3. 夹具生命周期 - 使用 IAsyncLifetime 实现正确的测试夹具设置和清理
  4. 端点发现 - 绝不要硬编码 URL;在运行时从 Aspire 发现端点
  5. 并行隔离 - 使用 xUnit 集合控制测试并行化
  6. 健康检查 - 始终等待服务健康后再运行测试

高级测试架构

┌─────────────────┐                    ┌──────────────────────┐
│ xUnit 测试文件    │──使用────────────►│  AspireFixture       │
└─────────────────┘                    │  (IAsyncLifetime)    │
                                       └──────────────────────┘
                                               │
                                               │ 启动
                                               ▼
                                    ┌───────────────────────────┐
                                    │  DistributedApplication   │
                                    │  (来自 AppHost)           │
                                    └───────────────────────────┘
                                               │ 暴露
                                               ▼
                                  ┌──────────────────────────────┐
                                  │   动态 HTTP 端点             │
                                  └──────────────────────────────┘
                                               │ 被消费
                                               ▼
                                   ┌─────────────────────────┐
                                   │  HttpClient / Playwright│
                                   └─────────────────────────┘

必需的 NuGet 包

<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>

关键:集成测试的文件监视器修复

当运行大量每个都启动 IHost 的集成测试时,默认的 .NET 宿主构建器会启用文件监视器以重新加载配置。这会耗尽 Linux 上的文件描述符限制。

在测试运行之前,将此代码添加到测试项目中:

// TestEnvironmentInitializer.cs
using System.Runtime.CompilerServices;

namespace YourApp.Tests;

internal static class TestEnvironmentInitializer
{
    [ModuleInitializer]
    internal static void Initialize()
    {
        // 禁用测试宿主中的配置文件监视
        // 防止 Linux 上的文件描述符耗尽(inotify 监视限制)
        Environment.SetEnvironmentVariable("DOTNET_HOSTBUILDER__RELOADCONFIGONCHANGE", "false");
    }
}

模式 1:基础 Aspire 测试夹具(现代 API)

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()
    {
        var builder = await DistributedApplicationTestingBuilder
            .CreateAsync<Projects.YourApp_AppHost>([
                "YourApp:UseVolumes=false",
                "YourApp:Environment=IntegrationTest",
                "YourApp:Replicas=1"
            ]);

        _app = await builder.BuildAsync();

        using var startupCts = new CancellationTokenSource(TimeSpan.FromMinutes(10));
        await _app.StartAsync(startupCts.Token);

        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();
        }
    }
}

模式 2:在测试中使用夹具

[CollectionDefinition("Aspire collection")]
public class AspireCollection : ICollectionFixture<AspireAppFixture> { }

[Collection("Aspire collection")]
public class IntegrationTests
{
    private readonly AspireAppFixture _fixture;

    public IntegrationTests(AspireAppFixture fixture)
    {
        _fixture = fixture;
    }

    [Fact]
    public async Task Application_ShouldStart()
    {
        var httpClient = _fixture.App.CreateHttpClient("yourapp");
        var response = await httpClient.GetAsync("/");
        Assert.Equal(HttpStatusCode.OK, response.StatusCode);
    }
}

请参阅 advanced-patterns.md 了解端点发现、数据库测试、Playwright UI 测试、条件资源配置、Respawn 数据库重置、服务到服务通信以及消息队列测试模式。

常见模式总结

模式用例
基础夹具简单的 HTTP 端点测试
端点发现避免硬编码 URL
数据库测试验证数据访问层
Playwright 集成带真实后端的完整 UI 测试
配置覆盖测试特定的设置
健康检查确保服务已就绪
服务通信测试分布式系统交互
消息队列测试验证异步消息传递

棘手/非显而易见的小贴士

问题解决方案
测试立即超时调用 await _app.StartAsync() 并等待服务健康
测试间的端口冲突使用 xUnit CollectionDefinition 共享夹具
因时序问题导致的测试不稳定实现正确的健康检查轮询,而非 Task.Delay()
无法连接到 SQL Server通过 GetConnectionStringAsync() 动态检索连接字符串
并行测试相互干扰使用 [Collection] 属性使相关测试顺序执行
Aspire 仪表板冲突一次只能运行一个仪表板;测试重用同一实例

最佳实践

  1. 使用 IAsyncLifetime - 确保正确的异步初始化和清理
  2. 通过集合共享夹具 - 通过重用应用实例减少测试执行时间
  3. 动态发现端点 - 绝不要硬编码像 localhost:5000 这样的地址
  4. 等待健康检查 - 不要假设服务立即就绪
  5. 使用真实依赖进行测试 - Aspire 使使用真实的 SQL、Redis 等变得容易
  6. 清理资源 - 始终正确实现 DisposeAsync
  7. 使用有意义的测试数据 - 用真实的测试数据填充数据库
  8. 测试失败场景 - 验证错误处理和弹性
  9. 保持测试隔离 - 每个测试应独立且不依赖顺序
  10. 监控测试执行时间 - 如果测试缓慢,考虑并行化

请参阅 ci-and-tooling.md 了解 GitHub Actions 设置、自定义资源等待器以及 Aspire CLI/MCP 集成。


调试提示

  1. 运行 Aspire 仪表板 - 测试失败时,检查仪表板 http://localhost:15888
  2. 将 Aspire CLI 与 MCP 结合使用 - 让 AI 助手查询真实的应用程序状态
  3. 启用详细日志记录 - 设置 ASPIRE_ALLOW_UNSECURED_TRANSPORT=true 以获取更详细的输出
  4. 检查容器日志 - 使用 docker logs 检查容器输出
  5. 在夹具中设置断点 - 调试夹具初始化以捕获启动问题
  6. 验证资源名称 - 确保 AppHost 中的资源名称与测试中的一致

Individual skills in this repo

This repo contains 20 individual skills — each has its own dedicated page.

akka-hosting-actor-patterns

Patterns for building entity actors with Akka.Hosting - GenericChildPerEntityParent, message extractors, cluster sharding abstraction, akka-reminders, and ITimeProvider. Supports both local testing and clustered production modes.

akka-net-aspire-configuration

Configure Akka.NET with .NET Aspire for local development and production deployments. Covers actor system setup, clustering, persistence, Akka.Management integration, and Aspire orchestration patterns.

akka-net-best-practices

Critical Akka.NET best practices including EventStream vs DistributedPubSub, supervision strategies, error handling, Props vs DependencyResolver, work distribution patterns, and cluster/local mode abstractions for testability.

akka-net-management

Akka.Management for cluster bootstrapping, service discovery (Kubernetes, Azure, Config), health checks, and dynamic cluster formation without static seed nodes.

akka-net-testing-patterns

Write unit and integration tests for Akka.NET actors using modern Akka.Hosting.TestKit patterns. Covers dependency injection, TestProbes, persistence testing, and actor interaction verification. Includes guidance on when to use traditional TestKit.

api-design

Design stable, compatible public APIs using extend-only design principles. Manage API compatibility, wire compatibility, and versioning for NuGet packages and distributed systems.

aspire-configuration

Configure Aspire AppHost to emit explicit app config via environment variables; keep app code free of Aspire clients and service discovery.

aspire-service-defaults

Create a shared ServiceDefaults project for Aspire applications. Centralizes OpenTelemetry, health checks, resilience, and service discovery configuration across all services.

crap-analysis

Analyze code coverage and CRAP (Change Risk Anti-Patterns) scores to identify high-risk code. Use OpenCover format with ReportGenerator for Risk Hotspots showing cyclomatic complexity and untested code paths.

csharp-concurrency-patterns

Choosing the right concurrency abstraction in .NET - from async/await for I/O to Channels for producer/consumer to Akka.NET for stateful entity management. Avoid locks and manual synchronization unless absolutely necessary.

database-performance

Database access patterns for performance. Separate read/write models, avoid N+1 queries, use AsNoTracking, apply row limits, and never do application-side joins. Works with EF Core and Dapper.

dependency-injection-patterns

Organize DI registrations using IServiceCollection extension methods. Group related services into composable Add* methods for clean Program.cs and reusable configuration in tests.

dotnet-devcert-trust

Diagnose and fix .NET HTTPS dev certificate trust issues on Linux. Covers the full certificate lifecycle from generation to system CA bundle inclusion, with distro-specific guidance for Ubuntu, Fedora, Arch, and WSL2.

dotnet-local-tools

Managing local .NET tools with dotnet-tools.json for consistent tooling across development environments and CI/CD pipelines.

dotnet-project-structure

Modern .NET project structure including .slnx solution format, Directory.Build.props, central package management, SourceLink, version management with RELEASE_NOTES.md, and SDK pinning with global.json.

dotnet-slopwatch

Use Slopwatch to detect LLM reward hacking in .NET code changes. Run after every code modification to catch disabled tests, suppressed warnings, empty catch blocks, and other shortcuts that mask real problems.

efcore-patterns

Entity Framework Core best practices including NoTracking by default, query splitting for navigation collections, migration management, dedicated migration services, and common pitfalls to avoid.

ilspy-decompile

Understand implementation details of .NET code by decompiling assemblies. Use when you want to see how a .NET API works internally, inspect NuGet package source, view framework implementation, or understand compiled .NET binaries.

mailpit-integration

Test email sending locally using Mailpit with .NET Aspire. Captures all outgoing emails without sending them. View rendered HTML, inspect headers, and verify delivery in integration tests.

marketplace-publishing

Workflow for publishing skills and agents to the dotnet-skills Claude Code marketplace. Covers adding new content, updating plugin.json, validation, and release tagging.

相关技能