public async Task when_updated_customer_it_should_be_updated_correctly_in_the_db()
        {
            ICustomerRepository _customerRepository = new CustomerRepository(_dbContextConfig.CompanyContext);

            var customer1 = new Customer("Justyna", "Stanczyk", "+48662622117");

            customer1.AddAddress(new CustomerAddress("190", "108", "Wadowica", "Kraków", "31-416"));
            var customer2 = new Customer("Karol", "Cichon", "+48504400336");

            customer2.AddAddress(new CustomerAddress("117", "06", "Krakowska", "Limanowa", "31-416"));
            await _customerRepository.AddAsync(customer1);

            await _customerRepository.AddAsync(customer2);

            var existingCustomer = await _customerRepository.GetByPhoneNumberAsync(customer1.TelephoneNumber);

            var existingCustomerWithAddress = await _customerRepository.GetWithAddressAsync(existingCustomer.Id);

            existingCustomerWithAddress.Update(existingCustomerWithAddress.Name, "Cichon", existingCustomerWithAddress.TelephoneNumber);
            existingCustomerWithAddress.CustomerAddress.Update("27", "28", "Krakowska", "Kraków", existingCustomerWithAddress.CustomerAddress.ZipCode);
            // // await _customerRepository.UpdateAsync (existingCustomerWithAddress);
            // var updatedCustomerWithAddress = await _customerRepository.GetWithAddressAsync (existingCustomerWithAddress.Id);
            // // Assert.Equal (existingCustomerWithAddress, updatedCustomerWithAddress);
            // Assert.Equal (customer2, existingCustomerWithAddress);
            customer1.ShouldBeEquivalentTo(existingCustomer);
        }
Пример #2
0
        public async Task UpdatesCustomerOrderStatusToPaidAfterTheReceivingOfOrderPaidNotification()
        {
            //Arrange
            var customerRepository       = new CustomerRepository(_dbContext);
            var suitAlterationRepository = new SuitAlterationRepository(_dbContext);
            var customer = CreateNewCustomer();
            await customerRepository.AddAsync(customer);

            customer.PlaceOrder(5, 5, 5, 5);
            await _unitOfWork.CommitAsync(CancellationToken.None);

            //Pre-assert
            var order = customer.SuitAlterations.Single();

            order.Status.Should().Be(SuitAlterationStatus.Created);

            //Act
            var markOrderAsPaidCommandHandler = new MarkOrderAsPaidCommandHandler(suitAlterationRepository);
            await markOrderAsPaidCommandHandler.Handle(new MarkOrderAsPaidCommand(order.Id), CancellationToken.None);

            await _unitOfWork.CommitAsync(CancellationToken.None);

            //Assert
            SuitAlteration paidOrder = await suitAlterationRepository.GetByIdAsync(order.Id);

            order.DomainEvents.Should().ContainEquivalentOf(new OrderPaidDomainEvent(order.Id));
            paidOrder.Status.Should().Be(SuitAlterationStatus.Paid);
            order.DomainEvents.Count.Should().Be(2);
        }
Пример #3
0
        public async Task EnsureInvoiceCreated()
        {
            var model = new InvoiceModelBuilder().Default;

            using (var ctx = CreateContext())
            {
                var repo     = new CustomerRepository(ctx);
                var customer = Mapper.Map <Customer>(new CustomerModelBuilder().Default);
                await repo.AddAsync(customer);

                var first = ctx.Customers.First();
                model.CustomerId = first.Id;
                var invoiceRepository = new InvoiceRepository(ctx);
                await invoiceRepository.AddAsync(Mapper.Map <Invoice>(model));
            }

            using (var ctx = CreateContext())
            {
                var repo     = new CustomerRepository(ctx);
                var customer = await repo.GetAsync(model.CustomerId);

                var invoices = customer.Invoices;
                invoices.Count.ShouldBe(1);
            }
        }
Пример #4
0
        public async Task ThrowsExceptionWhenOrderStatusIsPaidAndWeTriesToSetTheSameStatusAgain()
        {
            //Arrange
            var customerRepository       = new CustomerRepository(_dbContext);
            var suitAlterationRepository = new SuitAlterationRepository(_dbContext);

            var customer = CreateNewCustomer();
            await customerRepository.AddAsync(customer);

            customer.PlaceOrder(5, 5, 5, 5);
            await _unitOfWork.CommitAsync(CancellationToken.None);

            //Act
            var order = customer.SuitAlterations.Single();
            var markOrderAsPaidCommandHandler = new MarkOrderAsPaidCommandHandler(suitAlterationRepository);
            await markOrderAsPaidCommandHandler.Handle(new MarkOrderAsPaidCommand(order.Id), CancellationToken.None);

            await _unitOfWork.CommitAsync(CancellationToken.None);

            //Pre-assert
            order.DomainEvents.Should().ContainEquivalentOf(new OrderPaidDomainEvent(order.Id));
            //imagine that we got OrderPaidNotification second time
            Func <Task> action = async() => await markOrderAsPaidCommandHandler.Handle(new MarkOrderAsPaidCommand(order.Id), CancellationToken.None);

            //Assert
            action.Should().Throw <BusinessRuleValidationException>().WithMessage(
                $"Order has inconsistent status to be marked as paid. Status - {order.Status.ToString()}");
            order.DomainEvents.Count.Should().Be(2);
        }
Пример #5
0
        public async Task EnsureCustomerDeleted()
        {
            Customer customer;
            var      model = new CustomerModelBuilder().Default;

            using (var ctx = CreateContext())
            {
                var repo   = new CustomerRepository(ctx);
                var entity = Mapper.Map <Customer>(model);
                await repo.AddAsync(entity);

                var all = await repo.GetAllAsync();

                customer = all.First();
                await repo.DeleteAsync(customer.Id);
            }

            using (var ctx = CreateContext())
            {
                var repo  = new CustomerRepository(ctx);
                var found = await repo.GetAsync(customer.Id);

                found.ShouldBeNull();
            }
        }
Пример #6
0
        public async Task EnsureCustomerUpdated()
        {
            var model = new CustomerModelBuilder().Default;

            CustomerModel toUpdate;

            using (var ctx = CreateContext())
            {
                var repo   = new CustomerRepository(ctx);
                var entity = Mapper.Map <Customer>(model);
                await repo.AddAsync(entity);

                var all = await repo.GetAllAsync();

                var customer = all.First();

                toUpdate                = Mapper.Map <CustomerModel>(customer);
                toUpdate.Lastname       = "Updated";
                toUpdate.Address.Street = "AlsoUpdated";

                var updated = Mapper.Map <Customer>(toUpdate);
                await repo.UpdateAsync(updated.Id, updated);
            }

            using (var ctx = CreateContext())
            {
                var repo = new CustomerRepository(ctx);
                var all  = await repo.GetAllAsync();

                var customer = all.First();
                CheckCustomer(customer, toUpdate);
            }
        }
Пример #7
0
        public async Task EnsureSearchOnAllCriteria()
        {
            var model = new CustomerModelBuilder().Default;

            using (var ctx = CreateContext())
            {
                ctx.Customers.RemoveRange(ctx.Customers);
                await ctx.SaveChangesAsync();

                var repo     = new CustomerRepository(ctx);
                var customer = Mapper.Map <Customer>(model);
                await repo.AddAsync(customer);
            }

            await EnsureSearch(model.Lastname);
            await EnsureSearch(model.Firstname);
            await EnsureSearch($"{model.Firstname} {model.Lastname}");
            await EnsureSearch($"{model.Lastname} {model.Firstname}");
            await EnsureSearch(model.VatNumber);
            await EnsureSearch(model.Telephone);
            await EnsureSearch(model.Address.Street);
            await EnsureSearch($"{model.Address.Street} {model.Address.Number}");
            await EnsureSearch(model.Address.PostalCode);
            await EnsureSearch(model.Address.City);
        }
        public async Task WhenWeAskToAddACustomer_ShouldBeAskedToStoreInCosmosDB()
        {
            var newCustomer = DomainGenerator.CustomerGenerator().Generate();

            var updatedCustomer = await _sut.AddAsync(newCustomer);

            await _genericRepo.Received().CreateAsync(Arg.Any <Customer>());
        }
Пример #9
0
        public async Task <IActionResult> Create(CustomerDTO customerDTO)
        {
            Customer customer = new Customer();

            _mapper.Map(customerDTO, customer);

            await customerRepository.AddAsync(customer);

            return(Ok(customer.Id));
        }
Пример #10
0
        public async Task when_adding_new_customer_it_should_be_added_correctly_to_the_db()
        {
            ICustomerRepository _customerRepository = new CustomerRepository(_dbContextConfig.CompanyContext);
            var customer = new Customer("Karol", "Cichon", "+48504400336");

            customer.AddAddress(new CustomerAddress("27", "28", "Krakowska", "Kraków", "31-416"));
            await _customerRepository.AddAsync(customer);

            var existingCustomer = await _customerRepository.GetByPhoneNumberAsync(customer.TelephoneNumber);

            Assert.Equal(customer, existingCustomer);
        }
Пример #11
0
        public async Task added_customer_should_be_removed_correctly_in_the_db()
        {
            ICustomerRepository _customerRepository = new CustomerRepository(_dbContextConfig.CompanyContext);

            var customer = new Customer("Jan", "Kowalski", "+48123456789");

            customer.AddAddress(new CustomerAddress("1", "2", "Krotka", "Kraków", "31-416"));

            await _customerRepository.AddAsync(customer);

            var existingCustomer = await _customerRepository.GetByPhoneNumberAsync(customer.TelephoneNumber);

            await _customerRepository.DeleteAsync(existingCustomer);

            var removedCustomer = await _customerRepository.GetAsync(existingCustomer.Id);

            Assert.Equal(null, removedCustomer);
        }
Пример #12
0
        public async Task GetsExpectedSuitAlterationByCustomerId()
        {
            //Arrange
            var suitAlterationRepository = new SuitAlterationRepository(_dbContext);
            var customerRepository       = new CustomerRepository(_dbContext);

            var expectedCustomer = await RegisterCustomer();

            expectedCustomer.PlaceOrder(5, 5, 5, 5);

            var anotherCustomer = await RegisterCustomer();

            anotherCustomer.PlaceOrder(1, 1, 1, 1);
            await _unitOfWork.CommitAsync(CancellationToken.None);

            var expectedOrder = expectedCustomer.SuitAlterations.Single();
            SuitAlterationDto expectedCustomerSuitAlteration = null;

            _mapperMock.Setup(x => x.Map <SuitAlterationDto>(expectedOrder))
            .Returns((SuitAlteration suitAlteration) =>
            {
                expectedCustomerSuitAlteration = new SuitAlterationDto()
                {
                    Id = suitAlteration.Id.Value
                };
                return(expectedCustomerSuitAlteration);
            });

            //Act
            var customerOrdersQueryHandler = new GetCustomerSuitAlterationsQueryHandler(suitAlterationRepository, _mapperMock.Object);
            IReadOnlyList <SuitAlterationDto> customerSuitAlterations =
                await customerOrdersQueryHandler.Handle(new GetCustomerSuitAlterationsQuery(expectedCustomer.Id.Value), CancellationToken.None);

            //Assert
            customerSuitAlterations.Should().ContainSingle().Which.Id.Should().Be(expectedCustomerSuitAlteration.Id);

            async Task <Customer> RegisterCustomer()
            {
                var customer = CreateNewCustomer();
                await customerRepository.AddAsync(customer);

                return(customer);
            }
        }
Пример #13
0
        public async Task EnsureCustomerCreated()
        {
            var model = new CustomerModelBuilder().Default;

            using (var ctx = CreateContext())
            {
                var repo     = new CustomerRepository(ctx);
                var customer = Mapper.Map <Customer>(model);
                await repo.AddAsync(customer);
            }

            using (var ctx = CreateContext())
            {
                var repo = new CustomerRepository(ctx);
                var all  = await repo.GetAllAsync();

                var customer = all.First();
                CheckCustomer(customer, model);
            }
        }
Пример #14
0
        public async Task SuccessfullyPlacesCustomerOrderForNewSuitAlteration()
        {
            //Arrange
            var customerRepository = new CustomerRepository(_dbContext);
            var customer           = CreateNewCustomer();
            await customerRepository.AddAsync(customer);

            await _unitOfWork.CommitAsync(CancellationToken.None);

            var suitAlterationRepository = new SuitAlterationRepository(_dbContext);
            var customerOrders           = await LoadCustomerOrders();

            //Pre-assert
            customerOrders.Should().BeEmpty();

            //Act
            var placeCustomerOrderCommandHandler = new PlaceCustomerOrderCommandHandler(customerRepository);
            await placeCustomerOrderCommandHandler.Handle(new PlaceCustomerOrderCommand(5,
                                                                                        5,
                                                                                        5,
                                                                                        5,
                                                                                        customer.Id.Value), CancellationToken.None);

            await _unitOfWork.CommitAsync(CancellationToken.None);

            //Assert
            customerOrders = await LoadCustomerOrders();

            customerOrders.Should().ContainSingle();
            var createdOrder = customerOrders.Single();

            createdOrder.DomainEvents.Should().ContainSingle().And.BeEquivalentTo(new OrderPlacedDomainEvent(createdOrder.Id));
            createdOrder.Status.Should().Be(SuitAlterationStatus.Created);
            customer.SuitAlterations.Should().Contain(createdOrder);

            async Task <IReadOnlyList <SuitAlteration> > LoadCustomerOrders()
            {
                return(await suitAlterationRepository.GetByCustomerIdAsync(customer.Id));
            }
        }
        public async Task InitDemoDataAsync()
        {
            var brands = await BrandRepository.GetAllAsync();

            if (brands.Any())
            {
                return; // already initialized
            }
            var brandA = new CarBrand
            {
                Title = "Audi"
            };

            var brandB = new CarBrand
            {
                Title = "BMW"
            };

            var brandC = new CarBrand
            {
                Title = "Fiat"
            };

            brandA = await BrandRepository.AddAsync(brandA);

            brandB = await BrandRepository.AddAsync(brandB);

            brandC = await BrandRepository.AddAsync(brandC);

            var classA = new CarClass
            {
                Title = "Cheap",
                Cost  = 102.20M
            };

            var classB = new CarClass
            {
                Title = "Midlevel",
                Cost  = 180.50M
            };

            var classC = new CarClass
            {
                Title = "Highend",
                Cost  = 250.99M
            };

            classA = await ClassRepository.AddAsync(classA);

            classB = await ClassRepository.AddAsync(classB);

            classC = await ClassRepository.AddAsync(classC);

            var typeA = new CarType
            {
                Title = "PKW"
            };

            var typeB = new CarType
            {
                Title = "Limousine"
            };

            var typeC = new CarType
            {
                Title = "Coupé"
            };

            typeA = await TypeRepository.AddAsync(typeA);

            typeB = await TypeRepository.AddAsync(typeB);

            typeC = await TypeRepository.AddAsync(typeC);

            var customerA = new Customer
            {
                FirstName   = "Peter",
                LastName    = "Müller",
                Address     = "Mordorweg 4, 8355 Gondor",
                EMail       = "*****@*****.**",
                PhoneNumber = "79 546 65 65"
            };

            var customerB = new Customer
            {
                FirstName   = "Maria",
                LastName    = "Meier",
                Address     = "Rohangasse 23, 5564 Auenland",
                EMail       = "*****@*****.**",
                PhoneNumber = "76 215 54 64"
            };

            var customerC = new Customer
            {
                FirstName   = "Bruno",
                LastName    = "Gander",
                Address     = "Isengardweg 3, 5445 Helmsklamm",
                EMail       = "*****@*****.**",
                PhoneNumber = "76 651 12 35"
            };

            customerA = await CustomerRepository.AddAsync(customerA);

            customerB = await CustomerRepository.AddAsync(customerB);

            customerC = await CustomerRepository.AddAsync(customerC);

            var carA = new Car
            {
                BrandId          = brandA.Id,
                ClassId          = classA.Id,
                HorsePower       = 112,
                Kilometers       = 216535,
                RegistrationYear = 2000,
                TypeId           = typeA.Id
            };

            var carB = new Car
            {
                BrandId          = brandB.Id,
                ClassId          = classB.Id,
                HorsePower       = 212,
                Kilometers       = 116535,
                RegistrationYear = 2010,
                TypeId           = typeB.Id
            };

            var carC = new Car
            {
                BrandId          = brandC.Id,
                ClassId          = classC.Id,
                HorsePower       = 312,
                Kilometers       = 16535,
                RegistrationYear = 2018,
                TypeId           = typeC.Id
            };

            carA = await CarRepository.AddAsync(carA);

            carB = await CarRepository.AddAsync(carB);

            carC = await CarRepository.AddAsync(carC);

            var reservationA = new Reservation
            {
                CarId           = carA.Id,
                CustomerId      = customerA.Id,
                Days            = 12,
                RentalDate      = DateTime.Now.AddDays(12),
                ReservationDate = DateTime.Now,
                State           = ReservationState.Pending
            };

            var reservationB = new Reservation
            {
                CustomerId      = customerB.Id,
                CarId           = carB.Id,
                Days            = 2,
                RentalDate      = DateTime.Now.AddDays(1),
                ReservationDate = DateTime.Now.AddDays(-3),
                State           = ReservationState.Reserved
            };

            var reservationC = new Reservation
            {
                CustomerId      = customerC.Id,
                CarId           = carC.Id,
                Days            = 42,
                RentalDate      = DateTime.Now.AddDays(-2),
                ReservationDate = DateTime.Now.AddDays(-8),
                State           = ReservationState.Contracted
            };

            await ReservationRepository.AddAsync(reservationA);

            await ReservationRepository.AddAsync(reservationB);

            reservationC = await ReservationRepository.AddAsync(reservationC);

            var contractA = new RentalContract
            {
                CarId         = carC.Id,
                CustomerId    = customerC.Id,
                Days          = 42,
                RentalDate    = DateTime.Now.AddDays(-2),
                ReservationId = reservationC.Id,
                TotalCosts    = classC.Cost * 42
            };

            await ContractRepository.AddAsync(contractA);
        }
Пример #16
0
        public async Task CustomerRepositoryAsyncAllMethodTest()
        {
            // DbContextOptions<T> Object Creation
            var options = new DbContextOptionsBuilder <DotNetSaleCoreDbContext>()
                          .UseInMemoryDatabase(databaseName: $"DotNetSaleCore{Guid.NewGuid()}").Options;
            //.UseSqlServer("server=(localdb)\\mssqllocaldb;database=DotNetSaleCore;integrated security=true;").Options;

            // ILoggerFactory Object Creation
            var serviceProvider = new ServiceCollection().AddLogging().BuildServiceProvider();
            var factory         = serviceProvider.GetService <ILoggerFactory>();

            //[1] AddAsync() Method Test
            using (var context = new DotNetSaleCoreDbContext(options))
            {
                // Repository Object Creation
                //[!] Arrange
                var repository = new CustomerRepository(context, factory);
                var model      = new Customer {
                    CustomerName = "[1] 고객이름", Created = DateTime.Now
                };

                //[!] Act
                await repository.AddAsync(model);

                await context.SaveChangesAsync();
            }
            using (var context = new DotNetSaleCoreDbContext(options))
            {
                //[!] Assert
                Assert.AreEqual(1, await context.Customers.CountAsync());
                var model = await context.Customers.Where(m => m.CustomerId == 1).SingleOrDefaultAsync();

                Assert.AreEqual("[1] 고객이름", model?.CustomerName);
            }

            //[2] GetAllAsync() Method Test
            using (var context = new DotNetSaleCoreDbContext(options))
            {
                //// 트랜잭션 관련 코드는 InMemoryDatabase 공급자에서는 지원 X
                ////using (var transaction = context.Database.BeginTransaction()) { transaction.Commit(); }
                var repository = new CustomerRepository(context, factory);
                var model      = new Customer {
                    CustomerName = "[2] 홍길동", Created = DateTime.Now
                };
                await context.Customers.AddAsync(model);

                await context.SaveChangesAsync(); //[1]

                await context.Customers.AddAsync(new Customer { CustomerName = "[3] 백두산", Created = DateTime.Now });

                await context.SaveChangesAsync(); //[2]
            }
            using (var context = new DotNetSaleCoreDbContext(options))
            {
                var repository = new CustomerRepository(context, factory);
                var models     = await repository.GetAllAsync();

                Assert.AreEqual(3, models.Count);
            }

            //[3] GetByIdAsync() Method Test
            using (var context = new DotNetSaleCoreDbContext(options))
            {
                // Empty
            }
            using (var context = new DotNetSaleCoreDbContext(options))
            {
                var repository = new CustomerRepository(context, factory);
                var model      = await repository.GetByIdAsync(2);

                Assert.IsTrue(model.CustomerName.Contains("길동"));
                Assert.AreEqual("[2] 홍길동", model.CustomerName);
            }

            //[4] GetEditAsync() Method Test
            using (var context = new DotNetSaleCoreDbContext(options))
            {
                // Empty
            }
            using (var context = new DotNetSaleCoreDbContext(options))
            {
                var repository = new CustomerRepository(context, factory);
                var model      = await repository.GetByIdAsync(2);

                model.CustomerName = "[2] 임꺽정";
                await repository.EditAsync(model);

                await context.SaveChangesAsync();

                Assert.AreEqual("[2] 임꺽정",
                                (await context.Customers.Where(m => m.CustomerId == 2).SingleOrDefaultAsync()).CustomerName);
            }

            //[5] GetDeleteAsync() Method Test
            using (var context = new DotNetSaleCoreDbContext(options))
            {
                // Empty
            }
            using (var context = new DotNetSaleCoreDbContext(options))
            {
                var repository = new CustomerRepository(context, factory);
                await repository.DeleteAsync(2);

                await context.SaveChangesAsync();

                Assert.AreEqual(2, await context.Customers.CountAsync());
                Assert.IsNull(await repository.GetByIdAsync(2));
            }

            //[6] PagingAsync() Method Test
            using (var context = new DotNetSaleCoreDbContext(options))
            {
                // Empty
            }
            using (var context = new DotNetSaleCoreDbContext(options))
            {
                int pageIndex = 0;
                int pageSize  = 1;

                var repository = new CustomerRepository(context, factory);
                var models     = await repository.GetAllAsync(pageIndex, pageSize);

                Assert.AreEqual("[3] 백두산", models.Records.FirstOrDefault().CustomerName);
                Assert.AreEqual(2, models.TotalRecords);
            }
        }