单元测试ASP.NET DataAnnotations验证 [英] Unit Testing ASP.NET DataAnnotations validation

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

问题描述

我使用DataAnnotations我的模型验证即

I am using DataAnnotations for my model validation i.e.

    [Required(ErrorMessage="Please enter a name")]
    public string Name { get; set; }

在我的控制器我检查ModelState中的价值。这是正确返回false从我的观点贴无效的模型数据。

In my controller I am checking the value of ModelState. This is correctly returning false for invalid model data posted from my view.

但是,在执行我的控制器操作的单元测试时,总的ModelState返回true:

However, when executing the unit test of my controller action, ModelState always returns true:

    [TestMethod]
    public void Submitting_Empty_Shipping_Details_Displays_Default_View_With_Error()
    {
        // Arrange
        CartController controller = new CartController(null, null);
        Cart cart = new Cart();
        cart.AddItem(new Product(), 1);

        // Act
        var result = controller.CheckOut(cart, new ShippingDetails() { Name = "" });

        // Assert
        Assert.IsTrue(string.IsNullOrEmpty(result.ViewName));
        Assert.IsFalse(result.ViewData.ModelState.IsValid);
    }

我需要做任何额外的东西来建立模型验证在我的测试?

Do I need to do anything extra to set up the model validation in my tests?

谢谢,

推荐答案

确认将由 ModelBinder的执行。在这个例子中,在构造 ShippingDetails 自己,这将跳过 ModelBinder的,因此,完全验证。注意输入验证和模型验证之间的区别。输入验证以确保用户提供的一些数据,因为他不得不这样做的机会。如果你提供了一个形式不相关的领域,相关的验证器将不会被调用。

Validation will be performed by the ModelBinder. In the example, you construct the ShippingDetails yourself, which will skip the ModelBinder and thus, validation entirely. Note the difference between input validation and model validation. Input validation is to make sure the user provided some data, given he had the chance to do so. If you provide a form without the associated field, the associated validator won't be invoked.

有一直在模型验证与输入验证在MVC2的变化,所以确切的行为取决于您所使用的版本。见<一href=\"http://bradwilson.typepad.com/blog/2010/01/input-validation-vs-model-validation-in-aspnet-mvc.html\">http://bradwilson.typepad.com/blog/2010/01/input-validation-vs-model-validation-in-aspnet-mvc.html了解有关这两个MVC和MVC 2。关于这个细节

There have been changes in MVC2 on model validation vs. input validation, so the exact behaviour depends on the version you are using. See http://bradwilson.typepad.com/blog/2010/01/input-validation-vs-model-validation-in-aspnet-mvc.html for details on this regarding both MVC and MVC 2.

我想最干净的解决方案是通过提供一个定制的模拟 ValueProvider 的UpdateModel 在控制器code>。这应该火验证,并设置的ModelState 正确。

I guess the cleanest solution to this is to call UpdateModel on the Controller manually when testing by providing a custom mock ValueProvider. That should fire validation and set the ModelState correctly.

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

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