简体   繁体   中英

How to compare viewmodel and dependency in unit testing?

Below is the code of my method :-

   [HttpPost]
   public ActionResult Index(productViewModel model)
   {
       if (model != null)
       {             
           return PartialView("_ProductGrid", GetProduct(model));
       }
       else
       {
           return RedirectToAction("Index", "Product");
       }
   }

And Below is code for unit testing method (in C#,MVC) :-

    [TestMethod]
    public void Index_WithModel_PostTest()
    {
        //Arrange
        ProductController controller = new ProductController();

        var model = new productViewModel()
        {
            Name="product1",
            Description="desc"
        };


        //Act
        PartialViewResult actual = controller.Index(model) as PartialViewResult;                       

        if (actual != null)
        {
            var viewmodel = (productViewModel)((ViewResultBase)(actual)).Model;

            int matches = _productService.GetDeals("", model.Description).Count +
                          _productService.GetInsurance("", model.Description).Count +
                          _productService.GetCategory("", model.Description).Count;


            //Assert
            Assert.IsNotNull(actual);
            Assert.IsInstanceOfType(actual, typeof(PartialViewResult));
            Assert.IsInstanceOfType(viewmodel, typeof(productViewModel));
            Assert.AreEqual("_ProductGrid", actual.ViewName);

            Assert.AreEqual(matches, viewmodel.Products.Count());
        }
    }

you can see on the below part of the method is that i am fetching the Products from all of the 3 methods. But all of those 3 methods are the ProductService dependency.And i want to know that should I mock that condition ? Or i can do in some other way ? I want to Assert the count of matches variable and the actual.Product.Count .

i think the essence of unit testing is to take advantage of separation of concerns. U should use moq to create a mock data accessed by a created repository and call that repository in the controller and then pass it to the unit testing.the essence of separation of concerns and unit testing is to be able to test each layer separately.Browse on MOQ

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM