单元测试控制器 [英] unit testing controller

查看:118
本文介绍了单元测试控制器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a very simple scenario:

[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:

My unit test uses the testhelper from mvc contrib:

[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形式,但单元测试失败(它说,它重定向到感谢)。为什么是这样?任何人都可以看到什么错?谢谢!

When I open the browser and try to submit an invalid user (no lastname) it redirects to the createuser form but the unit test fails (it says that it redirects to thanks). Why is this? Can anyone see anything wrong? Thanks!

推荐答案

在你的单元测试,你应该模拟你的模型有一个错误,因为这是你想要测试(错误路径)是什么。在测试的模型是有效的,这就是为什么它重定向你的谢谢的看法。为了模拟你可以在行为部分之前做,在你的单元测试错误:

Inside your unit test you should simulate that your model has an error because it's what you want to test (the error path). In your test the model is valid that's why it redirects you to the "Thanks" view. To simulate the error you can do that in your unit test before "act" section :

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

就以这个例子来看看:<一href=\"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方法在这里:<一href=\"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

More about AddModelError method here : http://msdn.microsoft.com/en-us/library/system.web.mvc.modelstatedictionary.addmodelerror.aspx

这篇关于单元测试控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆