单元测试MVC 4 RedirectToAction

时间:2012-09-19 21:48:03

标签: unit-testing asp.net-mvc-4 asp.net-4.5

我正在尝试在MVC 4 .Net 4.5中对我的控制器的重定向进行单元测试。这是一个例子:

    [TestMethod]
    public void Register_PassValidModel_RedirectToHomeIndexShouldBeTrue()
    {
        //Arrange
        var registerModel = new RegisterModel
        {
            Email = "validEmailAddress@domain.com",
            Password = "password"
        };

        //Assign
        var result = _controller.Register(registerModel) as RedirectToRouteResult;

        //Assert
        result.RouteValues["Action"].ShouldBeEqual("Index");
        result.RouteValues["Controller"].ShouldBeEqual("Home");
    }

这是控制器:

    [HttpPost]
    public ActionResult Register(RegisterModel model)
    {
         if (ModelState.IsValid)
        {
            var userToRegister = new User { Email = model.Email, Password = model.Password };
            var service = new UserService(_userRepository);

            User user = service.RegisterUser(userToRegister);

            if (user.UserErrorMessages.Count != 0)
            {
                user.UserErrorMessages.ForEach(x => ModelState.AddModelError("", x));
                return View(model);
            }

            SetCookie(model.Email);

            return RedirectToAction("Index", "Home");
        }
        return View(model);
    }

单元测试中变量result的问题是null。我从一个正在研究MVC 2项目的人那里找到了这个代码,它似乎对他有用。 MVC 4有什么变化吗?

提前致谢!

1 个答案:

答案 0 :(得分:31)

试试这个希望它对你有用

 var result= (RedirectToRouteResult)controller.Register(registrModel);

           result.RouteValues["action"].Equals("Index");
           result.RouteValues["controller"].Equals("Home");

           Assert.AreEqual("Index", action.RouteValues["action"]);
           Assert.AreEqual("Home", action.RouteValues["controller"]);