测试助手
- 作者仓库星标 1,012
- 叉子 98
- 作者更新于 2026年4月16日 02:05
- 作者仓库 dotnet-skills
- 领域
- 安全
- 兼容 Agent
-
- Claude Code
- Cursor
- Cline
- Codex
- Windsurf
- Gemini CLI
- +20
- 信任分
- 88 / 100 · 社区维护
- 作者 / 版本 / 许可
- @Aaronontheweb · 未声明 license
- Token 消耗评级
- 低消耗
- 接入复杂程度
- 需简单配置
- 是否需要外部 API Key
- 不需要
- 兼容的系统
- Linux
- 底层运行要求
- 无特殊要求
- 文件与系统权限
-
- 只读
- 允许写入 / 修改
- Shell 执行
- 读取环境变量
- 网络行为
- 仅限本地
- 安装命令数
- 26 条
档案由构建时根据 SKILL.md 与安装命令自动衍生,可能与作者实际意图存在差异。
需要注意: 未限定 allowed-tools,默认拥有全部工具权限。
---
name: akka-net-testing-patterns
description: Write unit and integration tests for Akka.NET actors using modern Akka.Hosting.TestKit patterns.…
category: 安全
runtime: 无特殊运行时
---
# akka-net-testing-patterns 输出预览
## PART A: 任务判断
- 适用问题:安全审计、密钥扫描、权限检查或风险分析。
- 输入要求:目标材料、限制条件、期望输出和验收方式。
- 证据边界:围绕“When to Use This Skill / Reference Files / Choosing Your Testing Approach”读取原文规则,不把推断写成作者承诺。
## PART B: 执行结果
- **01** 任务判断:确认你的需求是否属于安全审计、密钥扫描、权限检查或风险分析,并标出输入、限制和预期结果。
- **02** 执行计划:优先按“When to Use This Skill / Reference Files / Choosing Your Testing Approach”拆成步骤,说明每一步会读取什么、修改什么、产出什么。
- **03** 交付结果:给出可复制的命令、文件改动、检查清单或内容草稿,并说明如何继续迭代。
- **04** 风险边界:结合 读取文件、写入/修改文件、执行终端命令、读取环境变量、主要在本地完成、通常不需要额外 API Key 给出执行前确认项。
## Running Rules
- 读取文件、写入/修改文件、执行终端命令、读取环境变量;主要在本地完成;通常不需要额外 API Key。
- 先小样例验证,再放大到真实任务。
- 交付时同时给结果、检查口径和下一步迭代建议。 原文没有稳定的斜杠命令要求。安装验证后通常全局生效,直接在对话里点名这个 Skill 并描述任务即可。
告诉 Agent 目标文件或材料、期望结果、不可改范围、是否允许联网或执行命令。本 Skill 的权限画像是:读取文件、写入/修改文件、执行终端命令、读取环境变量。
先用一个小任务确认它会围绕“When to Use This Skill / Reference Files / Choosing Your Testing Approach”工作;涉及文件或命令时,先看 diff、日志、预览或测试结果。
检查最终产物是否包含明确结果、必要证据和下一步动作;如果输出泛泛而谈,就补充输入、边界和验收标准后重跑。
---
name: akka-net-testing-patterns
description: Write unit and integration tests for Akka.NET actors using modern Akka.Hosting.TestKit patterns.…
category: 安全
source: Aaronontheweb/dotnet-skills
---
# akka-net-testing-patterns
## 什么时候使用
- 解决 Akka.NET Actor 单元与集成测试难题 适合验证消息流、监督生命周期、持久化恢复和本地集群分片 适合处理安全审计、密钥扫描、权限检查和风险分析,核心价值是把输入、判断、执行、验证和交付边界固定下来,避免 Agent 泛泛…
- 面向安全审计、密钥扫描、权限检查或风险分析,优先处理能明确输入、步骤和验收标准的工作。
## 需要提供什么
- 目标材料、目录范围、期望结果和不可改动内容。
- 是否允许联网、执行命令、读写文件或调用外部服务。
## 执行规则
- 围绕「When to Use This Skill / Reference Files / Choosing Your Testing Approach」组织步骤,不把推断写成作者事实。
- 读取文件、写入/修改文件、执行终端命令、读取环境变量;主要在本地完成;通常不需要额外 API Key。
- 先跑小样例,确认结果可检查后再扩大任务范围。
## 输出要求
- 给出最终产物、关键证据、验证方式和下一步动作。
- 信息不足时标记 unknown,不编造命令、平台或依赖。 作者原文负责流程事实;仓库文件负责来源和命令;流狐只补充适用场景、限制和质量判断。
skill "akka-net-testing-patterns" {
输入层 -> 用户目标 + 目标文件 + 禁止范围 + 验收标准
上下文层 -> When to Use This Skill / Reference Files / Choosing Your Testing Approach
规则层 -> SKILL.md 触发条件 / 执行顺序 / 输出格式
运行层 -> 无特殊运行时 | 读取文件、写入/修改文件、执行终端命令、读取环境变量 | 主要在本地完成
安全层 -> 通常不需要额外 API Key + 小任务验证 + diff / 日志复核
输出层 -> 可复制结果 + 检查清单 + 下一步迭代
} Akka.NET Testing Patterns
When to Use This Skill
Use this skill when:
- Writing unit tests for Akka.NET actors
- Testing persistent actors with event sourcing
- Verifying actor interactions and message flows
- Testing actor supervision and lifecycle
- Mocking external dependencies in actor tests
- Testing cluster sharding behavior locally
- Verifying actor state recovery and persistence
Reference Files
- examples.md: Complete code samples for all testing patterns (Patterns 1-8 plus Reminders)
- anti-patterns-and-reference.md: Anti-patterns, traditional TestKit, CI/CD integration
Choosing Your Testing Approach
Use Akka.Hosting.TestKit (Recommended for 95% of Use Cases)
When:
- Building modern .NET applications with
Microsoft.Extensions.DependencyInjection - Using Akka.Hosting for actor configuration in production
- Need to inject services into actors (
IOptions,DbContext,ILogger, HTTP clients, etc.) - Testing applications that use ASP.NET Core, Worker Services, or .NET Aspire
- Working with modern Akka.NET projects (Akka.NET v1.5+)
Advantages:
- Native dependency injection support - override services with fakes in tests
- Configuration parity with production (same extension methods work in tests)
- Clean separation between actor logic and infrastructure
- Type-safe actor registry for retrieving actors
Use Traditional Akka.TestKit
When:
- Contributing to Akka.NET core library development
- Working in environments without
Microsoft.Extensions(console apps, legacy systems) - Legacy codebases using manual
Propscreation without DI
See anti-patterns-and-reference.md for traditional TestKit patterns.
Core Principles (Akka.Hosting.TestKit)
- Inherit from
Akka.Hosting.TestKit.TestKit- This is a framework base class, not a user-defined one - Override
ConfigureServices()- Replace real services with fakes/mocks - Override
ConfigureAkka()- Configure actors using the same extension methods as production - Use
ActorRegistry- Type-safe retrieval of actor references - Composition over Inheritance - Fake services as fields, not base classes
- No Custom Base Classes - Use method overrides, not inheritance hierarchies
- Test One Actor at a Time - Use TestProbes for dependencies
- Match Production Patterns - Same extension methods, different
AkkaExecutionMode
Required NuGet Packages
<ItemGroup>
<!-- Core testing framework -->
<PackageReference Include="Akka.Hosting.TestKit" Version="*" />
<!-- xUnit (or your preferred test framework) -->
<PackageReference Include="xunit" Version="*" />
<PackageReference Include="xunit.runner.visualstudio" Version="*" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="*" />
<!-- Assertions (recommended) -->
<PackageReference Include="FluentAssertions" Version="*" />
<!-- In-memory persistence for testing -->
<PackageReference Include="Akka.Persistence.Hosting" Version="*" />
<!-- If testing cluster sharding -->
<PackageReference Include="Akka.Cluster.Hosting" Version="*" />
</ItemGroup>
CRITICAL: File Watcher Fix for Test Projects
Akka.Hosting.TestKit spins up real IHost instances, which by default enable file watchers for configuration reload. When running many tests, this exhausts file descriptor limits on Linux (inotify watch limit).
Add this to your test project - it runs before any tests execute:
// 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 automatically before any test code- Sets the environment variable globally for all
IHostinstances - Prevents cryptic
inotifyerrors when running 100+ tests - Also applies to Aspire integration tests that use
IHost
Testing Patterns Overview
Each pattern below has a condensed description. See examples.md for complete code samples.
Pattern 1: Basic Actor Test
The foundation pattern. Override ConfigureServices() to inject fakes, override ConfigureAkka() to register actors with the same extension methods as production.
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);
}
}
Pattern 2: TestProbe for Actor Interactions
Register a TestProbe in the ActorRegistry as a stand-in for a dependency actor. Use ExpectMsgAsync<T>() to verify messages were sent.
Pattern 3: Auto-Responding TestProbe
When the actor under test uses Ask to communicate with dependencies, create an auto-responder actor that forwards messages to a probe AND replies to avoid timeouts.
Pattern 4: Testing Persistent Actors
Use WithInMemoryJournal() and WithInMemorySnapshotStore(). Test recovery by killing the actor with PoisonPill and querying to force recovery from journal.
Pattern 5: Reuse Production Configuration
Always reuse production extension methods in tests instead of duplicating HOCON config. This ensures tests use the exact same configuration as production.
protected override void ConfigureAkka(AkkaConfigurationBuilder builder, IServiceProvider provider)
{
builder
.AddDraftSerializer() // Same as production
.AddOrderDomainActors(AkkaExecutionMode.LocalTest) // Same, but local mode
.WithInMemoryJournal().WithInMemorySnapshotStore(); // Test-specific overrides
}
Pattern 6: Cluster Sharding Locally
Use AkkaExecutionMode.LocalTest with GenericChildPerEntityParent to test sharding behavior without an actual cluster. Same extension methods, different mode.
Pattern 7: AwaitAssertAsync for Async Operations
Use AwaitAssertAsync when actors perform async operations. It retries assertions until they pass or timeout, preventing flaky tests.
await AwaitAssertAsync(() =>
{
_fakeReadModelService.SyncCallCount.Should().BeGreaterOrEqualTo(1);
}, TimeSpan.FromSeconds(3));
Pattern 8: Scenario-Based Integration Tests
Test complete business workflows end-to-end with multiple actors and state transitions. Register all domain actors, verify state at each step.
Common Patterns Summary
| Pattern | Use Case |
|---|---|
| Basic Actor Test | Single actor with injected services |
| TestProbe | Verify actor sends messages to dependencies |
| Auto-Responder | Avoid Ask timeouts when testing |
| Persistent Actor | Test event sourcing and recovery |
| Cluster Sharding | Test sharding behavior locally |
| AwaitAssertAsync | Handle async operations in actors |
| Scenario Tests | End-to-end business workflows |
Best Practices
- One test class per actor - Keep tests focused
- Override ConfigureServices/ConfigureAkka - Don't create base classes
- Use fakes, not mocks - Simpler, more maintainable
- Test one actor at a time - Use TestProbes for dependencies
- Match production patterns - Same extension methods, different
AkkaExecutionMode - Use AwaitAssertAsync for async - Prevents flaky tests
- Test recovery - Kill and restart actors to verify persistence
- Scenario tests for workflows - Test complete business flows end-to-end
- Keep tests fast - In-memory persistence, no real databases
- Use meaningful names -
Scenario_FirstTimePurchase_SuccessfulPayment
Debugging Tips
- Enable debug logging - Pass
LogLevel.Debugto TestKit constructor - Use ITestOutputHelper - See actor system logs in test output
- Inspect TestProbe - Check
probe.Messagesto see what was sent - Query actor state - Add state query messages for debugging
- Use AwaitAssertAsync with logging - See why assertions fail
- Check ActorRegistry - Verify actors are registered correctly
// Constructor with debug logging
public OrderActorTests(ITestOutputHelper output)
: base(output: output, logLevel: LogLevel.Debug)
{
}
先判断是否适合
作者设计意图
作者的方法与取舍
边界和复核