Skip to content

Commit df2e35d

Browse files
Add Akka.Hosting.TestKit coverage to three more sample projects (#593)
Extends the Akka.Hosting.TestKit pattern (established in the cluster-client PoC) to the Autofac, SqlSharding, and ReliableRabbitMQ samples. Each new test project uses the same setup: net10.0 exe, xunit v3 via the Microsoft.Testing.Platform runner, a DOTNET_HOSTBUILDER__RELOADCONFIGONCHANGE module initializer, TestProbes created inside ConfigureAkka (not the constructor), and versionless centrally-managed packages. - AutofacIntegration.Tests: EchoActorTests overrides ConfigureServices and wires the Autofac scope so EchoActor resolves its injected service; asserts echo replies via a TestProbe sender and ActorRegistry. - SqlSharding.Tests: ProductTotalsActorTests drive the persistent actor with in-memory journal/snapshot stores, asserting CommandResponse and verifying restart -> event replay -> state recovery. - ReliableRabbitMQ.Tests: ProductActorTests exercise the deterministic success path (retrying until an OrderCommandAck is observed), sidestepping the actor's random SimulateNetworkFailure. AMQP stream actors are intentionally not tested. - Adds Akka.Persistence.Hosting and wires each test project into its solution. Verified: all 7 solutions build with 0 errors; 8 tests pass across the four test projects (cluster-client 2, Autofac 2, SqlSharding 3, ReliableRabbitMQ 1).
1 parent 394a336 commit df2e35d

13 files changed

Lines changed: 365 additions & 0 deletions

File tree

‎Directory.Packages.props‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@
1919
<PackageVersion Include="Akka.Discovery.Azure" Version="$(AkkaVersion)" />
2020
<PackageVersion Include="Akka.Management" Version="$(AkkaVersion)" />
2121
<PackageVersion Include="Akka.Persistence.Sql.Hosting" Version="1.5.70" />
22+
<PackageVersion Include="Akka.Persistence.Hosting" Version="$(AkkaHostingVersion)" />
2223
<PackageVersion Include="Akka.Serialization.Hyperion" Version="$(AkkaVersion)" />
2324
<PackageVersion Include="Akka.Streams.Amqp.RabbitMq" Version="1.5.59" />
2425
<PackageVersion Include="Akka.Hosting.TestKit" Version="$(AkkaHostingVersion)" />

‎src/clustering/sharding-sqlserver/ShardingSqlServer.slnx‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,4 +2,5 @@
22
<Project Path="SqlSharding.Shared/SqlSharding.Shared.csproj" />
33
<Project Path="SqlSharding.Sql.Host/SqlSharding.Sql.Host.csproj" />
44
<Project Path="SqlSharding.WebApp/SqlSharding.WebApp.csproj" />
5+
<Project Path="SqlSharding.Tests/SqlSharding.Tests.csproj" />
56
</Solution>
Lines changed: 103 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,103 @@
1+
using Akka.Actor;
2+
using Akka.Hosting;
3+
using Akka.Hosting.TestKit;
4+
using Akka.Persistence.Hosting;
5+
using Akka.TestKit;
6+
using Microsoft.Extensions.DependencyInjection;
7+
using Microsoft.Extensions.Hosting;
8+
using SqlSharding.Host.Actors;
9+
using SqlSharding.Shared;
10+
using SqlSharding.Shared.Commands;
11+
using SqlSharding.Shared.Queries;
12+
using Xunit;
13+
14+
namespace SqlSharding.Tests;
15+
16+
/// <summary>
17+
/// Exercises <see cref="ProductTotalsActor"/>, the persistent (ReceivePersistentActor)
18+
/// shard entity, against the in-memory journal/snapshot store. These tests confirm
19+
/// command handling, the CommandResponse contract, and that state is recovered by
20+
/// replaying persisted events after an actor restart — WITHOUT requiring SQL Server.
21+
/// </summary>
22+
public class ProductTotalsActorTests : TestKit
23+
{
24+
// Entity id used as the actor's persistenceId argument. ProductTotalsActor
25+
// prepends the "totals-" entity-name constant to form the real PersistenceId.
26+
private const string EntityId = "product-foo";
27+
28+
// Created inside ConfigureAkka's WithActors callback (NOT the constructor).
29+
// The TestKit base initializes Sys during InitializeAsync, which runs after
30+
// the constructor, so CreateTestProbe() in the constructor throws NRE.
31+
private TestProbe? _sender;
32+
private IActorRef? _totalsActor;
33+
34+
protected override void ConfigureAkka(AkkaConfigurationBuilder builder, IServiceProvider provider)
35+
{
36+
builder
37+
.WithInMemoryJournal()
38+
.WithInMemorySnapshotStore()
39+
.WithActors((system, registry, resolver) =>
40+
{
41+
_sender = CreateTestProbe();
42+
_totalsActor = system.ActorOf(resolver.Props<ProductTotalsActor>(EntityId), "totals-actor");
43+
});
44+
}
45+
46+
[Fact]
47+
public async Task CreateProduct_Persists_And_Replies_With_CommandResponse()
48+
{
49+
var actor = _totalsActor!;
50+
actor.Tell(new CreateProduct(EntityId, "Foo", 10.99m, 5, new[] { "tag-a" }), _sender!.Ref);
51+
52+
var response = _sender.ExpectMsg<ProductCommandResponse>(TimeSpan.FromSeconds(5));
53+
Assert.True(response.Success);
54+
Assert.Equal(EntityId, response.ProductId);
55+
// CreateProduct yields ProductCreated + ProductInventoryChanged.
56+
Assert.Equal(2, response.ResponseEvents.Count);
57+
}
58+
59+
[Fact]
60+
public async Task SupplyProduct_Updates_Inventory_Totals()
61+
{
62+
var actor = _totalsActor!;
63+
actor.Tell(new CreateProduct(EntityId, "Foo", 10.99m, 5, new[] { "tag-a" }), _sender!.Ref);
64+
_sender.ExpectMsg<ProductCommandResponse>(TimeSpan.FromSeconds(5));
65+
66+
actor.Tell(new SupplyProduct(EntityId, 10), _sender.Ref);
67+
var supply = _sender.ExpectMsg<ProductCommandResponse>(TimeSpan.FromSeconds(5));
68+
Assert.True(supply.Success);
69+
70+
// Verify the projected totals via the query.
71+
actor.Tell(new FetchProduct(EntityId), _sender.Ref);
72+
var result = _sender.ExpectMsg<FetchResult>(TimeSpan.FromSeconds(5));
73+
Assert.Equal(15, result.State.Totals.RemainingInventory);
74+
Assert.Equal("Foo", result.State.Data.ProductName);
75+
}
76+
77+
[Fact]
78+
public async Task Restart_Replays_Events_And_Recovers_State()
79+
{
80+
var actor = _totalsActor!;
81+
// Build up some persisted state.
82+
actor.Tell(new CreateProduct(EntityId, "Foo", 10.99m, 5, new[] { "tag-a" }), _sender!.Ref);
83+
_sender.ExpectMsg<ProductCommandResponse>(TimeSpan.FromSeconds(5));
84+
85+
actor.Tell(new SupplyProduct(EntityId, 10), _sender.Ref);
86+
var supply = _sender.ExpectMsg<ProductCommandResponse>(TimeSpan.FromSeconds(5));
87+
Assert.True(supply.Success);
88+
89+
// Stop the actor and wait for termination before recreating it with the
90+
// same persistenceId so recovery must come from the journal replay.
91+
Watch(actor);
92+
actor.Tell(PoisonPill.Instance);
93+
ExpectTerminated(actor, TimeSpan.FromSeconds(5));
94+
95+
var recovered = Sys.ActorOf(Props.Create(() => new ProductTotalsActor(EntityId)), "totals-actor-recovered");
96+
97+
// After restart, querying must return the replayed state (remaining = 15).
98+
recovered.Tell(new FetchProduct(EntityId), _sender.Ref);
99+
var result = _sender.ExpectMsg<FetchResult>(TimeSpan.FromSeconds(5));
100+
Assert.Equal(15, result.State.Totals.RemainingInventory);
101+
Assert.Equal("Foo", result.State.Data.ProductName);
102+
}
103+
}
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
<Project Sdk="Microsoft.NET.Sdk">
2+
3+
<PropertyGroup>
4+
<OutputType>Exe</OutputType>
5+
<TargetFramework>net10.0</TargetFramework>
6+
<ImplicitUsings>enable</ImplicitUsings>
7+
<Nullable>enable</Nullable>
8+
<LangVersion>latestmajor</LangVersion>
9+
<IsPackable>false</IsPackable>
10+
<UseMicrosoftTestingPlatformRunner>true</UseMicrosoftTestingPlatformRunner>
11+
</PropertyGroup>
12+
13+
<ItemGroup>
14+
<PackageReference Include="Akka.Hosting.TestKit" />
15+
<PackageReference Include="Akka.Persistence.Hosting" />
16+
<PackageReference Include="xunit.v3" />
17+
</ItemGroup>
18+
19+
<ItemGroup>
20+
<ProjectReference Include="..\SqlSharding.Sql.Host\SqlSharding.Sql.Host.csproj" />
21+
</ItemGroup>
22+
23+
</Project>
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
using System.Runtime.CompilerServices;
2+
3+
namespace SqlSharding.Tests;
4+
5+
internal static class TestEnvironmentInitializer
6+
{
7+
[ModuleInitializer]
8+
internal static void Initialize()
9+
{
10+
// Disable config file watching in test hosts.
11+
// Prevents file descriptor exhaustion (inotify watch limit) on Linux
12+
// when running many Akka.Hosting.TestKit tests.
13+
Environment.SetEnvironmentVariable("DOTNET_HOSTBUILDER__RELOADCONFIGONCHANGE", "false");
14+
}
15+
}
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
<Project Sdk="Microsoft.NET.Sdk">
2+
3+
<PropertyGroup>
4+
<OutputType>Exe</OutputType>
5+
<TargetFramework>net10.0</TargetFramework>
6+
<ImplicitUsings>enable</ImplicitUsings>
7+
<Nullable>enable</Nullable>
8+
<LangVersion>latestmajor</LangVersion>
9+
<IsPackable>false</IsPackable>
10+
<UseMicrosoftTestingPlatformRunner>true</UseMicrosoftTestingPlatformRunner>
11+
</PropertyGroup>
12+
13+
<ItemGroup>
14+
<PackageReference Include="Akka.Hosting.TestKit" />
15+
<PackageReference Include="xunit.v3" />
16+
</ItemGroup>
17+
18+
<ItemGroup>
19+
<ProjectReference Include="..\AutofacIntegration\AutofacIntegration.csproj" />
20+
</ItemGroup>
21+
22+
</Project>
Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
1+
using Akka.Actor;
2+
using Akka.Hosting;
3+
using Akka.Hosting.TestKit;
4+
using Akka.TestKit;
5+
using Autofac;
6+
using AutoFacIntegration;
7+
using Microsoft.Extensions.DependencyInjection;
8+
using Microsoft.Extensions.Hosting;
9+
using Xunit;
10+
11+
namespace AutofacIntegration.Tests;
12+
13+
public class EchoActorTests : TestKit
14+
{
15+
// Created during host startup (ConfigureAkka), once the ActorSystem exists,
16+
// not in the constructor. The constructor runs before InitializeAsync, so
17+
// CreateTestProbe() there throws NullReferenceException.
18+
private TestProbe? _echoProbe;
19+
20+
protected override void ConfigureServices(HostBuilderContext context, IServiceCollection services)
21+
{
22+
// Replace the Autofac-container-registered AutofacInjected with a DI-registered
23+
// instance. EchoActor is constructed from the IServiceProvider, so this is the
24+
// instance it receives (the test-side "fake" for the Autofac path).
25+
services.AddSingleton<AutofacInjected>(new AutofacInjected());
26+
27+
// EchoActor also requires an Autofac lifetime scope to be resolvable, and its
28+
// PreStart resolves AutofacInjected from that scope. Register the same type the
29+
// sample's ConfigureContainer registers so the scope can resolve AutofacInjected.
30+
var builder = new ContainerBuilder();
31+
builder.RegisterType<AutofacInjected>();
32+
var container = builder.Build();
33+
services.AddSingleton<ILifetimeScope>(container.BeginLifetimeScope());
34+
}
35+
36+
protected override void ConfigureAkka(AkkaConfigurationBuilder builder, IServiceProvider provider)
37+
{
38+
// Probes are created here, inside host startup, NOT in the constructor:
39+
// the ActorSystem only exists after InitializeAsync runs.
40+
builder.StartActors((system, registry, resolver) =>
41+
{
42+
_echoProbe = CreateTestProbe();
43+
var echoActor = system.ActorOf(resolver.Props<EchoActor>(), "echo-actor");
44+
registry.Register<EchoActor>(echoActor);
45+
});
46+
}
47+
48+
[Fact]
49+
public async Task EchoActor_Replies_With_Same_Message()
50+
{
51+
var echo = ActorRegistry.Get<EchoActor>();
52+
var sender = CreateTestProbe();
53+
54+
// Send from a probe so we control who receives the echoed reply.
55+
echo.Tell("ping", sender.Ref);
56+
57+
var reply = sender.ExpectMsg<string>(TimeSpan.FromSeconds(5));
58+
Assert.Equal("ping", reply);
59+
}
60+
61+
[Fact]
62+
public async Task EchoActor_Registered_In_ActorRegistry()
63+
{
64+
var echo = ActorRegistry.Get<EchoActor>();
65+
Assert.NotNull(echo);
66+
67+
// The same actor is registered once; resolving for the actor type succeeds.
68+
var again = ActorRegistry.Get<EchoActor>();
69+
Assert.Same(echo, again);
70+
}
71+
}
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
using System.Runtime.CompilerServices;
2+
3+
namespace AutofacIntegration.Tests;
4+
5+
internal static class TestEnvironmentInitializer
6+
{
7+
[ModuleInitializer]
8+
internal static void Initialize()
9+
{
10+
// Disable config file watching in test hosts.
11+
// Prevents file descriptor exhaustion (inotify watch limit) on Linux
12+
// when running many Akka.Hosting.TestKit tests.
13+
Environment.SetEnvironmentVariable("DOTNET_HOSTBUILDER__RELOADCONFIGONCHANGE", "false");
14+
}
15+
}
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
11
<Solution>
22
<Project Path="AutofacIntegration/AutofacIntegration.csproj" />
3+
<Project Path="AutofacIntegration.Tests/AutofacIntegration.Tests.csproj" />
34
</Solution>
Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
using Akka.Actor;
2+
using Akka.Hosting;
3+
using Akka.Hosting.TestKit;
4+
using Akka.TestKit;
5+
using Microsoft.Extensions.DependencyInjection;
6+
using Microsoft.Extensions.Hosting;
7+
using ReliableRabbitMQ.Consumer.Actors;
8+
using ReliableRabbitMQ.Shared.Messages;
9+
using Xunit;
10+
11+
namespace ReliableRabbitMQ.Tests;
12+
13+
/// <summary>
14+
/// Unit tests for <see cref="ProductActor"/>.
15+
///
16+
/// ProductActor is the only actor in the sample that can be unit-tested without a
17+
/// live broker. The RabbitMqConsumerActor and AmqpProducerActor both open live AMQP
18+
/// streams inside <c>PreStart</c> and are NOT unit-testable without a RabbitMQ broker;
19+
/// they are intentionally not covered here.
20+
///
21+
/// ProductActor has a nondeterministic behaviour: <see cref="ProductActor.SimulateNetworkFailure"/>
22+
/// randomly drops about half of incoming <see cref="CreateOrder"/> messages without replying.
23+
/// To keep the test deterministic we drive the success path only, retrying with fresh
24+
/// distinct orders until a reply is observed. The probability that a recognizable number
25+
/// of consecutive attempts all fail is negligible (0.5^n), so the test is effectively
26+
/// deterministic while remaining robust to the actor's random dropout.
27+
/// </summary>
28+
public class ProductActorTests : TestKit
29+
{
30+
private const string ProductId = "prod-1";
31+
32+
// Created during host startup (ConfigureAkka), once the ActorSystem exists, not in the
33+
// constructor. The constructor runs before InitializeAsync, so CreateTestProbe() there
34+
// throws NullReferenceException.
35+
private TestProbe? _senderProbe;
36+
37+
protected override void ConfigureAkka(AkkaConfigurationBuilder builder, IServiceProvider provider)
38+
{
39+
builder.WithActors((system, registry, resolver) =>
40+
{
41+
_senderProbe = CreateTestProbe();
42+
var productActor = system.ActorOf(ProductActor.CreateProps(ProductId), "product");
43+
registry.Register<ProductActor>(productActor);
44+
});
45+
}
46+
47+
[Fact]
48+
public async Task ProductActor_Acknowledges_Order_When_Network_Is_Healthy()
49+
{
50+
var actor = ActorRegistry.Get<ProductActor>();
51+
52+
// Drive the deterministic success path: keep issuing fresh distinct orders
53+
// (ProductActor drops ~50% of them randomly without replying) until we observe
54+
// an OrderCommandAck. Failure probability across the attempts is negligible.
55+
OrderCommandAck? observed = null;
56+
for (var i = 0; i < 200 && observed is null; i++)
57+
{
58+
var order = new CreateOrder(Guid.NewGuid().ToString(), "customer", ProductId, 2);
59+
60+
// Tell from the probe so we control who receives the reply, just like the
61+
// RabbitMqConsumerActor does via ShardRegion Tell.
62+
actor.Tell(order, _senderProbe!.Ref);
63+
64+
// If the order was not randomly dropped, ProductActor replies with an ack
65+
// addressed to the sender. Wait a short window; a null means this order was
66+
// dropped by the simulated network failure, so try the next one.
67+
if (_senderProbe.ReceiveOne(TimeSpan.FromMilliseconds(100), TestContext.Current.CancellationToken) is OrderCommandAck ack)
68+
observed = ack;
69+
}
70+
71+
Assert.NotNull(observed);
72+
Assert.Equal(ProductId, observed!.ProductId);
73+
}
74+
}

0 commit comments

Comments
 (0)