Unit Testing ASP.NET DataAnnotations validation

后端 未结 5 1064
说谎
说谎 2020-12-02 07:28

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

[Required(ErrorMessage="Please enter a name")]
public string Name { get; set; }
5条回答
  •  青春惊慌失措
    2020-12-02 07:36

    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.

    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.

    [EDIT] 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.

提交回复
热议问题