using System.Diagnostics.CodeAnalysis; using Microsoft.Extensions.DependencyInjection; namespace Cqrs.Tests.CqrsServicesExtensionsTests; public class AddQueryHandler { public class TestQuery {} public class TestQueryResult {} [ExcludeFromCodeCoverage] public class TestQueryHandler : IQueryHandler { public ValueTask Handle(TestQuery Query, CancellationToken cancellation) { throw new NotImplementedException(); } } [Theory] [InlineData(ServiceLifetime.Transient)] [InlineData(ServiceLifetime.Scoped)] [InlineData(ServiceLifetime.Singleton)] public void WhenCalled_ShouldRegisterQueryHandler(ServiceLifetime lifetime) { // Given ServiceCollection services = new(); // When services.AddCqrs(opt => opt.AddQueryHandler(lifetime)); // Then services.ShouldContain( elementPredicate: descriptor => descriptor.ServiceType == typeof(IQueryHandler) && descriptor.ImplementationType == typeof(TestQueryHandler) && descriptor.Lifetime == lifetime, expectedCount: 1 ); } [Fact] public void WhenCalledMultipleTimes_ShouldRegisterQueryHandlerOnce() { // Given ServiceCollection services = new(); // When services.AddCqrs(opt => opt .AddQueryHandler() .AddQueryHandler() .AddQueryHandler()); services.AddCqrs(opt => opt .AddQueryHandler()); // Then services.ShouldContain( elementPredicate: descriptor => descriptor.ServiceType == typeof(IQueryHandler) && descriptor.ImplementationType == typeof(TestQueryHandler) && descriptor.Lifetime == ServiceLifetime.Transient, expectedCount: 1 ); } public class SecondTestQuery {} public class SecondTestQueryResult {} [ExcludeFromCodeCoverage] public class SecondTestQueryHandler : IQueryHandler { public ValueTask Handle(SecondTestQuery Query, CancellationToken cancellation) { throw new NotImplementedException(); } } public class ThirdTestQuery {} public class ThirdTestQueryResult {} [ExcludeFromCodeCoverage] public class ThirdTestQueryHandler : IQueryHandler { public ValueTask Handle(ThirdTestQuery Query, CancellationToken cancellation) { throw new NotImplementedException(); } } [Fact] public void WhenCalledMultipleTimes_ShouldRegisterAllQueryHandlers() { // Given ServiceCollection services = new(); // When services.AddCqrs(opt => opt .AddQueryHandler() .AddQueryHandler()); services.AddCqrs(opt => opt .AddQueryHandler()); // Then services.ShouldContain( elementPredicate: descriptor => descriptor.ServiceType == typeof(IQueryHandler) && descriptor.ImplementationType == typeof(TestQueryHandler) && descriptor.Lifetime == ServiceLifetime.Transient, expectedCount: 1 ); services.ShouldContain( elementPredicate: descriptor => descriptor.ServiceType == typeof(IQueryHandler) && descriptor.ImplementationType == typeof(SecondTestQueryHandler) && descriptor.Lifetime == ServiceLifetime.Transient, expectedCount: 1 ); services.ShouldContain( elementPredicate: descriptor => descriptor.ServiceType == typeof(IQueryHandler) && descriptor.ImplementationType == typeof(ThirdTestQueryHandler) && descriptor.Lifetime == ServiceLifetime.Transient, expectedCount: 1 ); } }