MVC的验证单元测试 [英] Unit tests on MVC validation

查看:112
本文介绍了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的验证单元测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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