gpt4 book ai didi

asp.net-mvc - 单元测试 Controller

转载 作者:行者123 更新时间:2023-12-01 08:38:59 25 4
gpt4 key购买 nike

我有一个非常简单的场景:

[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 表单,但单元测试失败(它说它重定向到感谢)。为什么是这样?有人能看出有什么不对吗?谢谢!

最佳答案

在您的单元测试中,您应该模拟您的模型有错误,因为这是您要测试的内容(错误路径)。在您的测试中,模型是有效的,这就是为什么它会将您重定向到“谢谢” View 。要模拟错误,您可以在“act”部分之前的单元测试中执行此操作:

UsersController.ModelState.AddModelError("username", "Bad username"); 

看看那个例子: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

关于asp.net-mvc - 单元测试 Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6438527/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com