Пример #1
0
 public void TestSetup()
 {
     controller = new ProductsController();
     controller.Task = new MainTask();
     controller.Task.Navigator = new StubNavigator();
     controller.Task.Navigator.Task = controller.Task;
 }
Пример #2
0
        public void AddToControllerHttpRequestWithHttpMethod()
        {
            var httpMethod = "httpMethod";
            var controller = new ProductsController ();

            var controllerResult = new Builder ()
                .WithHttpMethod (httpMethod)
                .AddTo (controller);

            controllerResult.Request.HttpMethod.Should ().Be (httpMethod);
        }
        public void PutProduct_ShouldFail_WhenDifferentID()
        {
            // arrange
            var controller = new ProductsController(new TestStoreAppContext());

            // act
            var badresult = controller.PutProduct(999, this.GetDemoProduct());

            // assert
            Assert.IsType(typeof(BadRequestResult), badresult);
        }
Пример #4
0
        public void AddToControllerHttpRequestWithContentType()
        {
            var contentType = "Content-Type";
            var controller = new ProductsController ();

            var controllerResult = new Builder ()
                .WithContentType (contentType)
                .AddTo (controller);

            controllerResult.Request.ContentType.Should ().Be (contentType);
        }
Пример #5
0
        public void AddToControllerHttpRequestWithHeader()
        {
            var header = "header";
            var headerValue = "headerValue";
            var controller = new ProductsController ();

            var controllerResult = new Builder ()
                .WithHeader (header, headerValue)
                .AddTo (controller);

            controllerResult.Request.Headers [header].Should ().Be (headerValue);
        }
        public void PostProduct_ShouldReturnSameProduct()
        {
            // arrange
            var controller = new ProductsController(new TestStoreAppContext());
            var item = this.GetDemoProduct();

            // act
            var result = controller.PostProduct(item) as CreatedAtRouteNegotiatedContentResult<Product>;

            // assert
            Assert.Equal(result.RouteName, "DefaultApi");
            Assert.Equal(result.RouteValues["id"], item.Id);
            Assert.Equal(result.Content.Name, item.Name);
        }
        public void GetProduct_ShouldReturnProductWithSameID()
        {
            // arrange
            var context = new TestStoreAppContext();
            context.Products.Add(this.GetDemoProduct());

            var controller = new ProductsController(context);

            // act
            var result = controller.GetProduct(3) as OkNegotiatedContentResult<Product>;

            // assert
            Assert.Equal(3, result.Content.Id);
        }
        public void DeleteProduct_ShouldReturnOK()
        {
            // arrange
            var context = new TestStoreAppContext();
            var item = this.GetDemoProduct();
            context.Products.Add(item);

            var controller = new ProductsController(context);

            // act
            var result = controller.DeleteProduct(3) as OkNegotiatedContentResult<Product>;

            // assert
            Assert.Equal(item.Id, result.Content.Id);
        }
        public void GetProducts_ShouldReturnAllProducts()
        {
            // arrange
            var context = new TestStoreAppContext();
            context.Products.Add(new Product { Id = 1, Name = "Demo1", Price = 20 });
            context.Products.Add(new Product { Id = 2, Name = "Demo2", Price = 30 });
            context.Products.Add(new Product { Id = 3, Name = "Demo3", Price = 40 });
            var controller = new ProductsController(context);

            // act
            var result = controller.GetProducts() as TestProductDbSet;

            // assert
            Assert.Equal(3, result.Local.Count);
        }
        public void PutProductTest()
        {
            Guid       productId = Guid.NewGuid();
            ProductDto product   = new ProductDto {
                Id = productId, Name = "Samsung Galaxy", Description = "mobile", Price = 199.99M, DeliveryPrice = 11.11M
            };
            var productsService = new Mock <IProductsService>();

            productsService
            .Setup(repo => repo.UpdateProduct(new ProductDoDtoConverter().ToDO(product)));
            ProductsController productsController = new ProductsController(productsService.Object, Mock.Of <ILogger <ProductsController> >());

            ActionResult result = productsController.PutProduct(productId, product);

            Assert.IsNotNull(result);
            Assert.IsInstanceOfType(result, typeof(NoContentResult));
        }
        public async Task Put()
        {
            // Arrange
            ProductsController controller = new ProductsController();
            Product            p          = new Product {
                ProductId = new Guid("7F80C7E9-FC41-4FB2-87FB-099081182FBC"), Price = 34.00M, ProductName = "TestProduct"
            };


            IHttpActionResult res = await controller.PutProduct(new Guid("7F80C7E9-FC41-4FB2-87FB-099081182FBC"), p);

            Assert.IsNotNull(res);



            // Assert
        }
Пример #12
0
        public async Task TestPatchtProductAsync()
        {
            //Arange
            var dbContext = DbContextMocker.GetProductContext(nameof(TestPatchtProductAsync));
            ProductsController controller  = new ProductsController(dbContext);
            ProductDescription description = new ProductDescription()
            {
                Description = "UnitTest"
            };

            //Act
            var response = await controller.PatchProductAsync(1, description);

            //Assert
            dbContext.Dispose();
            Assert.True(response is NoContentResult);
        }
Пример #13
0
        public void CreateGood()
        {
            var     obj = new ProductsController();
            Product aux = new Product();

            aux.ProductName = "Test CreateController";
            aux.Stock       = 5;
            aux.UnitPrice   = 10.0M;
            aux.Estado      = true;
            aux.Perecible   = true;
            aux.DueDate     = DateTime.Parse("2003-09-01");
            aux.Description = "Test Description";

            var actResult = obj.Create(aux) as RedirectToRouteResult;

            Assert.AreEqual("Index", actResult.RouteValues["action"]);
        }
        public void Delete_Product_Returns_NoContentStatusCode()
        {
            // Arrange
            mockProductService.Setup(c => c.Delete(It.IsAny <Product>()));
            ProductsController controller = new ProductsController(mockProductService.Object)
            {
                Request = new HttpRequestMessage()
                {
                    Properties = { { HttpPropertyKeys.HttpConfigurationKey, new HttpConfiguration() } }
                }
            };
            // Act
            var response = controller.Delete(_productId1);

            // Assert
            Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);
        }
Пример #15
0
        public void Post()
        {
            // Arrange
            ProductsController controller = new ProductsController();
            string             uniqueName = new Random().Next(int.MinValue, int.MaxValue).ToString();

            Product newProduct = new Product {
                Name = "TEST - " + uniqueName, ProductNumber = uniqueName, StandardCost = 1, ListPrice = 9, SellStartDate = DateTime.UtcNow, rowguid = Guid.NewGuid(), ModifiedDate = DateTime.UtcNow
            };

            // Act
            IHttpActionResult result = controller.Post(newProduct);

            System.Web.Http.OData.Results.CreatedODataResult <Product> odataResult = (System.Web.Http.OData.Results.CreatedODataResult <Product>)result;
            _productID = odataResult.Entity.ProductID;
            // Assert
        }
Пример #16
0
        public void Delete_BadRequest()
        {
            // Prepare the mock
            var mockRepository = new Mock <IProduct>();

            mockRepository.Setup(x => x.DeleteProduct(1))
            .Throws(new System.Exception());
            var controller = new ProductsController(mockRepository.Object);

            // Make the request
            var response = controller.Delete(1) as ObjectResult;

            // Validate the response
            Assert.Equal((int)HttpStatusCode.BadRequest, response.StatusCode);
            Assert.NotNull(response);
            Assert.NotNull(response.Value);
        }
Пример #17
0
        public async Task PagingRecordsTest()
        {
            // Arrange
            const int          pageSize = 6;
            IProductRepository mockRepo = new MockProductRepository();

            var mockDownloadTimesApi = Substitute.For <IDownloadTimesApi>();
            var mockProductTypesApi  = Substitute.For <IProductTypesApi>();
            var mockManufacturersApi = Substitute.For <IManufacturersApi>();
            var mockInstallTypesApi  = Substitute.For <IInstallTypesApi>();
            var mockMobileLookupApi  = Substitute.For <IMobileLookupApi>();
            var mockBrandApi         = Substitute.For <IBrandApi>();

            IDistributedCache   mockCache   = Substitute.For <IDistributedCache>();
            IOptions <Settings> appSettings = Substitute.For <IOptions <Settings> >();

            IStringLocalizer <ProductsController> mockLocalizer = new MockStringLocalizer <ProductsController>();

            IProductApi productApi = new ProductApi(appSettings, mockRepo);
            var         controller = new ProductsController(mockCache,
                                                            productApi,
                                                            mockDownloadTimesApi,
                                                            mockProductTypesApi,
                                                            mockManufacturersApi,
                                                            mockInstallTypesApi,
                                                            mockMobileLookupApi,
                                                            mockBrandApi,
                                                            mockLocalizer);

            var request = new GetProductsWithPagingRequestModel
            {
                FirstRecordNumber = 0,
                PageSize          = pageSize,
                SortField         = string.Empty,
                SortOrder         = SortOrderEnum.Asc
            };


            //// Act
            var actionResult = await controller.GetProductsWithPaging(request);

            //// Assert
            var actualRecord = ((ObjectResult)actionResult).Value;

            Assert.Equal(pageSize, ((List <ProductModel>)actualRecord).Count);
        }
Пример #18
0
        [Fact] // test methods without any parameters
        public async Task GetProducts()
        {
            // creates a new context
            var context = MockContext.GetContext("test1");

            // adds the mockdata to the context
            context.Seed();
            var controller = new ProductsController(_userManager, _signInManager, context);

            string[] arr      = new String[0];
            var      response = controller.Index("", arr, arr, arr, arr);
            var      result   = response.Result;

            // assert verifies the condition
            // IsAssignableFrom checks if the products .. are assigned
            Assert.IsAssignableFrom <ViewResult>(result);
        }
Пример #19
0
        public void TestEditMethod()
        {
            Products products = new Products {
                ProductId = 1, ProductName = "Harry Porter", Price = 10
            };

            //Mock IRepository of products
            Mock <IRepository <Products> > mockProductsController = new Mock <IRepository <Products> >();

            mockProductsController.Setup(b => b.Update(It.IsAny <Products>())).Callback <Products>(s => products = s);

            //Pass in the IRepository products
            ProductsController productsController = new ProductsController(mockProductsController.Object);
            var result = productsController.Edit(products) as RedirectToRouteResult;

            Assert.AreEqual(result.RouteValues["action"], "Index");
        }
Пример #20
0
        public void TestDetailsMethod()
        {
            Products product = new Products {
                ProductId = 1, ProductName = "Harry Porter", Price = 10
            };

            //Mock IRepository of products
            Mock <IRepository <Products> > mockProductsController = new Mock <IRepository <Products> >();

            mockProductsController.Setup(b => b.GetByID(It.IsAny <int>())).Returns(product);

            //Pass in the IRepository products
            ProductsController productsController = new ProductsController(mockProductsController.Object);
            ViewResult         result             = productsController.Details(1) as ViewResult;

            Assert.AreEqual(product, result.Model);
        }
Пример #21
0
        public void TestDeleteConfirmedMethod()
        {
            Products products = new Products {
                ProductId = 1, ProductName = "Harry Porter", Price = 10
            };

            //Mock IRepository of products
            Mock <IRepository <Products> > mockProductsController = new Mock <IRepository <Products> >();

            mockProductsController.Setup(b => b.Delete(It.IsAny <int>()));

            //Pass in the IRepository products
            ProductsController productsController = new ProductsController(mockProductsController.Object);
            var result = productsController.DeleteConfirmed(1) as RedirectToRouteResult;

            Assert.AreEqual(result.RouteValues["action"], "Index");
        }
Пример #22
0
        public async Task Delete_Success()
        {
            // Arrange
            var loggerController = Loggers.ProductControllerLogger();
            var loggerRepository = Loggers.ProductRepositoryLogger();

            var mapper = Mapper.Get();

            var dbContext = _fixture.Context;

            var category = NewDatas.NewCategory();
            await dbContext.Categories.AddRangeAsync(category);

            await dbContext.SaveChangesAsync();

            var product = NewDatas.NewProduct();

            product.CategoryId = category.CategoryId;
            await dbContext.Products.AddAsync(product);

            await dbContext.SaveChangesAsync();

            var productRepository = new ProductRepository(loggerRepository, mapper, dbContext);
            var productController = new ProductsController(loggerController, productRepository);

            // Act
            var result = await productController.RemoveProduct(product.ProductId);

            // Assert
            var deletedResult      = Assert.IsType <OkObjectResult>(result.Result);
            var deletedResultValue = Assert.IsType <ProductRespone>(deletedResult.Value);

            Assert.Equal(product.Name, deletedResultValue.Name);
            Assert.Equal(product.Price, deletedResultValue.Price);
            Assert.Equal(product.Description, deletedResultValue.Description);
            Assert.Equal(product.Image, deletedResultValue.Image);
            Assert.Equal(product.Rated, deletedResultValue.Rated);
            Assert.Equal(category.CategoryId, deletedResultValue.CategoryId);
            Assert.Equal(category.Name, deletedResultValue.CategoryName);

            await Assert.ThrowsAsync <NotFoundException>(async() =>
            {
                await productController.GetProduct(deletedResultValue.ProductId);
            });
        }
Пример #23
0
        public void GetAllCategories_CategoryIdList_ReturnSameIds()
        {
            ProductsController productController = new ProductsController();
            var             mockDbconnection     = new Mock <Models.ApplicationDbContext>();
            List <Category> categories           = new List <Category>
            {
                new Category
                {
                    CategoryId = 1,
                    Title      = "1"
                },
                new Category
                {
                    CategoryId = 2,
                    Title      = "2"
                },
                new Category
                {
                    CategoryId = 3,
                    Title      = "3"
                }
            };
            IQueryable <Category> queryableCats = categories.AsQueryable();

            var mockCategories = new Mock <DbSet <Category> >();

            mockCategories.As <IQueryable <Category> >().Setup(m => m.Provider).Returns(queryableCats.Provider);
            mockCategories.As <IQueryable <Category> >().Setup(m => m.Expression).Returns(queryableCats.Expression);
            mockCategories.As <IQueryable <Category> >().Setup(m => m.ElementType).Returns(queryableCats.ElementType);
            mockCategories.As <IQueryable <Category> >().Setup(m => m.GetEnumerator()).Returns(queryableCats.GetEnumerator());

            mockDbconnection.Setup(d => d.Categories).Returns(mockCategories.Object);

            var mockContext = new Mock <ControllerContext>();

            productController.ControllerContext = mockContext.Object;
            PrivateObject po = new PrivateObject(productController);

            po.SetField("db", mockDbconnection.Object);
            List <string> categoryIds = categories.Select(c => c.CategoryId.ToString()).ToList();

            List <string> result = productController.GetAllCategories().OrderBy(s => s.Value).Select(s => s.Value).ToList();

            Assert.AreEqual(String.Concat(result), String.Concat(categoryIds));
        }
Пример #24
0
        public async Task ProductsController_Put_Success()
        {
            var createRequest = new ProductCreateRequest
            {
                Name        = "Test product5",
                Price       = 123,
                Description = "product5",
                ImageUrl    = "http://image",
                BrandId     = _fixture.Brands[0].Id,
                CategoryIds = new List <int> {
                    _fixture.Categories[0].Id
                }
            };

            var controller   = new ProductsController(_fixture.ProductService);
            var createResult = await controller.Post(createRequest);

            var createResponse = GetResponse <ProductCreateResponse>(createResult);

            Assert.Equal("Test product5", createResponse.Name);

            var updateRequest = new ProductUpdateRequest
            {
                Id          = createResponse.Id,
                Name        = "New Name",
                Price       = 456,
                Description = "new new",
                ImageUrl    = "http://new-image",
                BrandId     = _fixture.Brands[2].Id,
                CategoryIds = new List <int> {
                    _fixture.Categories[2].Id,
                    _fixture.Categories[3].Id
                }
            };

            var updateResult = await controller.Put(updateRequest);

            var updateResponse = GetResponse <ProductUpdateResponse>(updateResult);

            Assert.Equal(updateRequest.Id, updateResponse.Id);
            Assert.Equal(updateRequest.Price, updateResponse.Price);
            Assert.Equal(updateRequest.ImageUrl, updateResponse.ImageUrl);
            Assert.Equal(updateRequest.BrandId, updateResponse.BrandId);
            Assert.Equal(updateRequest.CategoryIds, updateResponse.CategoryIds);
        }
Пример #25
0
        public async Task GetProductByIdAsync_GivenProductIdThatExists_ShouldReturnTypeOk()
        {
            // Arrange
            var productServiceMock  = new Mock <IProductService>();
            int productIdThatExists = 0;

            productServiceMock.Setup(ps => ps.DoesProductIdExist(productIdThatExists))
            .ReturnsAsync(true);
            productServiceMock.Setup(ps => ps.GetProductByIdAsync(productIdThatExists))
            .ReturnsAsync(new Product());
            var productsController = new ProductsController(productServiceMock.Object);

            // Act
            ActionResult <Product> actionResult = await productsController.GetProductByIdAsync(productIdThatExists);

            // Assert
            actionResult.Result.ShouldBeOfType <OkObjectResult>();
        }
        public void ShouldReturnNotFoundWhenNoRecomendations()
        {
            // Arrange
            var controller = new ProductsController(
                new StubIProductRepository
            {
                GetProductInt32 = (id) => new Product()
            },
                new StubIProductRecommendationRepository());

            SetupControllerForTests(controller);

            // Act
            var result = controller.GetRecommendations(1);

            // Assert
            Assert.AreEqual(result.StatusCode, HttpStatusCode.NotFound);
        }
Пример #27
0
        public void TestGetAll()
        {
            //Arrange
            Mock <IProductApplicationService> mockProductApplicationService =
                new Mock <IProductApplicationService>();

            mockProductApplicationService.Setup(service => service.GetProducts())
            .Returns(new List <ProductDto>()
            {
                new ProductDto(), new ProductDto()
            });
            ProductsController controller = new ProductsController(mockProductApplicationService.Object);
            //Act
            IActionResult actionResult = controller.Get();

            //Assert
            Assert.IsType <OkObjectResult>(actionResult);
        }
Пример #28
0
        public void Add()
        {
            // arrange
            var controller = new ProductsController(new Repository.Repository());
            var newProduct = new Product()
            {
                Description = "Pear",
                Price       = 0.65M,
            };

            // act
            controller.Post(newProduct);

            var result = controller.Get();

            // asset
            result.Count().Should().Be(4);
        }
Пример #29
0
        public void DetailsTest_correctInfo()
        {
            ProductsController testController = new ProductsController(mock.Object);

            ViewResult infoView1 = testController.Details(0) as ViewResult;
            Product    details1  = infoView1.ViewData.Model as Product;
            ViewResult infoView2 = testController.Details(1) as ViewResult;
            Product    details2  = infoView1.ViewData.Model as Product;
            ViewResult infoView3 = testController.Details(2) as ViewResult;
            Product    details3  = infoView1.ViewData.Model as Product;

            Assert.AreEqual(details1.Name, "testName1");
            Assert.AreEqual(details1.Cost, 999);
            Assert.AreEqual(details2.Name, "testName2");
            Assert.AreEqual(details2.Cost, 1);
            Assert.AreEqual(details3.Name, "testName3");
            Assert.AreEqual(details3.Cost, 25);
        }
        public void Get_ShouldReturnProductWithSameId()
        {
            // Arrange
            var mockRepository = new Mock<IProductRepository>();
            mockRepository.Setup(x => x.GetProduct("Found"))
                .Returns(new Product { Id = "Found" });

            var controller = new ProductsController(mockRepository.Object);

            // Act
            IHttpActionResult actionResult = controller.Get("Found");
            var contentResult = actionResult as OkNegotiatedContentResult<Product>;

            // Assert
            Assert.IsNotNull(contentResult);
            Assert.IsNotNull(contentResult.Content);
            Assert.AreEqual("Found", contentResult.Content.Id);
        }
Пример #31
0
        public void UpdateProduct_BadResult()
        {
            //Arrange
            var controller = new ProductsController(_uow);
            var productId  = 2;

            var product = new Product
            {
                ProductId = 3,
                Name      = "Produto Teste Update"
            };

            //Act
            var result = controller.Put(productId, product);

            //Assert
            Assert.IsType <BadRequestObjectResult>(result.Result);
        }
        public void ShouldReturnNotFoundForProducts()
        {
            // Arrange
            var productRepository = new StubIProductRepository()
            {
                GetProductsInt32 = subcategoryId => null
            };
            var recommendationRepository = new StubIProductRecommendationRepository();
            var controller = new ProductsController(productRepository, recommendationRepository);

            SetupControllerForTests(controller);

            // Act
            var result = controller.GetProducts(1);

            // Assert
            Assert.AreEqual(result.StatusCode, HttpStatusCode.NotFound);
        }
Пример #33
0
        public void Mock_IndexModelContainsProducts_Collection() // Confirms presence of known entry
        {
            // Arrange
            DbSetup();
            ProductsController controller  = new ProductsController(mock.Object);
            Product            testProduct = new Product {
                ProductId = 1, Name = "1lb Gummy Bear", Cost = 10, Description = "BIG OLE BEAR"
            };

            testProduct.ProductId = 1;

            // Act
            ViewResult     indexView  = controller.Index() as ViewResult;
            List <Product> collection = indexView.ViewData.Model as List <Product>;

            // Assert
            CollectionAssert.Contains(collection, testProduct);
        }
        public void GetReturnsAllProducts()
        {
            // Arrange
            var mockRepository = new Mock <ProductServiceContext>();

            mockRepository.Setup(x => x.Products)
            .Returns(GetQueryableMockDbSet(MockProductListFull).Object);
            var controller = new ProductsController(mockRepository.Object);

            // Act
            IHttpActionResult actionResult = controller.Get();
            var contentResult = actionResult as OkNegotiatedContentResult <List <Product> >;

            // Assert
            Assert.IsNotNull(contentResult);
            Assert.IsNotNull(contentResult.Content);
            CollectionAssert.AreEqual(MockProductListFull, contentResult.Content);
        }
        public void DB_IndexListAllProducts_Collection()
        {
            //arrange
            ProductsController controller   = new ProductsController(db);
            Product            testProduct1 = new Product("sponge", "Sponges up liquid", (decimal)1.99);
            Product            testProduct2 = new Product("many sponges", "Sponges up liquid", (decimal)5.00);

            //act
            controller.Create(testProduct1);
            controller.Create(testProduct2);
            var            collection = (controller.Index() as ViewResult).ViewData.Model as List <Product>;
            List <Product> result     = new List <Product> {
                testProduct1, testProduct2
            };

            //assert
            CollectionAssert.AreEqual(result, collection);
        }
        public ProductsControllerTests()
        {
            mockProductsService = new Mock <IProductService>();

            IOptions <Settings> someOptions = Options.Create <Settings>(new Settings()
            {
                MaxCountProducts = 0
            });

            var config = new MapperConfiguration(cfg =>
            {
                cfg.AddProfile(new ViewMappingProfile());
            });

            mapper = config.CreateMapper();

            controller = new ProductsController(mockProductsService.Object, someOptions, mapper);;
        }
Пример #37
0
        public void GetReturnsAllProducts()
        {
            MockRepository mockRespository = new MockRepository();
            MockJsonHelper mockJsonHelper  = new MockJsonHelper(mockRespository);

            var controller = new ProductsController(mockJsonHelper);

            controller.Request = new HttpRequestMessage();
            controller.Request.Properties.Add(HttpPropertyKeys.HttpConfigurationKey, new HttpConfiguration());

            var response = controller.Get(2);


            String firstname;

            Assert.IsTrue(response.TryGetContentValue <String>(out firstname));
            Assert.AreEqual("Leonardo", firstname);
        }
        public void Mock_DeleteProduct_ReturnsView()
        {
            //arrange
            Product testProduct = new Product {
                ProductId = 1, Name = "Sponge", Description = "Sponges up liquids", Cost = (decimal)1.99
            };

            DbSetup();
            ProductsController controller = new ProductsController(mock.Object);

            //act
            var resultView = controller.Delete(testProduct.ProductId) as ViewResult;
            var model      = resultView.ViewData.Model as Product;

            //assert
            Assert.IsInstanceOfType(resultView, typeof(ViewResult));
            Assert.IsInstanceOfType(model, typeof(Product));
        }
        public void UpdateProdust_WhenNotExist()
        {
            // Arrange
            var  mockService = new Mock <IProductDomainService>();
            Guid testId      = Guid.NewGuid();

            mockService.Setup(ms => ms.UpdateProduct(testId, It.IsAny <Product>()))
            .Throws <Exception>();
            var controller = new ProductsController(mockService.Object);

            // Act & Assert
            var testRequest = new ProductRequest()
            {
                Name = "Guasha"
            };

            Assert.Throws <Exception>(() => controller.UpdateProduct(testId, testRequest));
        }
Пример #40
0
        public ProductControllerTest()
        {
            repository = new Mock <IProductRepository>();
            logger     = new Mock <ILogger <ProductsController> >();
            sut        = new ProductsController(repository.Object,
                                                logger.Object);

            AutoMapper.Mapper.Initialize(cfg =>
            {
                cfg.CreateMap <Entities.Product, Models.ProductDto>();
                cfg.CreateMap <Entities.ProductOption, Models.ProductOptionDto>();

                cfg.CreateMap <Models.ProductForCreationDto, Entities.Product>();
                cfg.CreateMap <Models.ProductForUpdateDto, Entities.Product>();
                cfg.CreateMap <Models.ProductOptionForCreationDto, Entities.ProductOption>();
                cfg.CreateMap <Models.ProductOptionForUpdateDto, Entities.ProductOption>();
            });
        }
        private ProductsController SetupController()
        {
            //const string ProductDescription = "SomeDescr";
            var autoMapperConfig = new AutoMapperConfig();
            autoMapperConfig.Execute(typeof(ProductsController).Assembly);
            var productsServiceMock = new Mock<IProductsService>();
            productsServiceMock
                .Setup(x => x.GetById(It.IsAny<string>()))
                .Returns(new Product()
                {
                    Title = "someName",
                    ShortDescription = this.ProductDescription,
                    Category = new Category()
                    {
                        Name = "someName"
                    }
                });

            var cacheServiceMock = new Mock<ICacheService>();
            var controller = new ProductsController(productsServiceMock.Object, cacheServiceMock.Object);

            return controller;
        }
        public void Put_ShouldFail_WhenDifferentID()
        {
            // Arrange
            var mockRepository = new Mock<IProductRepository>();
            ProductsController controller = new ProductsController(mockRepository.Object);

            // Act
            var badresult = controller.Put("999", Helpers.CreateTestProduct());

            // Assert
            Assert.IsInstanceOfType(badresult, typeof(BadRequestResult));
        }
        public void PutProduct_ShouldReturnStatusCode()
        {
            // arrange
            var controller = new ProductsController(new TestStoreAppContext());
            var item = this.GetDemoProduct();

            // act
            var result = controller.PutProduct(item.Id, item) as StatusCodeResult;

            // assert
            Assert.IsType(typeof(StatusCodeResult), result);
            Assert.Equal(HttpStatusCode.NoContent, result.StatusCode);
        }
        public void Get_ShouldReturnNotFoundWhenProductDoesNotExist()
        {
            // Arrange
            var mockRepository = new Mock<IProductRepository>();
            mockRepository.Setup(x => x.GetProduct("Not Found"));

            var controller = new ProductsController(mockRepository.Object);

            // Act
            IHttpActionResult actionResult = controller.Get("Not Found");

            // Assert
            Assert.IsInstanceOfType(actionResult, typeof(NotFoundResult));
        }
        public void Get_ShouldReturnAllProducts()
        {
            // Arrange
            var mockRepository = new Mock<IProductRepository>();
            var testData = Helpers.GetTestData();
            mockRepository.Setup(x => x.GetAllProducts())
               .Returns(testData.AsQueryable());
            
            var controller = new ProductsController(mockRepository.Object);

            // Act
            IEnumerable<Product> products = controller.Get();

            // Assert
            Assert.IsNotNull(products);
            Assert.AreEqual(testData.Count, products.Count());
        }
        public void Post_ShouldSetRouteValues()
        {
            // Arrange
            var mockRepository = new Mock<IProductRepository>();                  
            ProductsController controller = new ProductsController(mockRepository.Object);

            controller.Request = new HttpRequestMessage
            {
                RequestUri = new Uri(string.Format("http://{0}:{1}/api/inventory/products", "localhost", 65217))
            };

            controller.Configuration = new HttpConfiguration();
            controller.Configuration.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/inventory/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional });

            controller.RequestContext.RouteData = new HttpRouteData(
                route: new HttpRoute(),
                values: new HttpRouteValueDictionary { { "controller", "products" } });

            // Act
            Product product = new Product() { Id = "MyTitle", Title = "Product1" };
            var actionResult = controller.Post(product);

            // Assert
            var response = actionResult as CreatedAtRouteNegotiatedContentResult<Product>;

            // Implementation uses WebAPI helper class to ensure that the response headers are set correct.
            // Only need to test that the ROute VAlues are configured
            Assert.IsNotNull(response);
            Assert.AreEqual("DefaultApi", response.RouteName);
            Assert.AreEqual("MyTitle", response.RouteValues["Id"]);

            mockRepository.Verify(m => m.InsertProduct(It.Is<Product>(arg => arg.Id == "MyTitle")));
        }
        public void Post_ShouldAddProductToRepo()
        {
            // Arrange
            var mockRepository = new Mock<IProductRepository>();
            ProductsController controller = new ProductsController(mockRepository.Object);

            controller.Request = new HttpRequestMessage
            {
                RequestUri = new Uri(string.Format("http://{0}:{1}/api/inventory/products", "localhost", 65217))
            };

            controller.Configuration = new HttpConfiguration();
            controller.Configuration.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/inventory/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional });

            controller.RequestContext.RouteData = new HttpRouteData(
                route: new HttpRoute(),
                values: new HttpRouteValueDictionary { { "controller", "products" } });

            // Act
            Product product = new Product() { Id = "MyTitle", Title = "Product1" };
            var actionResult = controller.Post(product);

            // Assert           
            mockRepository.Verify(m => m.InsertProduct(It.Is<Product>(arg => arg.Id == "MyTitle")));
        }
        public void Delete_ShouldReturnProductWithSameId()
        {
            // Arrange
            var item = Helpers.CreateTestProduct();

            var mockRepository = new Mock<IProductRepository>();
            mockRepository.Setup(x => x.GetProduct(item.Id)).Returns(item);
            mockRepository.Setup(x => x.DeleteProduct(item));

            var controller = new ProductsController(mockRepository.Object);

            // Act
            IHttpActionResult actionResult = controller.Delete(item.Id);
            var contentResult = actionResult as OkNegotiatedContentResult<Product>;

            // Assert
            Assert.IsNotNull(contentResult);
            Assert.IsNotNull(contentResult.Content);
            Assert.AreEqual(item.Id, contentResult.Content.Id);
        }       
        public void Get_ShouldReturnOkResult()
        {
            // Arrange
            var mockRepository = new Mock<IProductRepository>();
            mockRepository.Setup(x => x.GetProduct("Found"))
                .Returns(new Product { Id = "Found" });

            var controller = new ProductsController(mockRepository.Object);

            // Act
            IHttpActionResult actionResult = controller.Get("Found");            

            // Assert
            Assert.IsInstanceOfType(actionResult, typeof(OkNegotiatedContentResult<Product>));
        }
        public void Delete_ShouldReturnNotFoundWhenProductDoesNotExist()
        {
            // Arrange
            var item = Helpers.CreateTestProduct();

            var mockRepository = new Mock<IProductRepository>();
            mockRepository.Setup(x => x.GetProduct(item.Id));
            var controller = new ProductsController(mockRepository.Object);

            // Act
            IHttpActionResult actionResult = controller.Delete(item.Id);

            // Assert
            Assert.IsInstanceOfType(actionResult, typeof(NotFoundResult));
        }
        public void Delete_ShouldReturnOkResult()
        {
            // Arrange
            var item = Helpers.CreateTestProduct();

            var mockRepository = new Mock<IProductRepository>();
            mockRepository.Setup(x => x.GetProduct(item.Id)).Returns(item);
            //mockRepository.Setup(x => x.DeleteProduct(item.Id));

            var controller = new ProductsController(mockRepository.Object);

            // Act
            IHttpActionResult actionResult = controller.Delete(item.Id);

            // Assert
            Assert.IsInstanceOfType(actionResult, typeof(OkNegotiatedContentResult<Product>));
        }
        public void Put_ShouldChangeProductInRepo()
        {
            // Arrange
            var item = Helpers.CreateTestProduct();

            var mockRepository = new Mock<IProductRepository>();
            mockRepository.Setup(x => x.ProductExists(item.Id)).Returns(true);

            ProductsController controller = new ProductsController(mockRepository.Object);          
            controller.Request = new HttpRequestMessage
            {
                RequestUri = new Uri(string.Format("http://{0}:{1}/api/inventory/products", "localhost", 65217))
            };

            controller.Configuration = new HttpConfiguration();
            controller.Configuration.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/inventory/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional });

            controller.RequestContext.RouteData = new HttpRouteData(
                route: new HttpRoute(),
                values: new HttpRouteValueDictionary { { "controller", "products" } });

            // Act
            var actionResult = controller.Put(item.Id, item);

            // Assert           
            mockRepository.Verify(m => m.ChangeProduct(It.Is<Product>(arg => arg.Id == item.Id)));   
        }
        public void Put_ShouldFail_WhenModelStateInvalid()
        {
            // Arrange
            var mockRepository = new Mock<IProductRepository>();
            ProductsController controller = new ProductsController(mockRepository.Object);
            controller.ModelState.AddModelError("key", "error message");
            var item = Helpers.CreateTestProduct();

            // Act
            var badresult = controller.Put(item.Id, item);

            // Assert
            Assert.IsInstanceOfType(badresult, typeof(InvalidModelStateResult));
        }
        public void Put_ShouldReturnStatusCode()
        {
            // Arrange
            var item = Helpers.CreateTestProduct();

            var mockRepository = new Mock<IProductRepository>();
            mockRepository.Setup(x => x.ProductExists(item.Id)).Returns(true);
            mockRepository.Setup(x => x.ChangeProduct(item));

            ProductsController controller = new ProductsController(mockRepository.Object);            

            // Act
            var result = controller.Put(item.Id, item) as StatusCodeResult;

            // Assert
            Assert.IsNotNull(result);
            Assert.IsInstanceOfType(result, typeof(StatusCodeResult));
            Assert.AreEqual(HttpStatusCode.NoContent, result.StatusCode);
        }
        public void Put_ShouldFail_WhenProductNotFound()
        {
            // Arrange
            var item = Helpers.CreateTestProduct();

            var mockRepository = new Mock<IProductRepository>();
            mockRepository.Setup(x => x.ProductExists(item.Id)).Returns(false);

            ProductsController controller = new ProductsController(mockRepository.Object);           

            // Act            
            var actionResult = controller.Put(item.Id, item);

            // Assert           
            Assert.IsInstanceOfType(actionResult, typeof(NotFoundResult));
        }