
Akka.NET Testing Patterns
FreeStreamline testing for Akka.NET actors with modern patterns.
Free · Opens the source repo
What Akka.NET Testing Patterns does
Akka.NET Testing Patterns provides a comprehensive guide for developers looking to implement unit and integration tests for Akka.NET actors. This skill focuses on using the Akka.Hosting.TestKit, which is designed to work seamlessly with modern .NET applications that utilize dependency injection. It covers essential testing scenarios, including verifying actor interactions, testing persistent actors with event sourcing, and mocking external dependencies. The included guidance helps developers choose the right testing approach based on their project needs, ensuring effective testing practices.
The skill features detailed reference files, including examples of various testing patterns and common anti-patterns to avoid. The examples.md file contains complete code samples that illustrate the application of testing patterns, making it easier for developers to grasp the concepts and implement them in their own projects. The anti-patterns-and-reference.md file provides insights into traditional TestKit usage and CI/CD integration, helping developers understand when to use the recommended Akka.Hosting.TestKit versus traditional methods.
This skill is particularly useful for teams working on modern Akka.NET projects (version 1.5 or higher) that require robust testing strategies. By leveraging dependency injection and maintaining configuration parity with production, developers can write cleaner and more maintainable tests. The skill also addresses specific challenges, such as testing cluster sharding behavior and actor state recovery, which are crucial for ensuring the reliability of distributed systems.
Overall, Akka.NET Testing Patterns is an essential resource for developers and testers who want to enhance their testing capabilities for Akka.NET applications, providing them with the tools and knowledge necessary to write effective tests that align with best practices in the field.
When to use it
Use this skill when developing or maintaining Akka.NET applications that require thorough testing of actors, especially in scenarios involving dependency injection and persistent actors.
When not to use it
This skill is not suitable for legacy Akka.NET projects that do not utilize dependency injection or for environments that do not support Akka.Hosting.
What you can build with it
Testing Actor Interactions
Use the skill to verify message flows and interactions between actors, ensuring they communicate as expected.
Validating Persistent Actors
Implement tests for actors that utilize event sourcing, confirming that state recovery and persistence work correctly.
Mocking Dependencies in Tests
Leverage dependency injection to create fakes for external services in your tests, improving isolation and reliability.
How to install Akka.NET Testing Patterns
View source1. Install with the skills CLI
npx skills add aaronontheweb/dotnet-skills/akka-testing-patterns --agent claude-code2. Or install it manually
Download the skill folder and drop it into ~/.claude/skills/ for all projects, or .claude/skills/ to scope it to one repo. Restart Claude Code so it picks up the new skill.
Anthropic's agentic coding CLI, and the reference implementation of Agent Skills. Drop a skill folder into ~/.claude/skills and Claude Code loads it automatically whenever a task matches the skill's description. Claude Code docs
Inside SKILL.md
Written by aarononthewebAkka.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)
{
}
Frequently asked questions about Akka.NET Testing Patterns
Similar skills
Spring Boot Testing
Master testing techniques for Spring Boot 4 applications.
GitHub Issues
Manage GitHub issues efficiently with MCP tools.
Geofeed Tuner
Optimize your IP geolocation feeds in CSV format.
Batch Files
Master Windows batch scripting for automation and task management.
Adobe Illustrator Scripting
Automate your Illustrator workflows with ExtendScript.
Plugin Structure
Create and organize Claude Code plugins effectively.
