Exemplo n.º 1
0
        public void Add_should_return_Edit_view_when_invoked()
        {
            var action = controller.Add();

            Assert.That(action, Is.Not.Null);
            Assert.That(action.ViewName, Is.EqualTo("Edit"));
        }
Exemplo n.º 2
0
        public void Add_InvalidObjectPassed_ReturnsBadRequest1()
        {
            // Arrange
            var request = new AddProductRequest()
            {
                ExpirationDate = DateTime.Now,
                CategoryIds    = new int[] { 10 },
            };

            _productController.ModelState.AddModelError("Name", "Name required");
            _productController.ModelState.AddModelError("Rating", "Rating required");
            _productController.ModelState.AddModelError("BrandId", "Invalid Brand");
            _productController.ModelState.AddModelError("CategoryIds", "Invalid category");
            _productController.ModelState.AddModelError("ExpirationDate", "Expiration date should expire not less than 30 days since now");


            // Act
            var badResponse = _productController.Add(request).Result;

            // Assert
            Assert.IsType <BadRequestObjectResult>(badResponse);
            var response = (badResponse as BadRequestObjectResult).Value as SerializableError;

            Assert.Equal(5, response.Count);
        }
Exemplo n.º 3
0
        public async Task Add_ValidModel_ProductIsAdded()
        {
            var product = new Product();
            await _controller.Add(product);

            _productServicceMock.Verify(x => x.AddProductAsync(product), Times.Once);
        }
Exemplo n.º 4
0
        public async Task Add_FetchAllData()
        {
            // Act
            var result = await _controller.Add();

            // Assert
            _categoryServiceMock.Verify(service => service.GetAll(), Times.Once);
            _supplierServiceMock.Verify(service => service.GetAll(), Times.Once);
        }
Exemplo n.º 5
0
        public async Task Test_Add_Get_ShouldReturnModelWithEmptyProduct()
        {
            var result = (await _productController.Add()) as ViewResult;
            var model  = result?.Model as EditProductViewModel;

            Assert.NotNull(model);
            Assert.Null(model.Product);

            _categoryServiceMock.Verify(x => x.GetCategoriesAsync(), Times.Once);
            _supplierServiceMock.Verify(x => x.GetSuppliersAsync(), Times.Once);
        }
        public async Task AddPost_ReturnsViewWithModel_WhenModelStateIsInvalid()
        {
            var mockRepo       = new Mock <IProductRepository>();
            var controller     = new ProductController(mockRepo.Object);
            var invalidProduct = new Product()
            {
                Name      = string.Empty, // Name is required to be valid
                Price     = "9.99",
                ProductId = 1
            };

            controller.ModelState.AddModelError("Name", "Required");

            IActionResult result = await controller.Add(invalidProduct);

            Assert.IsInstanceOfType(result, typeof(ViewResult));

            ViewResult viewResult = result as ViewResult;

            Assert.IsInstanceOfType(viewResult.Model, typeof(Product));

            Product modelBoundProduct = viewResult.Model as Product;

            Assert.AreEqual(modelBoundProduct, invalidProduct, "Invalid Product should be passed back to view");
        }
        public async Task Add_RaisesWebUiException()
        {
            _productServiceMock.Setup(m => m.CreateAsync(It.IsAny <Product>())).Throws <ServiceException>();
            var target = new ProductController(_productServiceMock.Object);

            await target.Add(new WebUser(), new Product());
        }
Exemplo n.º 8
0
 private void BtnSave_Click(object sender, EventArgs e)
 {
     if (btnSave.Text == "Add")
     {
         var product = new Product
         {
             ID          = Guid.NewGuid(),
             Code        = txtCode.Text,
             Description = txtDesc.Text,
             Name        = txtName.Text,
             SKU         = txtSku.Text,
             EntryDate   = DateTime.Now,
             Status      = "Active"
         };
         productController.Add(product);
         grdProducts.DataSource = dtProducts = productController.GetAllDataTable();
         MessageBox.Show("Product Added Sucessfully");
     }
     else
     {
         var product = new Product
         {
             ID          = ProductID,
             Code        = txtCode.Text,
             Description = txtDesc.Text,
             Name        = txtName.Text,
             SKU         = txtSku.Text,
             EntryDate   = DateTime.Now,
             Status      = "Active"
         };
         productController.Update(ProductID, product);
         grdProducts.DataSource = dtProducts = productController.GetAllDataTable();
         MessageBox.Show("Product Updated Sucessfully");
     }
 }
Exemplo n.º 9
0
        private void AddButton_Click(object sender, RoutedEventArgs e)
        {
            ProductController productController = new ProductController();

            double.TryParse(Quantity.Text, out double quant);
            productController.Add(NameText.Text, CodeOneC.Text, Articul.Text, quant, QuantSI.Text, Address.Text, ComentText.Text);
        }
        public void Add_ReturnsAViewResult()
        {
            var mockRepo   = new Mock <IProductRepository>();
            var controller = new ProductController(mockRepo.Object);

            var result = controller.Add();

            Assert.IsInstanceOfType(result, typeof(ViewResult));
        }
        public void Add_GET_ModelISAsProductObject()
        {
            //Arrang
            var rep        = new Mock <IRepository <Product> >();
            var controller = new ProductController(rep.Object);

            //act
            var model = controller.Add().ViewData.Model as Product;

            //Assert
            Assert.IsType <Product>(model);
        }
Exemplo n.º 12
0
        public void Add_Returns_ViewResult()
        {
            //Arrange
            var repo       = new Mock <IRepository <Product> >();
            var controller = new ProductController(repo.Object);

            //Act
            var result = controller.Add();

            //Assert
            Assert.IsType <ViewResult>(result);
        }
        public void Add_GET_ValueOfViewBagActionPropertyIsAdd()
        {
            //arrange
            var    rep        = new Mock <IRepository <Product> >();
            var    controller = new ProductController(rep.Object);
            string expected   = "Add";

            //act
            ViewResult result = controller.Add();

            //Assert
            Assert.Equal(expected, result.ViewData["Action"]?.ToString());
        }
Exemplo n.º 14
0
        public async Task Add_RaisesWebUiExceptionWithInnerServiceException()
        {
            _productServiceMock.Setup(m => m.CreateAsync(It.IsAny <Product>())).Throws <ServiceException>();
            var target = new ProductController(_productServiceMock.Object);

            try
            {
                await target.Add(new WebUser(), new Product());
            }
            catch (WebUiException e)
            {
                Assert.IsInstanceOfType(e.InnerException, typeof(ServiceException));
            }
        }
Exemplo n.º 15
0
        public void AddTest()
        {
            // Arrange
            var mock       = new Mock <IProductRepository>();
            var controller = new ProductController(mock.Object);
            // Act
            var result = controller.Add(new WebApi.ViewModels.Product()
            {
                Id = 1, Name = "Product #1", CategoryId = 1, Description = "Product #1 Description", Price = 11, Quantity = 111
            }).Result as OkResult;

            // Assert
            Assert.NotNull(result);
            Assert.AreEqual(StatusCodes.Status200OK, result.StatusCode);
        }
Exemplo n.º 16
0
        public async Task Can_Add_Valid_Product()
        {
            Product product = new Product()
            {
                CategoryID = 1, Description = "Prod1", ProductID = 1
            };
            var target = new ProductController(_productServiceMock.Object);

            var result = await target.Add(new WebUser()
            {
                Id = "1"
            }, product);

            _productServiceMock.Verify(m => m.CreateAsync(product));
            Assert.IsInstanceOfType(result, typeof(RedirectToRouteResult));
        }
Exemplo n.º 17
0
        public async Task Cannot_Add_Invalid_Product()
        {
            Product product = new Product()
            {
                CategoryID = 1, Description = "Prod1", ProductID = 1
            };
            var target = new ProductController(_productServiceMock.Object);

            target.ModelState.AddModelError("error", "error");
            var result = await target.Add(new WebUser()
            {
                Id = "1"
            }, product);

            _productServiceMock.Verify(m => m.CreateAsync(product), Times.Never);
            Assert.IsNotInstanceOfType(result, typeof(RedirectToRouteResult));
        }
Exemplo n.º 18
0
        public static void Main(string[] args)
        {
            ProductController controller = new ProductController();

            while (true)
            {
                Console.WriteLine("1. Add product records");
                Console.WriteLine("2. Display product records");
                Console.WriteLine("3. Delete product by Id");
                Console.WriteLine("4. Exit");
                Console.WriteLine("--------------------------------");
                Console.WriteLine("Please enter your choice");
                int choice = Int32.Parse(Console.ReadLine());
                switch (choice)
                {
                case 1:
                    Console.WriteLine("Add product records");
                    controller.Add();
                    break;

                case 2:
                    Console.WriteLine("Display product records");
                    controller.Display();
                    break;

                case 3:
                    Console.WriteLine("Delete product by Id");
                    controller.Delete();
                    break;

                case 4:
                    Console.WriteLine("Exit");
                    break;

                default:
                    Console.WriteLine("Error");
                    break;
                }

                Console.WriteLine("Success.");
            }
        }
Exemplo n.º 19
0
        public void AddActionMethod_ReturnsAViewResult()
        {
            //arrange
            var unit      = new Mock <IUnitOfWork>();
            var products  = new Mock <IGenericRepository <Product> >();
            var customers = new Mock <IGenericRepository <Customer> >();

            unit.Setup(r => r.ProductRepository).Returns(products.Object);
            unit.Setup(r => r.CustomerRepository).Returns(customers.Object);

            var http = new Mock <IHttpContextAccessor>();

            var controller = new ProductController(unit.Object);

            //act
            var result = controller.Add();

            //assert
            Assert.IsType <ViewResult>(result);
        }
Exemplo n.º 20
0
        // Denna metod skapar en ny instans av en Produkt baserat på inputs från användaren.
        // Användarens inputs valideras och sedan skickas produkten till controller- och
        // repository lagret och sparas ned till fil.
        private void BTNAddProduct_Click(object sender, EventArgs e)
        {
            if (IsInputValid())
            {
                if (CheckPriceLimit())
                {
                    Product product = new Product();

                    // Här tas | bort eftersom den används som separator för klassens attributes i
                    // lagringsfilen.
                    // Detta betyder att användaren kan inkludera | i produktens namn, men det kommer
                    // tas bort automatiskt när produkten sparas.
                    product.name = TextBoxName.Text.Replace("|", "");

                    double.TryParse(TextBoxPrice.Text, out double productPrice);
                    product.price       = productPrice;
                    product.productType = (Product.ProductType)ComboBoxProductTypes.SelectedItem;

                    // Om productController återger false var det något problem och produkten sparas då inte.
                    if (productController.Add(product))
                    {
                        MessageBox.Show("Product succesfully added.");
                        Form.ActiveForm.Close();
                    }
                    else
                    {
                        MessageBox.Show("There was a problem adding the product.");
                    }

                    Form.ActiveForm.Close();
                }
                else
                {
                    MessageBox.Show("Max price is 99999");
                }
            }
            else
            {
                MessageBox.Show("Invalid input");
            }
        }
Exemplo n.º 21
0
        public static void GenerateMenu()
        {
            ProductController controller = new ProductController();

            while (true)
            {
                Console.WriteLine("---------WELCOME TO SPRING HERO BANK---------");
                Console.WriteLine("1. Add");
                Console.WriteLine("2. Display");
                Console.WriteLine("3. Delete");
                Console.WriteLine("4. Exit.");
                Console.WriteLine("---------------------------------------------");
                Console.WriteLine("Please enter your choice (1|2|3): ");
                var choice = Utility.GetInt32Number();
                switch (choice)
                {
                case 1:
                    controller.Add();
                    break;

                case 2:
                    controller.Display();
                    break;

                case 3:
                    controller.Delete();
                    break;

                case 4:
                    Console.WriteLine("See you later.");
                    Environment.Exit(1);
                    break;

                default:
                    Console.WriteLine("Invalid choice.");
                    break;
                }
            }
        }
Exemplo n.º 22
0
        protected void Add_Click(object sender, EventArgs e)
        {
            var isValid = Validation(sender, e);

            if (isValid)
            {
                try
                {
                    ProductController sysmgr = new ProductController();
                    Product           item   = new Product();
                    //No ProductID here as the database will give a new one back when we add
                    item.ProductName = Name.Text.Trim();   //NOT NULL in Database
                    if (SupplierList.SelectedValue == "0") //NULL in Database
                    {
                        item.SupplierID = null;
                    }
                    else
                    {
                        item.SupplierID = int.Parse(SupplierList.SelectedValue);
                    }
                    //CategoryID can be NULL in Database but NOT NULL when record is added in this CRUD page
                    item.CategoryID = int.Parse(CategoryList.SelectedValue);
                    //UnitPrice can be NULL in Database but NOT NULL when record is added in this CRUD page
                    item.UnitPrice    = decimal.Parse(UnitPrice.Text);
                    item.Discontinued = Discontinued.Checked; //NOT NULL in Database
                    int newID = sysmgr.Add(item);
                    ID.Text = newID.ToString();
                    ShowMessage("Record has been ADDED", "alert alert-success");
                    AddButton.Enabled    = false;
                    UpdateButton.Enabled = true;
                    DeleteButton.Enabled = true;
                    Discontinued.Enabled = true;
                }
                catch (Exception ex)
                {
                    ShowMessage(GetInnerException(ex).ToString(), "alert alert-danger");
                }
            }
        }
Exemplo n.º 23
0
        public void AddProduct_is_valid()
        {
            ////arrange
            Product p = new Product
            {
                Name        = "Product Tests",
                Description = "detail reference to product",
                Image       = "the url image",
                Price       = 10.25m,
                CategoryId  = Guid.NewGuid()
            };

            ////act
            var addController = new ProductController();
            var actualResult  = addController.Add(p);

            ////assert
            var createdActionResult = actualResult.Should().BeOfType <CreatedAtActionResult>().Subject;
            var actual = createdActionResult.Value.Should().BeAssignableTo <Product>().Subject;

            Assert.NotNull(actual);
        }
Exemplo n.º 24
0
        public static void GenerateMenu()
        {
            Console.WriteLine("--------- Product ----------");
            Console.WriteLine("1. Add product records");
            Console.WriteLine("2. Display product records");
            Console.WriteLine("3. Delete product by Id");
            Console.WriteLine("4. Exit");
            int choice = int.Parse(Console.ReadLine());

            switch (choice)
            {
            case 1:
                controller.Add();
                Console.ReadLine();
                break;

            case 2:
                Display();
                break;

            case 3:
                controller.Delete();
                break;

            case 4:
                Console.WriteLine("Bye bye.");
                break;

            default:
                Console.WriteLine("Invalid choice.");
                break;
            }

            if (choice == 4)
            {
                Environment.Exit(1);
            }
        }
Exemplo n.º 25
0
        public static void GenerateMenu()
        {
            while (true)
            {
                Console.WriteLine("--------- STORE MANAGEMENT ---------");
                Console.WriteLine("1. Add product records.");
                Console.WriteLine("2. Display product records.");
                Console.WriteLine("3. Delete product by Id.");
                Console.WriteLine("4. Exit.");
                Console.WriteLine("---------------------------------------------");
                Console.WriteLine("Please enter your choice (1|2|3|4): ");
                var choice = GetInt32Number();
                switch (choice)
                {
                case 1:
                    controller.Add();
                    break;

                case 2:
                    controller.Display();
                    break;

                case 3:
                    controller.Delete();
                    break;

                case 4:
                    Console.WriteLine("See you later.");
                    Environment.Exit(1);
                    break;

                default:
                    Console.WriteLine("Invalid choice.");
                    break;
                }
            }
        }
Exemplo n.º 26
0
        public static void GenerateMenu()
        {
            Console.WriteLine("Welcome to Product management program");
            while (true)
            {
                Console.WriteLine("********************************************");
                Console.WriteLine("1. Add product records");
                Console.WriteLine("2. Display product records");
                Console.WriteLine("3. Delete product by Id");
                Console.WriteLine("4. Exit");
                Console.WriteLine("Please select an option to continue");
                int choice = Convert.ToInt32(Console.ReadLine());
                switch (choice)
                {
                case 1:
                    controller.Add();
                    break;

                case 2:
                    controller.Display();
                    break;

                case 3:
                    controller.Delete();
                    break;

                case 4:
                    Console.WriteLine("Goodbye.");
                    Environment.Exit(1);
                    break;

                default:
                    Console.WriteLine("Invalid option.");
                    break;
                }
            }
        }
        public async Task AddPost_ReturnsARedirectAndAddsProduct_WhenodelStateIsValid()
        {
            var mockRepo = new Mock <IProductRepository>();

            mockRepo.Setup(repo => repo.AddProductAsync(It.IsAny <Product>())).Returns(Task.CompletedTask).Verifiable();

            var     controller = new ProductController(mockRepo.Object);
            Product p          = new Product()
            {
                Name  = "Widget",
                Price = "9.99"
            };
            var result = await controller.Add(p);

            Assert.IsInstanceOfType(result, typeof(RedirectToActionResult));

            var redirectResult = result as RedirectToActionResult;

            Assert.IsNull(redirectResult.ControllerName, "Controller name should not be specified in the redirect");

            Assert.AreEqual("Index", redirectResult.ActionName);

            mockRepo.Verify();
        }
Exemplo n.º 28
0
 public static String[] Insert(String name, String productTypeID, String price, String qty)
 {
     productController.Add(name, Int32.Parse(productTypeID), Int32.Parse(price), Int32.Parse(qty));
     return(JSONResponse.setMessage("success", "Yeay..", "Product has been added"));
 }
Exemplo n.º 29
0
        private void dataGridViewProducts_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            try
            {
                if (e.RowIndex == -1) //редактрование с второй строки
                {
                    return;
                }
                int taskIndex = dataGridViewProducts.Rows[e.RowIndex].Cells["Операция"].ColumnIndex;

                if (e.ColumnIndex == taskIndex)
                {
                    string task = dataGridViewProducts.Rows[e.RowIndex].Cells["Операция"].Value.ToString();

                    if (task == "Удалить")
                    {
                        if (MessageBox.Show("Удалить эту строку?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                        {
                            int id = (int)dataGridViewProducts.CurrentRow.Cells["ID"].Value;
                            productController.Delete(id);
                        }
                    }
                    else if (task == "Добавить")
                    {
                        int             rowIndex   = dataGridViewProducts.Rows.Count - 2;
                        DataGridViewRow currentRow = dataGridViewProducts.Rows[rowIndex];

                        Product newProduct = GetProductInfo(ref currentRow);
                        if (newProduct == null)
                        {
                            return;
                        }

                        int currentProductId = productController.GetProductIdByName(newProduct.Name);
                        if (currentProductId != 0)
                        {
                            MessageBox.Show("Продукт с введенным названием уже существует.");
                            return;
                        }

                        productController.Add(newProduct);
                        dataGridViewProducts.Rows[e.RowIndex].Cells["Операция"].Value = "Удалить";
                    }
                    else if (task == "Изм.")
                    {
                        int             rowIndex   = e.RowIndex;
                        DataGridViewRow currentRow = dataGridViewProducts.Rows[rowIndex];

                        Product updatedProduct = GetProductInfo(ref currentRow);
                        if (updatedProduct == null)
                        {
                            return;
                        }

                        int currentProductId = productController.GetProductIdByName(updatedProduct.Name);
                        if (updatedProduct.ID != currentProductId && currentProductId != 0)
                        {
                            MessageBox.Show("Продукт с введенным названием уже существует.");
                            return;
                        }

                        productController.Edit(updatedProduct);
                        currentRow.Cells["Операция"].Value = "Удалить";
                    }

                    productController.GetAllProducts(ref dataGridViewProducts);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Ошибка!", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }