Community程式設計與開發github.com

Akka.NET 測試模式

使用現代 Akka.Hosting.TestKit 模式為 Akka.NET 參與者撰寫單元測試與整合測試。涵蓋依賴注入、TestProbe、持久化測試及參與者互動驗證。包含何時使用傳統 TestKit 的指引。

Akka.NET 測試模式 是什麼?

此技能專為 Akka.NET 開發者設計,提供一套現代化的測試模式,以 Akka.Hosting.TestKit 為核心。它引導開發者在 95% 的案例中採用基於 Microsoft.Extensions.DependencyInjection 的測試方式,從而實現與生產環境配置一致、支援原生依賴注入 (如 IOptions、DbContext) 的乾淨測試。技能詳細說明了 8 種關鍵測試模式,包括基礎參與者測試、使用 TestProbe 驗證訊息互動、自動回應以避免 Ask 超時、持久化參與者的事件溯源與復原測試,以及本地模擬叢集分片行為。此外,它也強調了關鍵實踐,例如在測試中重複使用生產擴充方法、利用 AwaitAssertAsync 處理非同步操作以避免測試不穩定,並提供了一個必要的 `ModuleInitializer` 來解決 Linux 上因檔案監視器導致的檔案描述符耗盡問題。此技能涵蓋了 xUnit、FluentAssertions 和 Akka.Persistence.Hosting 等套件,並參考了反模式與 CI/CD 整合文件,旨在幫助開發者建立可靠、可維護且與生產環境緊密一致的測試套件。

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

Installed? Explore more 程式設計與開發 skills: steipete/bluebubbles, steipete/eightctl, steipete/blucli · View all 6 →

在你喜歡的 AI 中提問

開啟一個已預先載入此 Agent Skill 的新對話。

說明文件

Akka.NET 測試模式 是做什麼的?

何時使用此技能

在以下情況使用此技能:

  • 為 Akka.NET 參與者撰寫單元測試
  • 測試具有事件溯源功能的持久化參與者
  • 驗證參與者互動與訊息流
  • 測試參與者監督與生命週期
  • 在參與者測試中模擬外部依賴
  • 在本機測試叢集分片行為
  • 驗證參與者狀態復原與持久化

參考文件

選擇你的測試方法

使用 Akka.Hosting.TestKit(建議用於 95% 的案例)

何時使用:

  • 使用 Microsoft.Extensions.DependencyInjection 建置現代 .NET 應用程式
  • 在生產環境中使用 Akka.Hosting 進行參與者設定
  • 需要將服務注入參與者(IOptions、DbContext、ILogger、HTTP 客戶端等)
  • 測試使用 ASP.NET Core、Worker Services 或 .NET Aspire 的應用程式
  • 使用現代 Akka.NET 專案(Akka.NET v1.5+)

優點:

  • 原生依賴注入支援 – 在測試中以偽造物件覆寫服務
  • 與生產環境配置一致(相同的擴充方法在測試中也能運作)
  • 參與者邏輯與基礎設施之間有清晰的關注點分離
  • 型別安全的 ActorRegistry 用於取用參與者

使用傳統 Akka.TestKit

何時使用:

  • 貢獻於 Akka.NET 核心程式庫開發
  • 在沒有 Microsoft.Extensions 的環境中工作(主控台應用程式、舊版系統)
  • 使用手動 Props 建立且不含 DI 的舊版程式碼庫

請參閱 anti-patterns-and-reference.md 了解傳統 TestKit 模式。


核心原則(Akka.Hosting.TestKit)

  1. 繼承自 Akka.Hosting.TestKit.TestKit – 這是一個框架基底類別,不是使用者定義的
  2. 覆寫 ConfigureServices() – 以偽造物件/模擬物件取代真實服務
  3. 覆寫 ConfigureAkka() – 使用與生產環境相同的擴充方法設定參與者
  4. 使用 ActorRegistry – 型別安全地取用參與者參考
  5. 組合優於繼承 – 偽造服務作為欄位,而非基底類別
  6. 不要自訂基底類別 – 使用方法覆寫,而非繼承階層
  7. 一次測試一個參與者 – 對依賴項目使用 TestProbe
  8. 比照生產模式 – 相同的擴充方法,不同的 AkkaExecutionMode

必要的 NuGet 套件

<ItemGroup>
  <!-- 核心測試框架 -->
  <PackageReference Include="Akka.Hosting.TestKit" Version="*" />

  <!-- xUnit(或你偏好的測試框架) -->
  <PackageReference Include="xunit" Version="*" />
  <PackageReference Include="xunit.runner.visualstudio" Version="*" />
  <PackageReference Include="Microsoft.NET.Test.Sdk" Version="*" />

  <!-- 斷言(建議) -->
  <PackageReference Include="FluentAssertions" Version="*" />

  <!-- 記憶體內持久化以用於測試 -->
  <PackageReference Include="Akka.Persistence.Hosting" Version="*" />

  <!-- 如果測試叢集分片 -->
  <PackageReference Include="Akka.Cluster.Hosting" Version="*" />
</ItemGroup>

關鍵:測試專案的檔案監視器修正

Akka.Hosting.TestKit 會啟動真實的 IHost 執行個體,這些執行個體預設會啟用檔案監視器以重新載入設定。執行大量測試時,這會耗盡 Linux 上的檔案描述符限制(inotify 監視限制)。

將以下內容加入你的測試專案 – 它會在測試執行前執行:

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

為什麼這很重要:

  • [ModuleInitializer] 會在任何測試程式碼之前自動執行
  • 為所有 IHost 執行個體全域設定環境變數
  • 防止執行 100 個以上測試時出現難以理解的 inotify 錯誤
  • 也適用於使用 IHost 的 Aspire 整合測試

測試模式概觀

以下是每個模式的簡要說明。請參閱 examples.md 了解完整的程式碼範例。

模式 1:基本參與者測試

基礎模式。覆寫 ConfigureServices() 以注入偽造物件,覆寫 ConfigureAkka() 以使用與生產環境相同的擴充方法註冊參與者。

public class OrderActorTests : TestKit
{
    private readonly FakeOrderRepository _fakeRepository = new();

    protected override void ConfigureServices(HostBuilderContext context, IServiceCollection services)
    {
        services.AddSingleton<IOrderRepository>(_fakeRepository);
    }

    protected override void ConfigureAkka(AkkaConfigurationBuilder builder, IServiceProvider provider)
    {
        builder.WithInMemoryJournal().WithInMemorySnapshotStore();
        builder.WithActors((system, registry, resolver) =>
        {
            registry.Register<OrderActor>(system.ActorOf(resolver.Props<OrderActor>(), "order-actor"));
        });
    }

    [Fact]
    public async Task CreateOrder_Success_SavesToRepository()
    {
        var orderActor = ActorRegistry.Get<OrderActor>();
        var response = await orderActor.Ask<OrderCommandResult>(
            new CreateOrder("ORDER-123", "CUST-456", 99.99m), RemainingOrDefault);
        response.Status.Should().Be(CommandStatus.Success);
        _fakeRepository.SaveCallCount.Should().Be(1);
    }
}

模式 2:用於參與者互動的 TestProbe

在 ActorRegistry 中註冊一個 TestProbe 作為依賴參與者的替代品。使用 ExpectMsgAsync<T>() 驗證訊息是否已發送。

模式 3:自動回應的 TestProbe

當受測參與者使用 Ask 與依賴項目通訊時,建立一個自動回應的參與者,將訊息轉發給探針並同時回覆以避免超時。

模式 4:測試持久化參與者

使用 WithInMemoryJournal() 和 WithInMemorySnapshotStore()。透過發送 PoisonPill 殺死參與者並查詢以強制從日誌中復原,來測試復原。

模式 5:重複使用生產設定

始終在測試中重複使用生產擴充方法,而不是複製 HOCON 設定。這可確保測試使用與生產環境完全相同的設定。

protected override void ConfigureAkka(AkkaConfigurationBuilder builder, IServiceProvider provider)
{
    builder
        .AddDraftSerializer()                                    // 與生產環境相同
        .AddOrderDomainActors(AkkaExecutionMode.LocalTest)      // 相同,但使用本機模式
        .WithInMemoryJournal().WithInMemorySnapshotStore();      // 測試特定的覆寫
}

模式 6:本機叢集分片

使用 AkkaExecutionMode.LocalTest 搭配 GenericChildPerEntityParent,在沒有實際叢集的情況下測試分片行為。相同的擴充方法,不同的模式。

模式 7:用於非同步操作的 AwaitAssertAsync

當參與者執行非同步操作時,使用 AwaitAssertAsync。它會重試斷言直到成功或超時,防止測試不穩定。

await AwaitAssertAsync(() =>
{
    _fakeReadModelService.SyncCallCount.Should().BeGreaterOrEqualTo(1);
}, TimeSpan.FromSeconds(3));

模式 8:基於情境的整合測試

使用多個參與者與狀態轉換,端對端測試完整的商業工作流程。註冊所有領域參與者,在每個步驟驗證狀態。


常見模式摘要

模式使用案例
基本參與者測試單一參與者搭配注入的服務
TestProbe驗證參與者向依賴項目發送訊息
自動回應者測試時避免 Ask 超時
持久化參與者測試事件溯源與復原
叢集分片在本機測試分片行為
AwaitAssertAsync處理參與者內的非同步操作
情境測試端對端商業工作流程

最佳做法

  1. 每個參與者一個測試類別 – 保持測試集中
  2. 覆寫 ConfigureServices/ConfigureAkka – 不要建立基底類別
  3. 使用偽造物件,而非模擬物件 – 更簡單、更易於維護
  4. 一次測試一個參與者 – 對依賴項目使用 TestProbe
  5. 比照生產模式 – 相同的擴充方法,不同的 AkkaExecutionMode
  6. 對非同步使用 AwaitAssertAsync – 防止測試不穩定
  7. 測試復原 – 殺死並重新啟動參與者以驗證持久化
  8. 為工作流程進行情境測試 – 端對端測試完整的商業流程
  9. 保持測試快速 – 使用記憶體中持久化,不要使用真實資料庫
  10. 使用有意義的名稱 – Scenario_FirstTimePurchase_SuccessfulPayment

除錯技巧

  1. 啟用除錯記錄 – 將 LogLevel.Debug 傳遞給 TestKit 建構函式
  2. 使用 ITestOutputHelper – 在測試輸出中查看參與者系統日誌
  3. 檢查 TestProbe – 檢視 probe.Messages 以了解已發送的內容
  4. 查詢參與者狀態 – 為除錯新增狀態查詢訊息
  5. 搭配記錄使用 AwaitAssertAsync – 了解斷言失敗的原因
  6. 檢查 ActorRegistry – 確認參與者已正確註冊
// 含除錯記錄的建構函式
public OrderActorTests(ITestOutputHelper output)
    : base(output: output, logLevel: LogLevel.Debug)
{
}

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.

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

Write integration tests using .NET Aspire

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.

相關技能