2011-06-22 252 views
3

我有一个非常简单的场景:单元测试控制器

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

回答

7

在你的单元测试中,你应该模拟你的模型有错误,因为它是你想测试的(错误路径)。在您的测试中,模型是有效的,这就是为什么它将您重定向到“谢谢”视图。为了模拟,你可以在“行为”部分之前,做在你的单元测试错误:

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

+0

我刚刚看了这样的事情在这里:http://www.thepursuitofquality.com/post/53/how-to-test-modelstateisvalid- in-aspnet-mvc.html我不得不承认我并不完全理解。基本上我不需要创建一个无效的视图模型,只需添加此错误来测试控制器是否适当地作出反应。这是正确的吗?但是,我如何测试控制器能否正确处理无效视图模型?谢谢。 – cs0815

+1

你想测试的是你行动中的逻辑。 ModelState.IsValid == true的一个单元测试,以及ModelState.IsValid == false时的另一个单元测试。对于第二个测试,您应该模拟模型中存在错误。当应用程序运行时,模型的验证发生在执行您的操作之前。你在单元测试中没有这个验证,因为你没有运行所有的ASP.NET MVC框架。这就是为什么你应该模拟模型中的一个错误,以便只测试你的逻辑。 ASP.NET MVC团队已经测试了验证管道。 –

3

我beleive您将姓氏的DataAnnotations用于空,因此将由ModelBinder执行验证。 单元测试将跳过ModelBinder并验证。

有关详细信息,请参阅本SO question - 调用的UpdateModel控制器上的手动

+0

是的,我正在使用DataAnnotations。我看不到如何在测试中调用UpdateModel。你是这个意思吗? – cs0815

+0

验证将由ModelBinder执行,因此如果您调用updatemodel - validaion将在您的视图模型上执行并且相应的错误将被添加到模型中。 – swapneel