vendredi 6 mai 2016

Moq unit test not working properly in ASP.NET MVC

I am developing and ASP.NET MVC project. In my project, I am doing unit testing. I am using Moq to mock my business logic. But I am having a problem with unit test. Please see my scenario below.

This is the action of controller that I am testing

public ActionResult Edit(int id)
        {
            if(id==0)
            {
                return new HttpStatusCodeResult(400);
            }
            Area area = areaRepo.Area(id);
            if(area==null)
            {
                return HttpNotFound();
            }
            CreateAreaVM model = new CreateAreaVM
            {
                Id = area.Id,
                Name = area.Name,
                MmName = area.MmName,
                RegionId = area.RegionId,
                RegionSelectItems = regionRepo.RegionSelectItems(area.RegionId,"choose region",Lang.EN)
            };
            return View("Create",model);
        }

This is my test method

 [TestMethod]
        public void Cannot_Edit_If_Invalid_Area()
        {
            Area[] areas = new Area[]{
                new Area{
                    Id = 1,
                    Name = "test 1"
                },
                new Area{
                    Id = 2,
                    Name = "test 2"
                },
                new Area{
                    Id = 3,
                    Name = "test 3"
                }
            };
            Mock<IAreaRepo> mock = new Mock<IAreaRepo>();
            mock.Setup(m => m.Area(It.IsAny<int>())).Returns<int>((x) => areas.Where(e=>e.Id==x).FirstOrDefault());
            AreaController controller = new AreaController(mock.Object, null);
            var anonymousView = controller.Edit(4);
            Assert.IsNotInstanceOfType(anonymousView, typeof(HttpNotFoundResult));
        }

As you can see in test method code, if I passed invalid id to action, the test should be passed because I am testing cannot edit if invalid area entity. But the test is always fail because instance is ViewResult. I mean area is always valid even if I passed invalid id to action. So please why is that? How can I fix it please? Please explain me about it. Thanks.

Aucun commentaire:

Enregistrer un commentaire