public void Calculate_ShouldReturnDiscountResult_WithCorrectProductsAndModel() { // Arrange Mock <IDateTimeUtil> mockDateTimeUtil = new Mock <IDateTimeUtil>(); mockDateTimeUtil.Setup(x => x.Now()).Returns(new DateTime(2020, 10, 15)); ITimespanDiscountCalculator timespanDiscountCalculator = new TimespanDiscountCalculator(mockDateTimeUtil.Object); List <Product> products = new List <Product>() { new Product() { Id = 1, Name = "Beans", PluralName = "Beans", Price = 0.65m }, new Product() { Id = 2, Name = "Bread", PluralName = "Breads", Price = 0.8m }, new Product() { Id = 3, Name = "Milk", PluralName = "Milk", Price = 1.3m }, new Product() { Id = 4, Name = "Apple", PluralName = "Apples", Price = 1.0m }, }; TimespanDiscount timespanDiscount = new TimespanDiscount() { Id = 1, BuyingProduct = products[3], From = new DateTime(2020, 10, 10), To = new DateTime(2020, 10, 20), DiscountedProduct = products[3], DiscountPercentage = 0.1f, IsActive = true }; IEnumerable <BasketItem> items = new List <BasketItem>() { new BasketItem() { Product = new BasketItemProduct() { Id = 4, Name = "Apple", PluralName = "Apples", Price = 1.0m }, Quantity = 1 }, }; // Act DiscountResult discountResult = timespanDiscountCalculator.Calculate(items, timespanDiscount); // Assert Assert.Equal(0.1f, discountResult.DiscountPercentage); Assert.Equal(0.10m, discountResult.DiscountedPrice); Assert.Equal("Apples", discountResult.ProductPluralName); }
public DiscountResult Calculate(IEnumerable <BasketItem> items, TimespanDiscount model) { if (items == null) { throw new ArgumentNullException(nameof(items)); } if (model == null) { throw new ArgumentNullException(nameof(model)); } DateTime currentDate = this.dateTimeUtil.Now(); if (currentDate < model.From || currentDate > model.To) { return(null); } BasketItem buyingProduct = items.FirstOrDefault(p => p.Product.Id == model.BuyingProduct.Id); if (buyingProduct == null) { return(null); } BasketItem productForDiscount = items.FirstOrDefault(p => p.Product.Id == model.DiscountedProduct.Id); if (productForDiscount == null) { return(null); } decimal currentPrice = productForDiscount.Product.Price; decimal discountedPrice = (currentPrice * (decimal)model.DiscountPercentage) * productForDiscount.Quantity; DiscountResult result = new DiscountResult(); result.DiscountedPrice = discountedPrice; result.ProductPluralName = productForDiscount.Product.PluralName; result.DiscountPercentage = model.DiscountPercentage; return(result); }