Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Unit Test Data Annotation Validators

I'm implementing the Data Validation Validators as shown here:

http://www.asp.net/learn/mvc/tutorial-39-cs.aspx

This works great at runtime, but how can I Unit Test to verify if I say attribute [StringLength(10)], an error is returned?

like image 815
Keith Adler Avatar asked Aug 02 '09 15:08

Keith Adler


People also ask

How do you validate model data using DataAnnotations attributes?

ComponentModel. DataAnnotations namespace includes the following validator attributes: Range – Enables you to validate whether the value of a property falls between a specified range of values. RegularExpression – Enables you to validate whether the value of a property matches a specified regular expression pattern.

What is System ComponentModel DataAnnotations?

Data annotations (available as part of the System. ComponentModel. DataAnnotations namespace) are attributes that can be applied to classes or class members to specify the relationship between classes, describe how the data is to be displayed in the UI, and specify validation rules.

What is DataAnnotations MVC?

DataAnnotations is used to configure your model classes, which will highlight the most commonly needed configurations. DataAnnotations are also understood by a number of . NET applications, such as ASP.NET MVC, which allows these applications to leverage the same annotations for client-side validations.


2 Answers

Brad Wilson describes it pretty well in a blog post from a while ago (you'll have to scroll down a bit). Basically, you write tests where you use reflection to make sure that the proper attributes are applied, and then trust the framework to do its job on adding errors. After all, someone else tested the Data Annotation Validators before they were published - you just have to make sure you use them right =)

like image 168
Tomas Aschan Avatar answered Oct 21 '22 01:10

Tomas Aschan


This post by Villecoder is the unit testing solution I'm using. It also allows you unit unit test custom annotations

http://villecoder.com/2010/04/23/unit-testing-custom-data-annotations/

like image 29
ActualAl Avatar answered Oct 21 '22 02:10

ActualAl