Community编程与开发github.com

akka-net-testing-patterns

使用现代 Akka.Hosting.TestKit 模式为 Akka.NET actors 编写单元测试和集成测试。涵盖依赖注入、TestProbes、持久化测试和 Actor 交互验证,并包含传统 TestKit 的使用指导。

akka-net-testing-patterns 是什么?

该技能为 Akka.NET 开发者提供了一套全面的测试模式指南,专注于使用现代 Akka.Hosting.TestKit 框架编写单元测试和集成测试。它强调了在 95% 的用例中推荐使用 Akka.Hosting.TestKit,因为它原生支持依赖注入(DI)、与生产配置对等、类型安全的 ActorRegistry 以及简洁的代码分离。技能详细介绍了八种核心测试模式,包括基础 Actor 测试、TestProbe 用于交互验证、自动回复 TestProbe 避免超时、持久化 Actor 测试、复用生产配置、本地集群分片测试、异步操作的 AwaitAssertAsync 以及端到端的场景测试。此外,它还提供了关键的最佳实践,如每个 Actor 一个测试类、使用假对象而非模拟对象、匹配生产配置模式,以及一个关键的文件监视器修复方法,用于防止 Linux 上因 inotify 限制导致测试失败。该技能支持 xUnit 测试框架,并推荐使用 FluentAssertions 进行断言。

兼容平台~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 Actor 编写单元测试
  • 测试带有事件溯源的持久化 Actor
  • 验证 Actor 交互和消息流
  • 测试 Actor 监督和生命周期
  • 在 Actor 测试中模拟外部依赖
  • 本地测试集群分片行为
  • 验证 Actor 状态恢复和持久化

参考文件

选择测试方法

使用 Akka.Hosting.TestKit(推荐用于 95% 的用例)

适用场景:

  • 构建使用 Microsoft.Extensions.DependencyInjection 的现代 .NET 应用程序
  • 在生产中使用 Akka.Hosting 进行 Actor 配置
  • 需要将服务注入 Actor(IOptions、DbContext、ILogger、HTTP 客户端等)
  • 测试使用 ASP.NET Core、Worker Services 或 .NET Aspire 的应用程序
  • 使用现代 Akka.NET 项目(Akka.NET v1.5+)

优势:

  • 原生依赖注入支持——在测试中用假对象覆盖服务
  • 与生产配置对等(相同的扩展方法在测试中同样有效)
  • Actor 逻辑与基础设施之间清晰的分离
  • 类型安全的 ActorRegistry,用于检索 Actor

使用传统 Akka.TestKit

适用场景:

  • 为 Akka.NET 核心库开发做贡献
  • 在没有 Microsoft.Extensions 的环境中使用(控制台应用、遗留系统)
  • 手动创建 Props 且无依赖注入的遗留代码库

有关传统 TestKit 模式,请参见 anti-patterns-and-reference.md。


核心原则(Akka.Hosting.TestKit)

  1. 继承 Akka.Hosting.TestKit.TestKit——这是一个框架基类,不是用户定义的类
  2. 重写 ConfigureServices()——用假对象/模拟对象替换真实服务
  3. 重写 ConfigureAkka()——使用与生产相同的扩展方法配置 Actor
  4. 使用 ActorRegistry——类型安全的 Actor 引用检索
  5. 组合优于继承——将假服务作为字段,而不是基类
  6. 不要自定义基类——使用方法重写,而不是继承层次结构
  7. 一次测试一个 Actor——使用 TestProbes 作为依赖
  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:基础 Actor 测试

基础模式。重写 ConfigureServices() 以注入假对象,重写 ConfigureAkka() 以使用与生产相同的扩展方法注册 Actor。

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:用于 Actor 交互的 TestProbe

在 ActorRegistry 中注册一个 TestProbe,作为依赖 Actor 的替身。使用 ExpectMsgAsync<T>() 验证消息是否已发送。

模式 3:自动回复 TestProbe

当被测 Actor 使用 Ask 与依赖项通信时,创建一个自动回复 Actor,该 Actor 将消息转发到探针并回复,以避免超时。

模式 4:测试持久化 Actor

使用 WithInMemoryJournal() 和 WithInMemorySnapshotStore()。通过使用 PoisonPill 杀死 Actor 并查询以强制从日志恢复,来测试恢复。

模式 5:复用生产配置

始终在测试中复用生产扩展方法,而不是重复 HOCON 配置。这确保测试使用与生产完全相同的配置。

protected override void ConfigureAkka(AkkaConfigurationBuilder builder, IServiceProvider provider)
{
    builder
        .AddDraftSerializer()                                    // 与生产相同
        .AddOrderDomainActors(AkkaExecutionMode.LocalTest)      // 相同,但本地模式
        .WithInMemoryJournal().WithInMemorySnapshotStore();      // 测试特定覆盖
}

模式 6:本地集群分片

使用 AkkaExecutionMode.LocalTest 配合 GenericChildPerEntityParent 来测试分片行为,而无需实际集群。相同的扩展方法,不同的模式。

模式 7:用于异步操作的 AwaitAssertAsync

当 Actor 执行异步操作时使用 AwaitAssertAsync。它会重试断言,直到通过或超时,从而防止测试不稳定。

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

模式 8:基于场景的集成测试

使用多个 Actor 和状态转换端到端测试完整业务流程。注册所有领域 Actor,在每个步骤验证状态。


常见模式摘要

模式用例
基础 Actor 测试单个 Actor,带有注入的服务
TestProbe验证 Actor 向依赖项发送消息
自动回复避免测试 Ask 超时
持久化 Actor测试事件溯源和恢复
集群分片本地测试分片行为
AwaitAssertAsync处理 Actor 中的异步操作
场景测试端到端业务流程

最佳实践

  1. 每个 Actor 一个测试类——保持测试集中
  2. 重写 ConfigureServices/ConfigureAkka——不要创建基类
  3. 使用假对象而非模拟对象——更简单、更易维护
  4. 一次测试一个 Actor——使用 TestProbes 作为依赖
  5. 匹配生产模式——相同的扩展方法,不同的 AkkaExecutionMode
  6. 为异步操作使用 AwaitAssertAsync——防止测试不稳定
  7. 测试恢复——杀死并重启 Actor 以验证持久化
  8. 场景测试用于工作流——端到端测试完整业务流程
  9. 保持测试快速——内存持久化,无真实数据库
  10. 使用有意义的名称——Scenario_FirstTimePurchase_SuccessfulPayment

调试技巧

  1. 启用调试日志——将 LogLevel.Debug 传递给 TestKit 构造函数
  2. 使用 ITestOutputHelper——在测试输出中查看 Actor 系统日志
  3. 检查 TestProbe——查看 probe.Messages 以了解发送的内容
  4. 查询 Actor 状态——添加状态查询消息以进行调试
  5. 将 AwaitAssertAsync 与日志结合使用——查看断言失败的原因
  6. 检查 ActorRegistry——验证 Actor 是否正确注册
// 带调试日志的构造函数
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.

相关技能