#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Common.Events;
using Lumina.Infrastructure.Common.DomainEvents;
using Microsoft.Extensions.DependencyInjection;
using NSubstitute;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Infrastructure.UnitTests.Common.DomainEvents;
///
/// Contains unit tests for the class.
///
[ExcludeFromCodeCoverage]
public class DomainEventPublisherTests
{
public sealed record TestDomainEvent(Guid Id, DateTime OccurredOnUtc) : IDomainEvent;
public sealed record NestedTestDomainEvent(Guid Id, DateTime OccurredOnUtc) : IDomainEvent;
private sealed class RecordingDomainEventHandler : IDomainEventHandler
{
private readonly List _callLog;
private readonly string _handlerName;
public RecordingDomainEventHandler(List callLog, string handlerName)
{
_callLog = callLog;
_handlerName = handlerName;
}
public ValueTask HandleAsync(TestDomainEvent domainEvent, CancellationToken cancellationToken)
{
_callLog.Add(_handlerName);
return ValueTask.CompletedTask;
}
}
///
/// Creates a publisher wired to a fresh service provider, optionally registering additional services.
///
/// Optional action used to register additional services into the provider.
/// A domain event publisher resolved from the created provider.
private static IDomainEventPublisher CreatePublisher(Action? configureServices = null)
{
IServiceCollection services = new ServiceCollection();
services.AddScoped();
configureServices?.Invoke(services);
ServiceProvider serviceProvider = services.BuildServiceProvider();
return serviceProvider.GetRequiredService();
}
///
/// Creates a valid instance of .
///
/// The created domain event.
private static TestDomainEvent CreateTestDomainEvent()
{
return new TestDomainEvent(Guid.NewGuid(), DateTime.UtcNow);
}
///
/// Creates a valid instance of .
///
/// The created domain event.
private static NestedTestDomainEvent CreateNestedTestDomainEvent()
{
return new NestedTestDomainEvent(Guid.NewGuid(), DateTime.UtcNow);
}
[Fact]
public async Task Publish_WhenHandlersAreRegistered_ShouldInvokeAllHandlersInOrder()
{
// Arrange
TestDomainEvent domainEvent = CreateTestDomainEvent();
List callLog = [];
IDomainEventPublisher publisher = CreatePublisher(services =>
{
services.AddScoped>(_ => new RecordingDomainEventHandler(callLog, "first"));
services.AddScoped>(_ => new RecordingDomainEventHandler(callLog, "second"));
});
// Act
await publisher.PublishAsync(domainEvent, CancellationToken.None);
// Assert
Assert.Equal(["first", "second"], callLog);
}
[Fact]
public async Task Publish_WhenNoHandlersAreRegisteredForTheEventType_ShouldNotThrow()
{
// Arrange
TestDomainEvent domainEvent = CreateTestDomainEvent();
IDomainEventPublisher publisher = CreatePublisher();
// Act
await publisher.PublishAsync(domainEvent, CancellationToken.None);
// Assert
// reaching this point without an exception means the publish was a no-op, as expected
}
[Fact]
public async Task Publish_WhenOnlyAnotherEventTypeHasHandlers_ShouldNotInvokeThem()
{
// Arrange
TestDomainEvent domainEvent = CreateTestDomainEvent();
IDomainEventHandler nestedHandler = Substitute.For>();
IDomainEventPublisher publisher = CreatePublisher(services => services.AddScoped(_ => nestedHandler));
// Act
await publisher.PublishAsync(domainEvent, CancellationToken.None);
// Assert
await nestedHandler.DidNotReceive().HandleAsync(Arg.Any(), Arg.Any());
}
[Fact]
public async Task Publish_WhenHandlerThrows_ShouldPropagateTheException()
{
// Arrange
TestDomainEvent domainEvent = CreateTestDomainEvent();
InvalidOperationException expectedException = new("Test exception");
IDomainEventHandler handler = Substitute.For>();
handler.HandleAsync(Arg.Any(), Arg.Any())
.Returns(callInfo => throw expectedException);
IDomainEventPublisher publisher = CreatePublisher(services => services.AddScoped>(_ => handler));
// Act
InvalidOperationException result = await Assert.ThrowsAsync(
() => publisher.PublishAsync(domainEvent, CancellationToken.None).AsTask());
// Assert
Assert.Same(expectedException, result);
}
[Fact]
public async Task Publish_WhenHandlerPublishesAnotherEvent_ShouldInvokeNestedHandlers()
{
// Arrange
TestDomainEvent domainEvent = CreateTestDomainEvent();
NestedTestDomainEvent nestedDomainEvent = CreateNestedTestDomainEvent();
IDomainEventHandler handler = Substitute.For>();
IDomainEventHandler nestedHandler = Substitute.For>();
IDomainEventPublisher publisher = CreatePublisher(services =>
{
services.AddScoped(_ => handler);
services.AddScoped(_ => nestedHandler);
});
handler.HandleAsync(domainEvent, Arg.Any())
.Returns(callInfo => publisher.PublishAsync(nestedDomainEvent, callInfo.Arg()));
// Act
await publisher.PublishAsync(domainEvent, CancellationToken.None);
// Assert
await nestedHandler.Received(1).HandleAsync(nestedDomainEvent, Arg.Any());
}
[Fact]
public async Task Publish_WhenCancellationRequested_ShouldPassTokenToHandlers()
{
// Arrange
TestDomainEvent domainEvent = CreateTestDomainEvent();
using CancellationTokenSource cancellationTokenSource = new();
CancellationToken cancellationToken = cancellationTokenSource.Token;
IDomainEventHandler handler = Substitute.For>();
IDomainEventPublisher publisher = CreatePublisher(services => services.AddScoped(_ => handler));
// Act
await publisher.PublishAsync(domainEvent, cancellationToken);
// Assert
await handler.Received(1).HandleAsync(domainEvent, Arg.Is(cancellationToken));
}
[Fact]
public async Task Publish_WhenDomainEventIsNull_ShouldThrowArgumentNullException()
{
// Arrange
IDomainEventPublisher publisher = CreatePublisher();
// Act
ArgumentNullException result = await Assert.ThrowsAsync(() => publisher.PublishAsync(null!, CancellationToken.None).AsTask());
// Assert
Assert.Equal("domainEvent", result.ParamName);
}
}