Community程式設計與開發github.com

Aspire 整合測試

使用 .NET Aspire 撰寫整合測試,涵蓋真實數據庫、服務間通訊以及容器化基礎設施。

Aspire 整合測試 是什麼?

此技能提供了一套完整的指導方針與程式碼範例,幫助開發者使用 .NET Aspire 與 xUnit 撰寫高品質的整合測試。核心概念包含使用 Aspire 啟動真實的基礎設施(如 SQL Server、Redis)而非模擬物件,並透過動態埠繫結與端點發現(Endpoint Discovery)避免硬編碼位址。技能詳細說明了如何建立基本的 Aspire 測試夾具(Fixture)、透過 xUnit 集合(Collection)共享測試實例以提升執行效率,以及如何處理檔案監視器在 Linux 上的檔案描述子耗盡問題。此外,更進階的「advanced-patterns.md」涵蓋資料庫測試、Playwright UI 測試、服務間通訊與訊息佇列測試;「ci-and-tooling.md」則說明了 CI/CD 整合與 Aspire CLI / MCP 的使用方式。此技能支援 .NET Aspire 生態系中的所有主要測試平台,並提供健康檢查、並行隔離與錯誤診斷等最佳實踐。

相容平台~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 協調的服務結合
  • 測試具備服務探索(Service Discovery)與網路功能的微服務

參考檔案

  • advanced-patterns.md:端點探索、資料庫測試、Playwright、條件式設定、Respawn 重設、服務通訊、訊息佇列
  • ci-and-tooling.md:CI/CD 整合、自訂資源等待器、Aspire CLI 搭配 MCP

核心原則

  1. 真實相依性 - 使用 Aspire 提供的實際基礎設施(資料庫、快取),而非模擬物件
  2. 動態埠繫結 - 讓 Aspire 動態分配埠(127.0.0.1:0)以避免衝突
  3. Fixture 生命週期 - 使用 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("應用程式尚未初始化");

    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($"找不到資源 '{resourceName}' 的端點");
    }

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

如需端點探索、資料庫測試、Playwright UI 測試、條件式資源設定、Respawn 資料庫重設、服務對服務通訊及訊息佇列測試模式,請參閱 advanced-patterns.md。

常見模式摘要

模式使用案例
基本夾具簡單 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. 監控測試執行時間 - 若測試過慢,考慮平行化

如需 GitHub Actions 設定、自訂資源等待器以及 Aspire CLI / MCP 整合,請參閱 ci-and-tooling.md。


除錯技巧

  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.

相關技能