简体   繁体   English

是否可以在ASP.NET MVC中对一些AddModelError结果进行单元测试?

[英]Is it possible to unit test some AddModelError results in ASP.NET MVC?

I've got a controller method which returns a RedirectToActionResult (success!) or a ViewResult (failed with error messages). 我有一个控制器方法,它返回RedirectToActionResult (成功!)或ViewResult (失败并显示错误消息)。

If the business logic fails , i add the error messages to the AddModelError property. 如果业务逻辑失败 ,我将错误消息添加到AddModelError属性。

Is there any way i can test this in my MS Unit tests? 有什么方法可以在我的MS单元测试中测试这个吗? I also have Moq, if that helps too. 我也有Moq,如果这也有帮助。 (i don't believe Moq is required for this scenario though) .. I'm not using anything from the Request object. (我不相信这个场景需要Moq)..我没有使用Request对象中的任何东西。

Yep, figured it out. 是的,想通了。

// Arrange.
// .. whatever ..

// Act.
var viewResult = controller.Create(new Post()) as ViewResult;

// Assert.
Assert.IsNotNull(viewResult);
Assert.IsNotNull(viewResult.ViewData.ModelState["subject"]);
Assert.IsNotNull(viewResult.ViewData.ModelState["subject"].Errors);
Assert.IsTrue(viewResult.ViewData.ModelState["subject"].Errors.Count == 1);

You can (also) test the Controller directly (without testing the View) as follows: 您也可以(也)直接测试Controller(不测试View),如下所示:

// Arrange.
// .. 

// Act.
controller.Create(new Post());  // missing UserName will invalidate Model with "Please specify your name" message

// Assert
Assert.IsTrue(! controller.ModelState.IsValid);
Assert.IsTrue(  controller.ModelState["UserName"].Errors.Any( modelError => modelError.ErrorMessage == "Please specify your name"));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM