Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I invoke a validation attribute for testing?

Tags:

I am using the RegularExpressionAttribute from DataAnnotations for validation and would like to test my regex. Is there a way to invoke the attribute directly in a unit test?

I would like to be able to do something similar to this:

public class Person {     [RegularExpression(@"^[0-9]{3}-[0-9]{3}-[0-9]{4}$")]     public string PhoneNumber { get; set; } } 

Then in a unit test:

[TestMethod] public void PhoneNumberIsValid {     var dude = new Person();     dude.PhoneNumber = "555-867-5309";      Assert.IsTrue(dude.IsValid); } 

Or even

Assert.IsTrue(dude.PhoneNumber.IsValid); 
like image 370
CobraGeek Avatar asked Mar 18 '11 16:03

CobraGeek


People also ask

How do I create a custom validation attribute?

To create a custom validation attributeUnder Add New Item, click Class. In the Name box, enter the name of the custom validation attribute class. You can use any name that is not already being used. For example, you can enter the name CustomAttribute.

What are validation attributes?

Validation attributes let you specify the error message to be displayed for invalid input. For example: C# Copy. [StringLength(8, ErrorMessage = "Name length can't be more than 8.")]

Which attribute is used to define custom unit test properties in unit testing?

A simple generic way to test Custom Attributes with NUnit. This test class contains two test methods which are identified by the NUnit [Test] attribute.


1 Answers

I ended up using the static Validator class from the DataAnnotations namespace. My test now looks like this:

[TestMethod] public void PhoneNumberIsValid() {     var dude = new Person();     dude.PhoneNumber = "666-978-6410";      var result = Validator.TryValidateObject(dude, new ValidationContext(dude, null, null), null, true);      Assert.IsTrue(result); } 
like image 133
CobraGeek Avatar answered Sep 29 '22 13:09

CobraGeek