我正在尝试在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有什么变化吗?
提前致谢!
答案 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"]);