akka-net-testing-patterns
Akka.NETアクターのユニットテストと統合テストを、Akka.Hosting.TestKitパターンで記述し、依存性注入、TestProbe、永続化テスト、アクター間の連携検証を網羅的に行い、従来のTestKitの使い分けも支援するSkill。
📜 元の英語説明(参考)
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.
🇯🇵 日本人クリエイター向け解説
Akka.NETアクターのユニットテストと統合テストを、Akka.Hosting.TestKitパターンで記述し、依存性注入、TestProbe、永続化テスト、アクター間の連携検証を網羅的に行い、従来のTestKitの使い分けも支援するSkill。
※ jpskill.com 編集部が日本のビジネス現場向けに補足した解説です。Skill本体の挙動とは独立した参考情報です。
下記のコマンドをコピーしてターミナル(Mac/Linux)または PowerShell(Windows)に貼り付けてください。 ダウンロード → 解凍 → 配置まで全自動。
mkdir -p ~/.claude/skills && cd ~/.claude/skills && curl -L -o akka-net-testing-patterns.zip https://jpskill.com/download/8698.zip && unzip -o akka-net-testing-patterns.zip && rm akka-net-testing-patterns.zip
$d = "$env:USERPROFILE\.claude\skills"; ni -Force -ItemType Directory $d | Out-Null; iwr https://jpskill.com/download/8698.zip -OutFile "$d\akka-net-testing-patterns.zip"; Expand-Archive "$d\akka-net-testing-patterns.zip" -DestinationPath $d -Force; ri "$d\akka-net-testing-patterns.zip"
完了後、Claude Code を再起動 → 普通に「動画プロンプト作って」のように話しかけるだけで自動発動します。
💾 手動でダウンロードしたい(コマンドが難しい人向け)
- 1. 下の青いボタンを押して
akka-net-testing-patterns.zipをダウンロード - 2. ZIPファイルをダブルクリックで解凍 →
akka-net-testing-patternsフォルダができる - 3. そのフォルダを
C:\Users\あなたの名前\.claude\skills\(Win)または~/.claude/skills/(Mac)へ移動 - 4. Claude Code を再起動
⚠️ ダウンロード・利用は自己責任でお願いします。当サイトは内容・動作・安全性について責任を負いません。
🎯 このSkillでできること
下記の説明文を読むと、このSkillがあなたに何をしてくれるかが分かります。Claudeにこの分野の依頼をすると、自動で発動します。
📦 インストール方法 (3ステップ)
- 1. 上の「ダウンロード」ボタンを押して .skill ファイルを取得
- 2. ファイル名の拡張子を .skill から .zip に変えて展開(macは自動展開可)
- 3. 展開してできたフォルダを、ホームフォルダの
.claude/skills/に置く- · macOS / Linux:
~/.claude/skills/ - · Windows:
%USERPROFILE%\.claude\skills\
- · macOS / Linux:
Claude Code を再起動すれば完了。「このSkillを使って…」と話しかけなくても、関連する依頼で自動的に呼び出されます。
詳しい使い方ガイドを見る →- 最終更新
- 2026-05-18
- 取得日時
- 2026-05-18
- 同梱ファイル
- 1
📖 Skill本文(日本語訳)
※ 原文(英語/中国語)を Gemini で日本語化したものです。Claude 自身は原文を読みます。誤訳がある場合は原文をご確認ください。
Akka.NET テストパターン
このスキルを使用するタイミング
このスキルは、以下の場合に使用します。
- Akka.NET アクターのユニットテストを作成する
- イベントソーシングを使用して永続アクターをテストする
- アクターのインタラクションとメッセージフローを検証する
- アクターのスーパービジョンとライフサイクルをテストする
- アクターテストで外部依存関係をモックする
- クラスターシャーディングの動作をローカルでテストする
- アクターの状態復旧と永続化を検証する
参照ファイル
- examples.md: すべてのテストパターン(パターン1〜8とリマインダー)の完全なコードサンプル
- anti-patterns-and-reference.md: アンチパターン、従来の TestKit、CI/CD 統合
テストアプローチの選択
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+) を使用する場合
利点:
- ネイティブな依存性注入のサポート - テストでサービスをフェイクでオーバーライドする
- 本番環境との構成のパリティ (同じ拡張メソッドがテストで動作する)
- アクターロジックとインフラストラクチャの明確な分離
- アクターを取得するためのタイプセーフなアクターレジストリ
従来の Akka.TestKit の使用
タイミング:
- Akka.NET コアライブラリの開発に貢献する場合
Microsoft.Extensionsのない環境 (コンソールアプリ、レガシーシステム) で作業する場合- DI なしで手動で
Propsを作成するレガシーコードベース
従来の TestKit パターンの詳細については、anti-patterns-and-reference.md を参照してください。
コア原則 (Akka.Hosting.TestKit)
Akka.Hosting.TestKit.TestKitから継承する - これはフレームワークの基本クラスであり、ユーザー定義のものではありませんConfigureServices()をオーバーライドする - 実際のサービスをフェイク/モックに置き換えるConfigureAkka()をオーバーライドする - 本番環境と同じ拡張メソッドを使用してアクターを構成するActorRegistryを使用する - アクター参照のタイプセーフな取得- 継承よりもコンポジション - 基本クラスではなく、フィールドとしてフェイクサービスを使用する
- カスタム基本クラスなし - 継承階層ではなく、メソッドのオーバーライドを使用する
- 一度に 1 つのアクターをテストする - 依存関係に TestProbe を使用する
- 本番環境のパターンに一致させる - 同じ拡張メソッド、異なる
AkkaExecutionMode
必要な NuGet パッケージ
<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>
重要: テストプロジェクトのファイルウォッチャーの修正
Akka.Hosting.TestKit は実際の IHost インスタンスを起動しますが、デフォルトでは構成のリロードのためにファイルウォッチャーが有効になっています。 多数のテストを実行すると、Linux でファイル記述子の制限 (inotify watch limit) が使い果たされます。
これをテストプロジェクトに追加してください - すべてのテストが実行される前に実行されます:
// 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");
}
}
これが重要な理由:
[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 を使用して通信する場合
(原文がここで切り詰められています)
📜 原文 SKILL.md(Claudeが読む英語/中国語)を展開
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)
{
}