我有一个非常简单的场景:
[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 表单,但单元测试失败(它说它重定向到感谢)。为什么是这样?谁能看出有什么问题吗?谢谢!
在单元测试中,您应该模拟模型有错误,因为这是您想要测试的内容(错误路径)。在您的测试中,模型是有效的,这就是它将您重定向到“谢谢”视图的原因。要模拟错误,您可以在“act”部分之前的单元测试中执行此操作:
UsersController.ModelState.AddModelError("username", "Bad username");
看看那个例子:http://www.thepursuitofquality.com/post/53/how-to-test-modelstateisvalid-in-aspnet-mvc.html http://www.thepursuitofquality.com/post/53/how-to-test-modelstateisvalid-in-aspnet-mvc.html
有关 AddModelError 方法的更多信息请参见此处:http://msdn.microsoft.com/en-us/library/system.web.mvc.modelstatedictionary.addmodelerror.aspx http://msdn.microsoft.com/en-us/library/system.web.mvc.modelstatedictionary.addmodelerror.aspx
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)