MVC的验证单元测试

编程入门 行业动态 更新时间:2024-10-11 13:22:33
本文介绍了MVC的验证单元测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我如何测试我的控制器操作是把正确的错误中的ModelState验证实体时,当我使用DataAnnotation验证的MVC 2 preVIEW 1?

How can I test that my controller action is putting the correct errors in the ModelState when validating an entity, when I'm using DataAnnotation validation in MVC 2 Preview 1?

有些code来说明。首先,动作:

Some code to illustrate. First, the action:

[HttpPost] public ActionResult Index(BlogPost b) { if(ModelState.IsValid) { _blogService.Insert(b); return(View("Success", b)); } return View(b); }

而这里的,我认为应该通过,但是是不是一个失败的单元测试(使用MbUnit的&安培; MOQ):

And here's a failing unit test that I think should be passing but isn't (using MbUnit & Moq):

[Test] public void When_processing_invalid_post_HomeControllerModelState_should_have_at_least_one_error() { // arrange var mockRepository = new Mock<IBlogPostSVC>(); var homeController = new HomeController(mockRepository.Object); // act var p = new BlogPost { Title = "test" }; // date and content should be required homeController.Index(p); // assert Assert.IsTrue(!homeController.ModelState.IsValid); }

我想除了这个问题,的应的我被测试验证,并应在我这种方式来测试它?

I guess in addition to this question, should I be testing validation, and should I be testing it in this way?

推荐答案

的FormCollection 。然后,您可以创建博文自己并调用的UpdateModel(型号,formCollection.ToValueProvider()); 。

Instead of passing in a BlogPost you can also declare the actions parameter as FormCollection. Then you can create the BlogPost yourself and call UpdateModel(model, formCollection.ToValueProvider());.

这将触发验证在的FormCollection 。

[HttpPost] public ActionResult Index(FormCollection form) { var b = new BlogPost(); TryUpdateModel(model, form.ToValueProvider()); if (ModelState.IsValid) { _blogService.Insert(b); return (View("Success", b)); } return View(b); }

只要确保你的测试中的观点各领域增加了一个空值形成要留空。

Just make sure your test adds a null value for every field in the views form that you want to leave empty.

我发现,做这种方式,在code的一些额外的线路费用,让我的单元测试类似于code被调用运行时更紧密地使他们更有价值的方式。您还可以测试,当有人在绑定到int属性控制进入ABC会发生什么。

I found that doing it this way, at the expense of a few extra lines of code, makes my unit tests resemble the way the code gets called at runtime more closely making them more valuable. Also you can test what happens when someone enters "abc" in a control bound to an int property.

更多推荐

MVC的验证单元测试

本文发布于:2023-10-10 21:55:15,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1479862.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:单元测试   MVC

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!