Example #1
0
        public async Task AddProductCommandHandler_Success()
        {
            //Arrange
            basketRedisService.Setup(x => x.GetBasket(It.IsAny <string>())).Returns(Task.FromResult(basketDto));

            //Act
            var action = await commandHandler.Handle(command, It.IsAny <CancellationToken>());

            //Assert
            Assert.Equal(Unit.Value, action);
            basketRedisService.Verify(x => x.SaveBasket(It.IsAny <string>(), It.IsAny <UserBasketDto>()), Times.Once);
        }
Example #2
0
        public async Task Should_ThrowException_When_InputIsNull()
        {
            var dbContext = new Mock <CleanArchWriteDbContext>();
            var logger    = new Mock <ILogger <AddProductCommandHandler> >();

            var commandHandler = new AddProductCommandHandler(dbContext.Object, logger.Object);

            var request = new Mock <AddProductCommand>();

            //await Assert.ThrowsAsync<InvalidNullInputException>(() => commandHandler.Handle(request.Object, CancellationToken.None));
            await Assert.ThrowsAsync <InvalidNullInputException>(() => commandHandler.Handle(null, CancellationToken.None));
        }
Example #3
0
        public void WhenUserAddsTheProduct(string userName, Table table)
        {
            var user = sessionFactory.OpenSession().Query <User>().First(u => u.UserName == userName);

            var command = new AddProductCommand();

            command.UserId       = user.Id;
            command.ProductName  = table.Rows[0]["Name"];
            command.ProductNotes = table.Rows[0]["Notes"];

            var handler = new AddProductCommandHandler(sessionFactory.OpenSession());
            var result  = handler.Handle(command);

            ScenarioContext.Current.Set(command);
        }
Example #4
0
        public void AddProduct_IfIsCorrect_ShouldSuccess()
        {
            SystemTime.NowFunc = () => new DateTime(2019, 4, 1);

            var command = new AddProductCommand
            {
                Name                = "Mleko",
                ExpirationDate      = new DateTime(2019, 4, 17),
                MaxDaysAfterOpening = 2
            };

            var handler = new AddProductCommandHandler(ServiceFactory.ProductsRepository);
            var result  = handler.Handle(command);

            result.IsSuccess.Should().BeTrue();
        }
        public async Task AddProductCommandHandler_Success()
        {
            //Arrange
            mapper.Setup(x => x.Map <Product>(command)).Returns(product);

            productRepository.Setup(x => x.Add(product));
            productRepository.Setup(x => x.SaveAllAsync()).Returns(Task.FromResult(true));

            //Act
            var action = await commandHandler.Handle(command, It.IsAny <CancellationToken>());

            //Assert
            Assert.Equal(Unit.Value, action);
            productRepository.Verify(x => x.CheckIfExistByCondition(It.IsAny <Expression <Func <Product, bool> > >()), Times.Once);
            bus.Verify(x => x.Publish(It.IsAny <ProductAddedEvent>(), It.IsAny <CancellationToken>()), Times.Once);
        }
Example #6
0
        public void AddProduct_IfExpirationDateIsLessThanCurrent_ShouldFailure()
        {
            SystemTime.NowFunc = () => new DateTime(2019, 4, 20);

            var command = new AddProductCommand
            {
                Name                = "Mleko",
                ExpirationDate      = new DateTime(2019, 4, 17),
                MaxDaysAfterOpening = 2
            };

            var handler = new AddProductCommandHandler(ServiceFactory.ProductsRepository);
            var result  = handler.Handle(command);

            result.IsSuccess.Should().BeFalse();
            result.ErrorMessage.Should().BeEquivalentTo("Expiration date should be greater than current date.");
        }
Example #7
0
        public void AddProduct_IfNameIsEmpty_ShouldFailure()
        {
            SystemTime.NowFunc = () => new DateTime(2019, 4, 1);

            var command = new AddProductCommand
            {
                Name                = "",
                ExpirationDate      = new DateTime(2019, 4, 17),
                MaxDaysAfterOpening = 2
            };

            var handler = new AddProductCommandHandler(ServiceFactory.ProductsRepository);
            var result  = handler.Handle(command);

            result.IsSuccess.Should().BeFalse();
            result.ErrorMessage.Should().BeEquivalentTo("Product name can not be empty.");
        }
Example #8
0
        public async Task Execute_CorrectCommand_ReturnsSuccess()
        {
            //Arrange
            var command = new AddProductCommand {
                Name = "TestProduct", CarbsGrams = 12, FatsGrams = 22, ProteinsGrams = 31
            };
            var validator = new Mock <AbstractValidator <AddProductCommand> >();

            validator.Setup(x => x.Validate(It.IsAny <ValidationContext <AddProductCommand> >())).Returns(new ValidationResult());
            var handler = new AddProductCommandHandler(_config.Object, _logger.Object, validator.Object, _context);

            //Act
            var result = await handler.Handle(command);

            //Assert
            Assert.AreEqual(result.Success, true);
        }
        public void CreateProductSuccessfully(Product product)
        {
            _productService.Setup(ps => ps.CreateProduct(It.IsAny <Product>())).ReturnsAsync(product.Id);

            var handler = new AddProductCommandHandler(_productService.Object);

            var result = handler.Handle(new AddProductCommand()
            {
                Product = new ProductVm()
                {
                    Name  = product.Name,
                    Price = product.Price
                }
            }, default);

            Assert.IsNotNull(result);
            Assert.IsInstanceOf <Task <Response <ProductVm> > >(result);
            Assert.AreEqual(StatusCodes.Status200OK, result.Result.StatusCode);
        }
Example #10
0
        public void AddProduct_IfIsCorrect_ShouldIncreaseProductsCount()
        {
            SystemTime.NowFunc = () => new DateTime(2019, 4, 1);

            var command = new AddProductCommand
            {
                Name                = "Mleko",
                ExpirationDate      = new DateTime(2019, 4, 17),
                MaxDaysAfterOpening = 2
            };

            var productsRepository = ServiceFactory.ProductsRepository;

            productsRepository.Query().Count().Should().Be(0);

            var handler = new AddProductCommandHandler(productsRepository);

            handler.Handle(command);

            productsRepository.Query().Count().Should().Be(1);
        }
Example #11
0
        public async Task Execute_IncorrectCommand_ReturnsFailure()
        {
            //Arrange
            var command = new AddProductCommand {
                Name = "TestProduct3", CarbsGrams = 12, FatsGrams = 22, ProteinsGrams = 31
            };
            var validator = new Mock <AbstractValidator <AddProductCommand> >();
            var incorrectValidationResultStub = new ValidationResult()
            {
                Errors = { new ValidationFailure("Name", "IncorrectName") }
            };

            validator.Setup(x => x.Validate(It.IsAny <ValidationContext <AddProductCommand> >()))
            .Returns(incorrectValidationResultStub);
            var handler = new AddProductCommandHandler(_config.Object, _logger.Object, validator.Object, _context);

            //Act
            var result = await handler.Handle(command);

            //Assert
            Assert.AreEqual(result.Success, false);
        }
        public async Task CommandIsValid_Executed_Success()
        {
            // Arrange
            var productRepository = new Mock <IProductRepository>();
            var addProductCommand = new AddProductCommand("titulo", "descricao", 1000);

            var product = new Product("", "", 1000);

            // productRepository.Setup(pr => pr.Add(It.IsAny<Product>())).Verifiable();
            productRepository.Setup(pr => pr.Add(It.IsAny <Product>())).Returns(Task.FromResult(product));

            var addProductCommandHandler = new AddProductCommandHandler(productRepository.Object);

            // Act
            var productResult = await addProductCommandHandler.Handle(addProductCommand, new CancellationToken());

            // Assert
            productRepository.Verify(pr => pr.Add(It.IsAny <Product>()), Times.Once);
            Assert.NotNull(productResult);
            Assert.Equal(product.Price, productResult.Price);
            Assert.Equal(product.Title, productResult.Title);
            Assert.Equal(product.Description, productResult.Description);
        }
        public void Handle(Command command)
        {
            switch (command)
            {
            case AddCustomerCommand ac:
                addCustomerCommandHandler.Handle(ac);
                break;

            case AddOrderCommand ao:
                addOrderCommandHandler.Handle(ao);
                break;

            case AddProductCommand ap:
                addProductCommandHandler.Handle(ap);
                break;

            case AddProductToOrder apo:
                addProductToOrderCommandHandler.Handle(apo);
                break;

            default:
                throw new Exception($"Unknown command {command.GetType().Name}");
            }
        }
Example #14
0
        public void GivenUserHasSavedTheFollowingProducts(string userName, Table table)
        {
            using (var session = sessionFactory.OpenSession())
            {
                var user = session.Query <User>().First(u => u.UserName == userName);

                foreach (var row in table.Rows)
                {
                    var command = new AddProductCommand
                    {
                        UserId       = user.Id,
                        ProductName  = row["Name"],
                        ProductNotes = row["Notes"]
                    };

                    var handler  = new AddProductCommandHandler(session);
                    var response = handler.Handle(command);

                    if (row.ContainsKey("Tags") && !string.IsNullOrWhiteSpace(row["Tags"]))
                    {
                        var addTagHandler = new AddTagToProductCommandHandler(session);
                        var tagNames      = row["Tags"].Split(',').Select(t => t.Trim());
                        foreach (var tagName in tagNames)
                        {
                            var addTagCommand = new AddTagToProductCommand
                            {
                                UserId    = user.Id,
                                ProductId = response.NewProductId,
                                TagName   = tagName
                            };
                            addTagHandler.Handle(addTagCommand);
                        }
                    }
                }
            }
        }