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);
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.
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.")]
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.
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); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With