我有一个非常简单的场景:单元测试控制器
[HttpGet]
public ActionResult CreateUser()
{
return View();
}
[HttpGet]
public ActionResult Thanks()
{
return View();
}
[HttpPost]
public ActionResult CreateUser(CreateUserViewModel CreateUserViewModel)
{
if (ModelState.IsValid)
{
return View("Thanks");
}
return View(CreateUserViewModel);
}
我的单元测试使用从MVC的contrib的testhelper:
[Test]
public void UserController_CannotCreateUserWithNoLastName()
{
// arrange
UsersController UsersController = new UsersController();
CreateUserViewModel CreateUserViewModel = new CreateUserViewModel();
CreateUserViewModel.LastName = "";
// act
ActionResult result = UsersController.CreateUser(CreateUserViewModel);
// assert
result.AssertViewRendered().ForView("CreateUser");
}
当我打开浏览器,并尝试提交无效用户(没有姓氏)它重定向到createuser表单,但单元测试失败(它说它重定向到谢谢)。为什么是这样?任何人都可以看到任何错谢谢!
我刚刚看了这样的事情在这里:http://www.thepursuitofquality.com/post/53/how-to-test-modelstateisvalid- in-aspnet-mvc.html我不得不承认我并不完全理解。基本上我不需要创建一个无效的视图模型,只需添加此错误来测试控制器是否适当地作出反应。这是正确的吗?但是,我如何测试控制器能否正确处理无效视图模型?谢谢。 – cs0815
你想测试的是你行动中的逻辑。 ModelState.IsValid == true的一个单元测试,以及ModelState.IsValid == false时的另一个单元测试。对于第二个测试,您应该模拟模型中存在错误。当应用程序运行时,模型的验证发生在执行您的操作之前。你在单元测试中没有这个验证,因为你没有运行所有的ASP.NET MVC框架。这就是为什么你应该模拟模型中的一个错误,以便只测试你的逻辑。 ASP.NET MVC团队已经测试了验证管道。 –