using System; using System.Reflection; using System.Threading; using System.Threading.Tasks; using Autofac; using MediatR; using Microsoft.eShopOnContainers.Services.Ordering.API.Application.Commands; using Microsoft.eShopOnContainers.Services.Ordering.Infrastructure.Idempotency; using Moq; using Ordering.API.Infrastructure.Behaviors; using Xunit; namespace UnitTest.Ordering.Application { public class ExistingCommandBehaviorTest { private readonly Mock _requestManager; private readonly Mock> _commandHandler; public ExistingCommandBehaviorTest() { _requestManager = new Mock(); _commandHandler = new Mock>(); } private ContainerBuilder PrepareContainerBuilder() { var builder = new ContainerBuilder(); builder.RegisterAssemblyTypes(typeof(IMediator).GetTypeInfo().Assembly) .AsImplementedInterfaces(); builder.Register(context => { var componentContext = context.Resolve(); return t => { object o; return componentContext.TryResolve(t, out o) ? o : null; }; }); builder.RegisterInstance(_requestManager.Object).AsImplementedInterfaces(); builder.RegisterInstance(_commandHandler.Object).AsImplementedInterfaces(); builder.RegisterGeneric(typeof(ExistingCommandBehavior<,>)).As(typeof(IPipelineBehavior<,>)); return builder; } [Fact] public async Task Handler_sends_command_when_no_order_exists() { //Arrange var command = new CreateOrderCommand(); _requestManager.Setup(x => x.ExistAsync(It.IsAny())) .Returns(Task.FromResult(false)); var builder = PrepareContainerBuilder(); var container = builder.Build(); var mediator = container.Resolve(); //Act await mediator.Send(command); //Assert _commandHandler.Verify(x => x.Handle(It.IsAny(), It.IsAny()), Times.Once); } [Fact] public async Task Handler_sends_no_command_and_returns_defined_response_when_order_already_exists() { //Arrange var command = new CreateOrderCommand(); var existingCommandResponse = new Mock.ExistingCommand, bool>>(); existingCommandResponse.Setup(x => x.Handle(It.IsAny.ExistingCommand>(), It.IsAny())) .Returns(Task.FromResult(true)); _requestManager.Setup(x => x.ExistAsync(It.IsAny())) .Returns(Task.FromResult(true)); var builder = PrepareContainerBuilder(); builder.RegisterInstance(existingCommandResponse.Object).AsImplementedInterfaces(); var container = builder.Build(); var mediator = container.Resolve(); //Act var response = await mediator.Send(command); //Assert Assert.True(response); existingCommandResponse.Verify(x => x.Handle(It.IsAny.ExistingCommand>(), It.IsAny()), Times.Once); _commandHandler.Verify(x => x.Handle(It.IsAny(), It.IsAny()), Times.Never); } } }