Skip to content
Development
Skill

/akka-testing-patterns

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.

From plugin
dotnet-skills
1.2k39 skills6 agents

Claude Code

$ npx -y skills add aaronontheweb/dotnet-skills --skill akka-testing-patterns --agent claude-code

SKILL.md

akka-testing-patterns.SKILL.md
name: akka-net-testing-patterns
description: 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.
user-invocable: false

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](examples.md): Complete code samples for all testing patterns (Patterns 1-8 plus Reminders)
  • [anti-patterns-and-reference.md](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 `Props` creation without DI

See [anti-patterns-and-reference.md](anti-patterns-and-reference.md) for traditional TestKit patterns.

---

Core Principles (Akka.Hosting.TestKit)

1. **Inherit from `Akka.Hosting.TestKit.TestKit`** - This is a framework base class, not a user-defined one 2. **Override `ConfigureServices()`** - Replace real services with fakes/mocks 3. **Override `ConfigureAkka()`** - Configure actors using the same extension methods as production 4. **Use `ActorRegistry`** - Type-safe retrieval of actor references 5. **Composition over Inheritance** - Fake services as fields, not base classes 6. **No Custom Base Classes** - Use method overrides, not inheritance hierarchies 7. **Test One Actor at a Time** - Use TestProbes for dependencies 8. **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 `IHost` instances
  • Prevents cryptic `inotify` errors 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](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);
        _fakeRepositor
Read more
@aaronontheweb
Ships withdotnet-skills

A comprehensive AI coding plugin with 30 skills and 5 specialized agents for professional .NET development. Battle-tested patterns from production systems covering C#, Akka.NET, Aspire, EF Core, testing, and performance optimization.

1.2k39 skills6 agents
Get the whole plugin

Stars on GitHub

Momentum

stars in total
1.2k
Star history of aaronontheweb/dotnet-skills on GitHub, a chart by star-history.com

Other skills on dotnet-skills.

aot-trimming

aot-trimming

Guidelines for making .NET libraries and applications trimming-safe and Native AOT compatible. Covers the trimming/AOT model, the…

More skills from other plugins.

brainstorming
Auto-invoked

brainstorming

You MUST use this before any creative work - creating features, building components, adding functionality, modifying behavior, or…

@obra@obraInstall Skill
ask-matt

ask-matt

Ask which skill or flow fits your situation. A router over the skills in this repo.

skills11d309k
@mattpocock@mattpocockInstall Skill
accessibility
Auto-invoked

accessibility

Design, implement, and audit accessible UI to WCAG 2.2 Level AA across Web, iOS, and Android — semantic ARIA roles and labels,…

ecc12d293k
@affaan-m@affaan-mInstall Skill
compiler-commit

compiler-commit

Use when you want to verify compiler changes and commit with the correct convention. Runs tests, lint, and format, then commits…

react1d252k
@facebook@facebookInstall Skill

Questions about akka-testing-patterns.

Which coding agents can use akka-testing-patterns?
akka-testing-patterns installs in Claude Code, Codex, Cursor, Gemini CLI, GitHub Copilot, OpenCode and Windsurf with the skills CLI, using each agent's flag shown on this page. Flowy's auto-invocation, which fires a skill when your prompt matches, runs in Claude Code only.