Example #1
0
        public void Can_Edit_Category()
        {
            //---Arrange---
            Mock <IRepository> mock = new Mock <IRepository>();

            mock.Setup(c => c.Products).Returns(new Product[]
            {
                new Product()
                {
                    ProductId = 1, Name = "Alba", BrandId = 1, CategoryId = 1, Color = "Blue", ProductCondition = "Very good", Description = "Desc", Price = 23.2,
                },
                new Product()
                {
                    ProductId = 2, Name = "Alba", BrandId = 1, CategoryId = 1, Color = "Blue", ProductCondition = "Very good", Description = "Desc", Price = 23.2,
                },
                new Product()
                {
                    ProductId = 3, Name = "Alba", BrandId = 1, CategoryId = 1, Color = "Blue", ProductCondition = "Very good", Description = "Desc", Price = 23.2,
                },
            });

            //---Arrange---
            ProductsController controller = new ProductsController(mock.Object);

            //---Action---
            var product1 = ((ViewResult)controller.Edit(1)).ViewData.Model as Product;
            var product2 = ((ViewResult)controller.Edit(2)).ViewData.Model as Product;
            var product3 = ((ViewResult)controller.Edit(3)).ViewData.Model as Product;

            //---Assert---
            Assert.AreEqual(1, product1.ProductId);
            Assert.AreEqual(2, product2.ProductId);
            Assert.AreEqual(3, product3.ProductId);
        }
        public void Should_return_BadRequest_when_element_to_modify_is_not_found()
        {
            var result = _testController.Edit(_notCreatedValidDateProductDto) as BadRequestObjectResult;

            Assert.IsNotNull(result);
            Assert.AreEqual(400, result.StatusCode);
        }
Example #3
0
        public void Edit_Get_Objekt()
        {
            var actionResult = _productController.Edit(1);
            var viewRessult  = actionResult as ViewResult;
            var result       = (Product)viewRessult.Model;

            Assert.AreEqual(ResourceData.Products[0].Name, result.Name);
            Assert.AreEqual(ResourceData.Products[0].Volume, result.Volume);
            Assert.AreEqual(ResourceData.Products[0].VatCode, result.VatCode);
        }
        public void EditLoadsErrorViewWithNullId()
        {
            var result     = controller.Edit(null);
            var viewResult = (ViewResult)result.Result;

            Assert.AreEqual("Error", viewResult.ViewName);
        }
Example #5
0
        public async Task Edit_ValidModel_ShouldPerformEdit()
        {
            var viewModel = new ProductViewModel()
            {
                ProductId = 1, ProductName = "New Name"
            };
            var result = await _controller.Edit(viewModel.ProductId, viewModel) as RedirectToActionResult;

            _productsServiceMock.Verify(x => x.UpdateAsync(It.IsAny <ProductDto>()), Times.Once);

            Assert.IsNotNull(result);
            Assert.AreEqual(nameof(_controller.Index), result.ActionName);
        }
        public async void Should_GetEditAction_Returns_RedirectToIndex_IF_idIsNull(int?id)
        {
            var result = await controller.Edit(id);

            //Assert.IsType<RedirectToActionResult>(result); gibi
            Assert.Equal(nameof(Index), ((RedirectToActionResult)result).ActionName);
        }
        public void Edit_RedirectToHome_WhenProductNotExist()
        {
            // Arrange
            var id = 1;

            mockProductsService.Setup(x => x.Get(id, true)).Returns <Product>(null);

            // Act
            RedirectToActionResult redirectResult =
                (RedirectToActionResult)controller.Edit(id);

            // Assert
            Assert.Equal(redirectResult.ActionName, "Index");
        }
Example #8
0
        public void EditGet_IfIdValid_ShouldReturnView_ShouldReturnModel()
        {
            // arrange
            InitializeController();

            // act
            var result = _productsController.Edit(1);

            // assert
            Assert.IsType <ViewResult>(result);
            _categoryServiceMock.Verify(_ => _.GetAllCategories(), Times.Once);
            _supplierServiceMock.Verify(_ => _.GetAllSuppliers(), Times.Once);
            _productServiceMock.Verify(_ => _.GetProduct(1), Times.Once);
        }
Example #9
0
        public void Product_ProductEdit_ReturnsProductServiceUpdate()
        {
            var viewModel = new ProductEditModel()
            {
                Product = new ProductDto()
                {
                    SupplierId = 1, Name = "Test", WholesalerId = 1, PurchasePrice = 9.99, CategoryId = 1
                }
            };

            var result = _controller.Edit(viewModel) as RedirectToRouteResult;

            _productService.Received().Update(viewModel.Product);
        }
Example #10
0
        public void TestEditP()
        {
            var rand    = new Random();
            var db      = new CS4PEntities();
            var product = db.Products.AsNoTracking().First();

            product.Name        = rand.NextDouble().ToString();
            product.Description = rand.NextDouble().ToString();
            product.Price       = -rand.Next();

            var controller = new ProductsController();

            var result0 = controller.Edit(product, null) as ViewResult;

            Assert.IsNotNull(result0);
            Assert.AreEqual("Price is less than Zero", controller.ModelState["Price"].Errors[0].ErrorMessage);

            var picture = new Mock <HttpPostedFileBase>();
            var server  = new Mock <HttpServerUtilityBase>();
            var context = new Mock <HttpContextBase>();

            context.Setup(c => c.Server).Returns(server.Object);
            controller.ControllerContext = new ControllerContext(context.Object,
                                                                 new System.Web.Routing.RouteData(), controller);

            var fileName = String.Empty;

            server.Setup(s => s.MapPath(It.IsAny <string>())).Returns <string>(s => s);
            picture.Setup(p => p.SaveAs(It.IsAny <string>())).Callback <string>(s => fileName = s);

            using (var scope = new TransactionScope())
            {
                product.Price = -product.Price;
                controller.ModelState.Clear();
                var result1 = controller.Edit(product, picture.Object) as RedirectToRouteResult;
                Assert.IsNotNull(result1);
                Assert.AreEqual("Index", result1.RouteValues["action"]);

                var entity = db.Products.Find(product.id);
                Assert.IsNotNull(entity);
                Assert.AreEqual(product.Name, entity.Name);
                Assert.AreEqual(product.Description, entity.Description);
                Assert.AreEqual(product.Price, entity.Price);

                Assert.AreEqual("~/Upload/Products/" + product.id, fileName);
                //Assert.IsTrue(fileName.StartsWith("~/Upload/Products/"));
                //Assert.IsTrue(fileName.EndsWith(entity.id.ToString()));
            }
        }
        public void Edit_PostInvalidModel_ReturnsModelWithListOfCategories()
        {
            var mockProductService         = new Mock <IProductService>();
            var mockCategoryService        = new Mock <ICategoryService>();
            var mockCategoryProductService = new Mock <ICategoryAndProductService>();

            var controller = new ProductsController(mockProductService.Object,
                                                    mockCategoryService.Object,
                                                    mockCategoryProductService.Object);

            mockCategoryService.Setup(x => x.GetAllCategories()).Returns(GetCategories());

            var productCreateEditViewModel = new ProductCreateEditFormViewModel();

            controller.ModelState.AddModelError("FakeError", "Fake Error Message");

            var result     = controller.Edit(productCreateEditViewModel) as ViewResult;
            var categories = ((ProductCreateEditFormViewModel)result.ViewData.Model).Categories.ToList();

            Assert.IsNotNull(result);
            Assert.AreEqual(string.Empty, result.ViewName);
            Assert.IsFalse(result.ViewData.ModelState.IsValid);
            Assert.AreEqual(4, categories.Count);
            Assert.AreEqual(2, categories[1].Id);
            Assert.AreEqual("Accessories", categories[3].Name);
        }
Example #12
0
        public async Task TestEditShouldNotReturnErrors()
        {
            ProductViewModel product = new ProductViewModel
            {
                Id           = 1,
                Name         = "Test",
                NoOfUnit     = 12,
                ReOrderLevel = 1,
                UnitPrice    = 100
            };

            _productViewModelFactory.Setup(m => m.ExceuteUpdate(product))
            .ReturnsAsync((new ProductViewModel
            {
                Id = 1,
                Name = "Test",
                NoOfUnit = 12,
                ReOrderLevel = 1,
                UnitPrice = 100
            }, new List <string> {
            }));

            var result = await _controller.Edit(product) as ViewResult;

            Assert.That(result.ViewData.ModelState.IsValid, Is.EqualTo(true));
            Assert.That(result.ViewData.ModelState.ErrorCount, Is.EqualTo(0));
        }
Example #13
0
 public void EditPriceByID()
 {
     using (ProductsController productsController = new ProductsController())
     {
         Assert.IsNotNull(productsController.Edit(GetItem("Price", 3.99m).Id));
     }
 }
Example #14
0
 public void EditNameByID()
 {
     using (ProductsController productsController = new ProductsController())
     {
         Assert.IsNotNull(productsController.Edit(GetItem("Name", "Item Name Changed by ID").Id));
     }
 }
Example #15
0
        public async Task Edit_RedirectsIndexActionWithNewlyCreatedProductIdInRoute()
        {
            int productIdTest    = 7;
            var productViewModel = new ProductViewModel();
            var product          = new Product
            {
                ProductId = productIdTest
            };

            _mockMapper.Setup(m => m.Map <Product>(productViewModel))
            .Returns(product)
            .Verifiable();
            _mockDataRepository.Setup(m => m.UpdateProductAsync(product))
            .Returns(Task.FromResult(product))
            .Verifiable();
            _mockDataRepository.Setup(m => m.CommitAsync())
            .Verifiable();

            var controller = new ProductsController(_mockDataRepository.Object, _mockOptions.Object, _mockMapper.Object);

            var result = await controller.Edit(productViewModel);

            var redirectToActionResult = Assert.IsType <RedirectToActionResult>(result);

            Assert.Equal("Index", redirectToActionResult.ActionName);
            _mockMapper.Verify();
            _mockDataRepository.Verify();
        }
        public void SaveInvalidChangesToProductTest()
        {
            Mock <IProductRepository>     mockRepository      = new Mock <IProductRepository>();
            Mock <IUserPreferenceService> mockUserPrefService = new Mock <IUserPreferenceService>();

            mockUserPrefService.Setup(prefService => prefService.Preferences).Returns(new UserPreferenceInfo()
            {
                ProductsPerPage         = 5,
                ProductColumnsToDisplay = new List <string>()
            });

            Mock <ILocalizedMessageService> mockMessageService = new Mock <ILocalizedMessageService>();

            mockMessageService.Setup(messageService => messageService.ProductSaved).Returns("{0} was saved.");

            ProductsController controller = new ProductsController(mockRepository.Object, mockUserPrefService.Object, mockMessageService.Object);

            controller.ModelState.AddModelError("error", "error");
            Product      product = GenerateFakeProducts(1).FirstOrDefault();
            ActionResult result  = controller.Edit(product);

            // Assert - check that the repository was not called
            mockRepository.Verify(m => m.SaveProduct(It.IsAny <Product>()), Times.Never());
            // Assert - check the method result type
            Assert.IsInstanceOfType(result, typeof(ViewResult));
        }
        public async Task Edit_GivenAProductIdThatExistsAsAnUnauthorizedUser_ShouldReturnForbidResult()
        {
            // Arrange
            var productServiceMock  = new Mock <IProductService>();
            var productIdThatExists = 1;

            productServiceMock.Setup(ps => ps.DoesProductIdExist(productIdThatExists))
            .ReturnsAsync(true);

            var authorizationServiceMock = CreateAuthorizationServiceMockThatDoesNotAuthorizeUser();

            var mockUserStore   = new Mock <IUserStore <IdentityUser> >();
            var userManagerMock = new Mock <UserManager <IdentityUser> >(mockUserStore.Object, null, null, null, null, null, null, null, null);

            var productsController = new ProductsController(
                productServiceMock.Object,
                authorizationServiceMock.Object,
                userManagerMock.Object
                );

            // Act
            IActionResult actionResult = await productsController.Edit(productIdThatExists);

            // Assert
            actionResult.ShouldBeOfType <ForbidResult>();
        }
Example #18
0
        public void CanNot_Save_Invalid_Changes()
        {
            //---Arrange---
            Mock <IRepository> mock = new Mock <IRepository>();

            mock.Setup(c => c.Products).Returns(new Product[]
            {
                new Product()
                {
                    ProductId = 1, Name = "Alba", BrandId = 1, CategoryId = 1, Color = "Blue", ProductCondition = "Very good", Description = "Desc", Price = 23.2,
                },
                new Product()
                {
                    ProductId = 2, Name = "Alba", BrandId = 1, CategoryId = 1, Color = "Blue", ProductCondition = "Very good", Description = "Desc", Price = 23.2,
                },
                new Product()
                {
                    ProductId = 3, Name = "Alba", BrandId = 1, CategoryId = 1, Color = "Blue", ProductCondition = "Very good", Description = "Desc", Price = 23.2,
                },
            });
            ProductsController controller = new ProductsController(mock.Object);
            Product            product    = new Product()
            {
                ProductId = 4, Name = "Alba", BrandId = 1, CategoryId = 1, Color = "Blue", ProductCondition = "Very good", Description = "Desc", Price = 23.2,
            };

            controller.ModelState.AddModelError("error", "error");

            //---Act---
            ActionResult result = controller.Edit(product.ProductId);

            //---Assert---
            mock.Verify(m => m.SaveProducts(It.IsAny <Product>()), Times.Never());
            Assert.IsInstanceOfType(result, typeof(ViewResult));
        }
Example #19
0
        public async Task EditInvalid()
        {
            var context = MockContext.GetContext("test6");

            context.Seed();
            var controller = new ProductsController(_userManager, _signInManager, context);

            var product = new Product
            {
                Name         = "UpdatedName1",
                LatinName    = "LatinName1",
                Description  = "Description1",
                Kind         = "Kind1",
                Type         = "Type1",
                Light        = "Light1",
                Water        = "Water1",
                ProductDate  = DateTime.Now,
                Picture      = null,
                PictureTwo   = null,
                PictureThree = null,
                Trade        = "Trade1",
                Delivery     = "Delivery1",
                Soil         = "Soil1"
            };


            var response = controller.Edit(10, product, null, null, null);

            var plant = context.Products.FirstOrDefault(p => p.Id == 1);

            Assert.IsType <NotFoundResult>(response.Result);
        }
Example #20
0
        public void Can_Edit_NonExistent_Category()
        {
            //---Arrange---
            Mock <IRepository> mock = new Mock <IRepository>();

            mock.Setup(c => c.Products).Returns(new Product[]
            {
                new Product()
                {
                    ProductId = 1, Name = "Alba", BrandId = 1, CategoryId = 1, Color = "Blue", ProductCondition = "Very good", Description = "Desc", Price = 23.2,
                },
                new Product()
                {
                    ProductId = 2, Name = "Alba", BrandId = 1, CategoryId = 1, Color = "Blue", ProductCondition = "Very good", Description = "Desc", Price = 23.2,
                },
                new Product()
                {
                    ProductId = 3, Name = "Alba", BrandId = 1, CategoryId = 1, Color = "Blue", ProductCondition = "Very good", Description = "Desc", Price = 23.2,
                },
            });
            ProductsController controller = new ProductsController(mock.Object);
            //---Action---

            var nonexistent = ((ViewResult)controller.Edit(5)).ViewData.Model as Product;


            //---Assert---

            Assert.IsNull(nonexistent);
        }
        public async Task Edit_GivenAProductIdThatDoesNotExist_ShouldReturnNotFound()
        {
            // Arrange
            var productServiceMock        = new Mock <IProductService>();
            int productIdThatDoesNotExist = 0;

            productServiceMock.Setup(ps => ps.DoesProductIdExist(productIdThatDoesNotExist))
            .ReturnsAsync(false);

            var authorizationServiceMock = new Mock <IAuthorizationService>();

            var mockUserStore   = new Mock <IUserStore <IdentityUser> >();
            var userManagerMock = new Mock <UserManager <IdentityUser> >(mockUserStore.Object, null, null, null, null, null, null, null, null);

            var productsController = new ProductsController(
                productServiceMock.Object,
                authorizationServiceMock.Object,
                userManagerMock.Object
                );

            // Act
            IActionResult actionResult = await productsController.Edit(productIdThatDoesNotExist);

            // Assert
            actionResult.ShouldBeOfType <NotFoundResult>();
        }
Example #22
0
 public void EditPriceByObject()
 {
     using (ProductsController productsController = new ProductsController())
     {
         Assert.IsNotNull(productsController.Edit(GetItem("Price", 2.99m)));
     }
 }
Example #23
0
        public async Task Edit_ReturnsViewWithProductViewModel()
        {
            int productIdTest    = 7;
            var productViewModel = new ProductViewModel
            {
                ProductId = productIdTest
            };
            var product = new Product
            {
                ProductId = productIdTest
            };

            _mockDataRepository.Setup(m => m.GetProductByIdAsync(productIdTest))
            .Returns(Task.FromResult(product))
            .Verifiable();
            _mockMapper.Setup(m => m.Map <ProductViewModel>(product))
            .Returns(productViewModel)
            .Verifiable();
            var controller = new ProductsController(_mockDataRepository.Object, _mockOptions.Object, _mockMapper.Object);

            var result = await controller.Edit(productIdTest);

            var viewResult = Assert.IsType <ViewResult>(result);

            Assert.IsAssignableFrom <ProductViewModel>(viewResult.Model);
        }
Example #24
0
 public void EditLocationByObject()
 {
     using (ProductsController productsController = new ProductsController())
     {
         Assert.IsNotNull(productsController.Edit(GetItem("Location", "Games")));
     }
 }
        public async Task Edit_ReturnsViewResultWithModel(string expectedName)
        {
            var product = new Product
            {
                Id          = Guid.NewGuid(),
                Name        = "Keyboard",
                Description = "",
                Quantity    = 10,
                Enable      = true
            };

            var mockService = new Mock <IEntityService <Product> >();

            mockService.Setup(s => s.GetByIdAsync(product.Id)).Returns(Task.FromResult(product));
            var controller = new ProductsController(mockService.Object);

            // Act
            var result = await controller.Edit(product.Id); // as ViewResult;

            var viewResult = Assert.IsType <ViewResult>(result);
            var model      = Assert.IsAssignableFrom <Product>(viewResult.ViewData.Model);

            Assert.NotNull(viewResult);
            Assert.NotNull(model);
            Assert.NotNull(viewResult.Model);
            Assert.Equal(expectedName, model.Name);
            Assert.Equal(10, model.Quantity);
            Assert.Equal(typeof(Product), viewResult.Model.GetType());
        }
Example #26
0
 public void EditLocationByID()
 {
     using (ProductsController productsController = new ProductsController())
     {
         Assert.IsNotNull(productsController.Edit(GetItem("Location", "Hardware").Id));
     }
 }
Example #27
0
        public void edit()
        {
            ProductsController controller = new ProductsController();
            ViewResult         result     = controller.Edit(1) as ViewResult;

            Assert.IsNotNull(result);
        }
Example #28
0
        public void Mock_GetViewResultEditGet_ActionResult() // Confirms route returns view
        {
            DbSetup();
            ProductsController controller = new ProductsController(mock.Object);
            var result = controller.Edit(2);

            Assert.IsInstanceOfType(result, typeof(ViewResult));
        }
Example #29
0
        public void TestEditGet()
        {
            var controller = new ProductsController();
            var result0    = controller.Edit(0);

            Assert.IsInstanceOfType(result0, typeof(HttpNotFoundResult));

            var db      = new ProductEntities();
            var item    = db.Products.First();
            var result1 = controller.Edit(item.id) as ViewResult;

            Assert.IsNotNull(result1);
            var model = result1.Model as Product;

            Assert.IsNotNull(model);
            Assert.AreEqual(item.id, model.id);
        }
Example #30
0
 public void EditByIDNullCheck()
 {
     using (ProductsController productsController = new ProductsController())
     {
         //The ID '0' is not a valid item and will produce a null record in the controller.
         Assert.IsNotNull(productsController.Edit(0));
     }
 }