コード例 #1
0
ファイル: ApiCrudTest.cs プロジェクト: zzekikaya/InGame
        public async Task InsertProductWithApi()
        {
            var bodyString = @"{Email: ""*****@*****.**"", Password: ""Pass@word1""}";
            var response   = _client.PostAsync("/api/Token",
                                               new StringContent(bodyString, Encoding.UTF8, "application/json")).Result;

            Assert.Equal(HttpStatusCode.OK, response.StatusCode);

            var token = await response.Content.ReadAsStringAsync();

            Assert.NotNull(token);

            // Arrange
            var request = new Product
            {
                Name        = "silah",
                Price       = 3000,
                Description = "ucuz item"
            };

            var productService = new ProductService(_mockProductRepo.Object, null);

            await productService.AddAsync(request);

            _mockProductRepo.Verify(x => x.AddAsync(request), Times.Once);
        }
コード例 #2
0
        public async Task <IActionResult> Post([FromForm] IEnumerable <IFormFile> pictures)
        {
            ProductAddCommand command = null;

            try
            {
                command = JsonConvert.DeserializeObject <ProductAddCommand>(Request.Form["Product"].ToString());

                command.Pictures = await UploadProductFiles(pictures, null);

                return(Ok
                       (
                           await service.AddAsync(command, GetPathTemplate(Request))
                       ));
            }
            catch (DuplicateWaitObjectException ex)
            {
                DeleteProductFiles(command.Pictures?.Select(x => new FileInfoDto(GetPathTemplate(Request), x.Key, x.Value)));
                return(Conflict(ex.Message));
            }
            catch (HttpRequestException ex)
            {
                return(StatusCode(StatusCodes.Status503ServiceUnavailable, ex.Message));
                //return BadRequest(ex.Message);
            }
            catch (Exception ex)
            {
                DeleteProductFiles(command.Pictures?.Select(x => new FileInfoDto(GetPathTemplate(Request), x.Key, x.Value)));
                System.Diagnostics.Debug.Print(ex.ToString());
                return(BadRequest(Error));
            }
        }
コード例 #3
0
        public async Task Should_Add_Product_Async()
        {
            //Arrange
            Product product = new Product()
            {
                Name        = "Test Name",
                Description = "Test Name Description",
                Price       = 100
            };

            //Act
            var result = await _productService.AddAsync(product);

            //Assert
            Assert.NotNull(result);
        }
コード例 #4
0
        public async void AddAsync_ShouldAddProductCorrectly()
        {
            var            context = DbContextHelper.GetContextWithData();
            ProductService service = new ProductService(context);

            int allProductsCount = context.Products.Count();

            Category         category = context.Categories.FirstOrDefault();
            ProductViewModel model    = new ProductViewModel()
            {
                AvailableQuantity = 10,
                Category          = category.Id,
                Description       = "some description",
                ImageFileName     = null,
                Price             = 40,
                RentPrice         = null,
                Title             = "title"
            };

            await service.AddAsync(model);

            var allProducts = await service.GetAllAsync();

            Assert.Equal(allProductsCount + 1, allProducts.Count());

            var addedProduct = context.Products.FirstOrDefault(p => p.Title == model.Title);

            Assert.NotNull(addedProduct);
        }
コード例 #5
0
        public async Task AddAsync()
        {
            // Arrange
            var productEntity = new ProductEntity()
            {
                Description = "Description", Name = "Name"
            };
            var product = new Product()
            {
                Description = "Description1", Name = "Name1"
            };

            var repositoryMock = new Mock <IGenericRepository <ProductEntity> >();

            repositoryMock.Setup(x => x.AddAsync(productEntity)).ReturnsAsync(productEntity);

            var mapperMock = new Mock <IMapper>();

            mapperMock.Setup(m => m.Map <ProductEntity, Product>(It.IsAny <ProductEntity>())).Returns(product);

            var service = new ProductService(repositoryMock.Object, mapperMock.Object);

            // Act
            var result = await service.AddAsync(product);

            // Assert
            Assert.IsNotNull(result);
            Assert.AreEqual(result.Description, product.Description);
        }
コード例 #6
0
        public async Task AddAsync_AddsItemToDatabase()
        {
            var numberOfItemsInDatabase = await _context.Products.CountAsync();

            await _service.AddAsync(new ProductDto { Name = "Testie" });

            _context.Products.CountAsync().Result.Should().Be(numberOfItemsInDatabase + 1);
            _validator.VerifyAll();
        }
コード例 #7
0
        public void AddByName_InsertsNewProduct_CallsMethod_AddOfRepository()
        {
            mockProductRepository.Setup(repo => repo.SelectWhereAsync(It.IsAny <Predicate <ProductDB> >()))
            .Returns(Task.FromResult((IEnumerable <ProductDB>)selectedList));

            using (var productService = new ProductService(mockProductRepository.Object, mockCategoryRepository.Object, mockBarcodeService.Object, mapper))
            {
                productService.AddAsync(product.Name);

                mockProductRepository.Verify(m => m.AddAsync(It.IsAny <ProductDB>()), Times.Once);
            }
        }
コード例 #8
0
ファイル: ProductTest.cs プロジェクト: zzekikaya/InGame
        public async Task Insert_Product_Test()
        {
            var product = new Product()
            {
                Name        = "silah",
                Description = "ücretsiz",
                Price       = 5000
                              //,SubCategoryID = 1
            };
            var productService = new ProductService(_mockProductRepo.Object, null);

            await productService.AddAsync(product);

            _mockProductRepo.Verify(x => x.AddAsync(product));
        }
コード例 #9
0
        public async Task <ActionResult <Product> > Post(
            [FromBody] Product product)
        {
            if (ModelState.IsValid)
            {
                product.Offer = await _offerService.FindByIdAsync(product.OfferId);

                await _productService.AddAsync(product);

                return(product);
            }
            else
            {
                return(BadRequest(ModelState));
            }
        }
コード例 #10
0
        public async Task AddAsync_ShouldAddNewProduct()
        {
            // Arrange
            var product = _fixture.Build <Product>()
                          .Create();

            // Act
            var id = await _sut.AddAsync(product.Name, product.Calories, product.Proteins,
                                         product.Carbohydrates, product.Fats, product.CategoryOfProduct.Name.ToString());

            // Assert
            await _productRepository.Received(1).AddAsync(Arg.Is <Product>(p =>
                                                                           p.Id == id &&
                                                                           p.Name == product.Name &&
                                                                           p.Proteins == product.Proteins &&
                                                                           p.Carbohydrates == product.Carbohydrates &&
                                                                           p.Fats == product.Fats));
        }
コード例 #11
0
        public async Task <IActionResult> Create(Product product, int categoryId)
        {
            product.Category = await _categoryService.FindAsync(categoryId);

            if (product.Category == null)
            {
                ModelState.AddModelError("Category", "Category is not found");
            }

            if (ModelState.IsValid)
            {
                await _productService.AddAsync(product);

                return(RedirectToAction(nameof(Index)));
            }

            ViewBag.Categories = await GetCategoriesSelectList();

            return(View(product));
        }
コード例 #12
0
        public async Task AddTestAsync()
        {
            var product = new Product
            {
                Id          = 2,
                Name        = "Product add",
                Description = "Description add",
                Category    = new Category
                {
                    Id = 7
                }
            };

            var result = await _mockService.AddAsync(product);

            Assert.NotNull(result);
            Assert.IsAssignableFrom <Product>(result);
            Assert.Equal(2, result.Id);
            Assert.IsType <string>(result.Description);
        }
コード例 #13
0
        // POST: odata/Products1
        public async Task <IHttpActionResult> Post(ProductResponseDto product)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }
            if (product == null)
            {
                return(BadRequest("Product is required"));
            }
            await productServices.AddAsync(new AddProductDto
            {
                Name        = product.Name,
                Description = product.Description,
                Price       = product.Price,
                CategoryId  = product.Category?.Id ?? 0
            });

            UOW.Commit();
            return(Created(product));
        }
コード例 #14
0
        public async Task AddAsync()
        {
            var options = new DbContextOptionsBuilder <ApplicationDbContext>()
                          .UseInMemoryDatabase(Guid.NewGuid().ToString())
                          .Options;
            IOptions <OperationalStoreOptions> someOptions = Options.Create(new OperationalStoreOptions());


            using (var context = new ApplicationDbContext(options, someOptions))
            {
                var products = new[]
                {
                    new Product()
                    {
                        Id = 1, Name = "first", Category = new Category {
                            Id = 1
                        }
                    },
                    new Product()
                    {
                        Id = 2, Name = "second"
                    },
                };

                context.Products.AddRange(products);
                context.SaveChanges();

                var productService = new ProductService(context);
                await productService.AddAsync(new Product()
                {
                    Id = 3, Name = "third"
                });

                Assert.AreEqual(
                    3,
                    (await productService.FindAsync(3)).Id
                    );
            }
        }
コード例 #15
0
        public async Task <IActionResult> AddProduct(ProductViewModel product, CancellationToken cancellationToken)
        {
            await _productService.AddAsync(new Product { Tittle = product.Name, Price = product.Price }, cancellationToken);

            return(Ok());
        }
コード例 #16
0
        public void TestProductCreateAndUpdate()
        {
            RunTestWithDbContext(async context =>
            {
                var i18NService     = new I18nService(context, new HttpContextAccessor(), Mock.Of <ILogger <I18nService> >());
                var imageService    = new ImageService(context, Mock.Of <ILogger <ImageService> >());
                var wishlistService = new WishlistService(context, Mock.Of <ILogger <WishlistService> >());
                var categoryService = new CategoryService(context, Mock.Of <ILogger <CategoryService> >());
                var productService  = new ProductService(context, i18NService,
                                                         Mock.Of <ILogger <ProductService> >(), imageService, wishlistService);

                // Add a category which is necessary for the product creation
                var category = new CategoryEntity
                {
                    Title = "Hard Rock"
                };

                await categoryService.AddAsync(category);

                Assert.Empty(await productService.GetAllAsync());

                // Create product
                var product = new ProductEntity
                {
                    Artist      = "Artist",
                    CategoryId  = category.Id,
                    Label       = "test",
                    ReleaseDate = DateTime.Today,
                    Image       = new ImageEntity
                    {
                        Base64String = "asf23523sdfk",
                        Description  = "Hard Rock image",
                        ImageType    = "jpg"
                    }
                };

                // Create product prices
                var productPriceEntities = new List <ProductPriceEntity>
                {
                    new ProductPriceEntity
                    {
                        CurrencyId = "EUR",
                        Price      = 9,
                        ProductId  = product.Id
                    },
                    new ProductPriceEntity
                    {
                        CurrencyId = "USD",
                        Price      = 20,
                        ProductId  = product.Id
                    }
                };

                // Create product translations
                var productTranslationEntities = new List <ProductTranslationEntity>
                {
                    new ProductTranslationEntity
                    {
                        Description      = "Deutsche Beschreibung",
                        DescriptionShort = "kurz",
                        LanguageId       = "de_DE",
                        ProductId        = product.Id,
                        Title            = "Deutsches Produkt"
                    },
                    new ProductTranslationEntity
                    {
                        Description      = "English Description",
                        DescriptionShort = "short",
                        LanguageId       = "en_US",
                        ProductId        = product.Id,
                        Title            = "English Product"
                    }
                };

                await productService.AddAsync(product, productPriceEntities, productTranslationEntities);

                //Test Products
                Assert.NotNull(await productService.GetByIdAsync(product.Id));
                Assert.Null(await productService.GetByIdAsync(new Guid()));
                Assert.Single(productService.GetAllAsync().Result);
                Assert.True(await productService.DoesProductExistByIdAsync(product.Id));

                Assert.NotNull(await imageService.GetByIdAsync(product.ImageId));
                Assert.True(categoryService.DoesCategoryNameExist(category.Title));
                Assert.Single(categoryService.GetAllAsync().Result);

                // Add a second category
                var secondCategory = new CategoryEntity
                {
                    Title = "Rock"
                };

                await categoryService.AddAsync(secondCategory);

                var updatedProduct        = product;
                updatedProduct.Id         = product.Id;
                updatedProduct.CategoryId = secondCategory.Id;
                await productService.UpdateAsync(updatedProduct);

                //Test Updated Product
                Assert.NotNull(await productService.GetByIdAsync(updatedProduct.Id));
                Assert.Null(await productService.GetByIdAsync(new Guid()));
                Assert.Single(productService.GetAllAsync().Result);
                Assert.True(await productService.DoesProductExistByIdAsync(updatedProduct.Id));

                Assert.True(categoryService.DoesCategoryNameExist(secondCategory.Title));
                Assert.Equal(2, categoryService.GetAllAsync().Result.Count);
                Assert.Equal("Rock", productService.GetByIdAsync(updatedProduct.Id).Result.Category.Title);
            });
        }
コード例 #17
0
        public async void Post(AddProductDto dto)
        {
            await service.AddAsync(dto);

            uow.Commit();
        }