public Order Add(Order order) { var result = _validator.Validate(order); if (!result.IsValid) { throw new InvalidOperationException(result.ToString()); } return(_orderService.Add(order)); }
public void OrderShouldBeValid() { //Act Order sut = new Order() { Price = 1 }; var results = validator.Validate(sut); //Assert Assert.True(results.IsValid); }
public OrderDTO AddOrder(OrderDTO orderDto) { var order = OrderMapper.DtoToDomain(orderDto); var errorMessages = new List <string>(); if (!OrderValidator.Validate(order, unitOfWork, ref errorMessages)) { throw new InvalidObjectException("Order", orderDto, errorMessages); } try { var customer = unitOfWork.CustomerRepository.GetById(order.CustomerId); order.CustomerName = customer.CustomerName; order.CustomerNumber = customer.CustomerNumber; unitOfWork.OrderRepository.Add(order); unitOfWork.Commit(); return(OrderMapper.DomainToDto(order)); } catch (Exception exception) { throw new Exception("An exception occured adding customer: ", exception); } }
public IActionResult SessionCartOrder(OrderViewModel order) { var validator = new OrderValidator(); var validationResult = validator.Validate(order); if (!validationResult.IsValid) { var model = _orderService.PrepareSessionCartOrder(); foreach (var error in validationResult.Errors) { model.Errors.Add(error.ToString()); } return(View(model)); } int orderId = _orderService.AddOrder(order); _shoppingCartService.Cart.Lines.Clear(); ViewData["orderId"] = orderId; return(View("Success")); }
public Result <Order> CreateOrder(OrderDTO orderDTO) { ICollection <OrderDetail> orderDetails = orderDTO.OrderDetails.Select(od => new OrderDetail(od.Product, od.Price, od.Count)).ToList(); Order order = new Order(orderDetails); //string failureMesasge = order.IsValid(); OrderValidator orderValidator = new OrderValidator(); var validationResult = orderValidator.Validate(order); //if (failureMesasge == string.Empty) if (validationResult.IsValid) { try { OrdersDbSet.Add(order); _context.SaveChanges(); return(Result <Order> .Ok(order)); } catch (Exception ex) { Console.WriteLine(ex); return(Result.Fail <Order>(ex.Message)); } } else { return(Result.Fail <Order>(string.Join(" ", validationResult.Errors))); } //return Result.Fail<Order>(failureMesasge); }
public void Should_Be_Valid_When_Required_Values_Are_Present() { // Arrange var order = new Order { OrderDate = DateTime.Now, CustomerId = 1 }; order.Items.Add(GetValidOrderLineItem()); // Act var result = _validator.Validate(order); // Assert result.IsValid .Should() .BeTrue(); }
public IActionResult Update([FromBody] OrderViewModel model) { try { var results = _validator.Validate(model); if (!results.IsValid) { throw new Exception(results.Errors[0].ErrorMessage); } var savedModel = _orderService.UpdateOrder(model); return(Ok(savedModel)); } catch (Exception e) { return(BadRequest(e)); } }
public void ValidOrder_IsValid() { var emptyOrder = new OrderBuilder().Build(); var sut = new OrderValidator(); var sutInvalidResult = sut.Validate(emptyOrder); Assert.False(sutInvalidResult.IsValid); var validOrder = new OrderBuilder() .WithOrderLine() .WithShippingAddress() .Build(); var sutValidResult = sut.Validate(validOrder); Assert.True(sutValidResult.IsValid); }
public void OrderValidatorTests_ThrowsError_WhenRequstedProductDoesNotExist() { var serviceMethodId = Guid.NewGuid(); _productRepository.Setup(r => r.GetProductIds()).ReturnsAsync(new List <Guid>()); _serviceMethodRepository.Setup(r => r.GetServiceMethodIds()).ReturnsAsync(new List <Guid> { serviceMethodId }); var result = _validator.Validate(new OrderDto { ProductId = Guid.NewGuid(), ServiceMethodId = serviceMethodId }); Assert.False(result.IsValid); Assert.Single(result.Errors); Assert.Equal(ErrorMessages.OrderedProductDoesNotExist, result.Errors.Single().ErrorMessage); }
public string ProcessOrder(string input) { var order = Converter.TryParse(input); OrderValidator.Validate(order); Trimmer.TrimOrder(order); DishSorter.Sort(order); return(OutputGenerator.GenerateResult(order)); }
public void ValidOrder_IsValid() { var order = new Tests.ValidOrderBuilder().Build(); var sut = new OrderValidator(); var sutResult = sut.Validate(order); Assert.True(sutResult.IsValid); Assert.Empty(sutResult.ValidationErrors); }
public void OrderMustHaveOneOrderLine() { var validOrder = new OrderBuilder() .WithOrderLine() .Build(); var sut = new OrderValidator(); var sutValidResult = sut.Validate(validOrder); Assert.True(sutValidResult.IsValid); }
public (bool isValid, IEnumerable <ValidationResult> errors) Validate() { var validator = new OrderValidator(); var result = validator.Validate(this); if (result.IsValid) { return(true, null); } return(false, result.Errors.Select(item => new ValidationResult(item.ErrorMessage, new [] { item.PropertyName }))); }
public void OrderWithOutOrderLine_IsNotValid() { var emptyOrder = new OrderBuilder() .Build(); var sut = new OrderValidator(); var sutInvalidResult = sut.Validate(emptyOrder); Assert.False(sutInvalidResult.IsValid); Assert.Single(sutInvalidResult.ValidationErrors); Assert.Equal(ValidationErrorTypes.OrderlinesRequired, sutInvalidResult.ValidationErrors.First().Type); }
public void Validate(Notification note) { var validator = new OrderValidator(); validator.Validate(note, this); foreach (var orderItem in this.items) { orderItem.Validate(note); } IsValid = !note.HasErrors; }
public void RejectWhenQuantityIsZero() { var dummyProduct = new Product(); var result = _sut.Validate(0, dummyProduct); Assert.Equal(OrderResult.Rejected, result); }
public void TestFailOnNullClientOrderNumber() { const string expectedMessage = "MISSING VALUE - CountryCode is required. Use SetCountryCode(...).\n" + "MISSING VALUE - ClientOrderNumber is required. Use SetClientOrderNumber(...).\n" + "MISSING VALUE - Currency is required. Use SetCurrency(...).\n" + "MISSING VALUE - OrderRows are required. Use AddOrderRow(Item.OrderRow) to get orderrow setters.\n"; CreateOrderBuilder order = WebpayConnection.CreateOrder(SveaConfig.GetDefaultConfig()) .AddCustomerDetails(TestingTool.CreateMiniCompanyCustomer()) .SetValidator(new VoidValidator()) .Build(); Assert.That(_orderValidator.Validate(order), Is.EqualTo(expectedMessage)); }
public void ValidOrder_WhenNoShippingAddress_InvalidatesCorrectly() { var order = new Tests.ValidOrderBuilder() .WithoutShippingAddress() .Build(); var sut = new OrderValidator(); var sutResult = sut.Validate(order); Assert.False(sutResult.IsValid); Assert.Single(sutResult.ValidationErrors); Assert.Equal(ValidationErrorTypes.ShippingAddressRequired, sutResult.ValidationErrors.First().Type); }
public void TestValidateFailOrderIsNull() { const string expectedMessage = "MISSING VALUE - CountryCode is required. Use SetCountryCode(...).\n" + "MISSING VALUE - ClientOrderNumber is required (has an empty value). Use SetClientOrderNumber(...).\n" + "MISSING VALUES - AmountExVat, Quantity and VatPercent are required for Orderrow. Use SetAmountExVat(), SetQuantity() and SetVatPercent().\n"; CreateOrderBuilder order = WebpayConnection.CreateOrder(SveaConfig.GetDefaultConfig()) .AddOrderRow(null) .SetCurrency(TestingTool.DefaultTestCurrency) .SetClientOrderNumber("") .AddCustomerDetails(TestingTool.CreateMiniCompanyCustomer()) .SetValidator(new VoidValidator()) .Build(); _orderValidator = new HostedOrderValidator(); Assert.That(_orderValidator.Validate(order), Is.EqualTo(expectedMessage)); }
public void TestValidateDeCustomerIdentity() { CreateOrderBuilder order = WebpayConnection.CreateOrder(SveaConfig.GetDefaultConfig()) .SetClientOrderNumber(TestingTool.DefaultTestClientOrderNumber) .SetCountryCode(CountryCode.DE) .SetCurrency(Currency.EUR) .AddOrderRow(Item.OrderRow() .SetAmountExVat(5.0M) .SetVatPercent(25) .SetQuantity(1)) .AddCustomerDetails(TestingTool.CreateMiniCompanyCustomer()); _orderValidator = new HostedOrderValidator(); Assert.That(_orderValidator.Validate(order), Is.Empty); }
public void ValidOrder_WhenMultipleErrors_ReportsMultipleErrors() { var order = new Tests.ValidOrderBuilder() .WithoutShippingAddress() .WithoutOrderLines() .Build(); var sut = new OrderValidator(); var sutResult = sut.Validate(order); Assert.False(sutResult.IsValid); Assert.Equal(2, sutResult.ValidationErrors.Count); Assert.NotNull(sutResult.ValidationErrors.First(f => f.Type == ValidationErrorTypes.ShippingAddressRequired)); Assert.NotNull(sutResult.ValidationErrors.First(f => f.Type == ValidationErrorTypes.OrderlinesRequired)); }
public async Task <Order> CreateOrder(Order order) { await orderValidator.Validate(order); var now = DateTime.Now; order.CreatedOn = now; order.LastModifiedOn = now; order.LastModifiedById = order.CreatedById; foreach (var orderItem in order.OrderItems) { orderItem.CreatedOn = now; orderItem.LastModifiedOn = now; } return(await orderRepository.CreateOrder(order)); }
public void TestFailAmountExVatAndVatPercentIsMissing() { const string expectedMessage = "MISSING VALUE - CountryCode is required. Use SetCountryCode(...).\n" + "MISSING VALUE - ClientOrderNumber is required (has an empty value). Use SetClientOrderNumber(...).\n" + "MISSING VALUE - At least one of the values must be set in combination with AmountIncVat: AmountExVat or VatPercent for Orderrow. Use one of: SetAmountExVat() or SetVatPercent().\n"; CreateOrderBuilder order = WebpayConnection.CreateOrder(SveaConfig.GetDefaultConfig()) .AddOrderRow(Item.OrderRow() .SetQuantity(1) .SetAmountIncVat(125)) .SetCurrency(TestingTool.DefaultTestCurrency) .SetClientOrderNumber("") .AddCustomerDetails(TestingTool.CreateMiniCompanyCustomer()) .SetValidator(new VoidValidator()) .Build(); _orderValidator = new HostedOrderValidator(); Assert.That(_orderValidator.Validate(order), Is.EqualTo(expectedMessage)); }
public async Task <IActionResult> Post([FromBody] OrderCreateDto newOrderDto) { var newOrder = _mapper.Map <Order>(newOrderDto); foreach (var item in newOrderDto.OrderItems) { newOrder.AddItem(_mapper.Map <OrderItem>(item)); } var validator = new OrderValidator(_orderrepository); var result = validator.Validate(newOrder); if (result.IsValid) { await _orderrepository.AddAsync(newOrder); return(Ok(newOrder)); } return(BadRequest(result.Errors)); }
private List <string> ValidateOrders(IEnumerable <Order> orders) { var errorsList = new List <string>(); var validator = new OrderValidator(); var result = new ValidationResult(); foreach (var order in orders) { result = validator.Validate(order); } if (!result.IsValid) { foreach (var failure in result.Errors) { var err = "Property " + failure.PropertyName + " failed validation. Error was: " + failure.ErrorMessage; errorsList.Add(err); _logger.LogError(err); } } return(errorsList); }
public void TestCheckOfIdentityClass() { const string expectedMessage = "MISSING VALUE - CountryCode is required. Use SetCountryCode().\n" + "MISSING VALUE - OrderRows are required. Use AddOrderRow(Item.OrderRow) to get orderrow setters.\n" + "MISSING VALUE - OrderDate is required. Use SetOrderDate().\n"; CreateOrderBuilder order = WebpayConnection.CreateOrder(SveaConfig.GetDefaultConfig()) .AddCustomerDetails(TestingTool.CreateCompanyCustomer()); Assert.That(_orderValidator.Validate(order), Is.EqualTo(expectedMessage)); }
/// <summary> /// Build /// </summary> /// <exception cref="SveaWebPayValidationException"></exception> /// <returns>CreateOrderBuilder</returns> public CreateOrderBuilder Build() { _validator.Validate(this); return(this); }