Well, testing it should be pretty easy. For me, using NUnit, its like this:
[Test]
[ExpectedException(typeof(RulesException))]
public void Cannot_Save_Large_Data_In_Color()
{
var scheme = ColorScheme.Create();
scheme.Color1 = "1234567890ABCDEF";
scheme.Validate();
Assert.Fail("Should have thrown a DataValidationException.");
}
This assumes you have a validation runner for DataAnnotations already built and a way to call it. If you don't here is a really simplistic one I use for testing (which I nicked from Steve Sanderson's blog):
internal static class DataAnnotationsValidationRunner
{
public static IEnumerable<ErrorInfo> GetErrors(object instance)
{
return from prop in TypeDescriptor.GetProperties(instance).Cast<PropertyDescriptor>()
from attribute in prop.Attributes.OfType<ValidationAttribute>()
where !attribute.IsValid(prop.GetValue(instance))
select new ErrorInfo(prop.Name, attribute.FormatErrorMessage(string.Empty), instance);
}
}
In the small sample above I call the runner like so:
public class ColorScheme
{
[Required]
[StringLength(6)]
public string Color1 {get; set; }
public void Validate()
{
var errors = DataAnnotationsValidationRunner.GetErrors(this);
if(errors.Any())
throw new RulesException(errors);
}
}
This is all overly simplistic but works. A better solution when using MVC is the Mvc.DataAnnotions model binder which you can get from codeplex. Its easy enough to build your own modelbinder from DefaultModelBinder, but no need to bother since its already been done.
Hope this helps.
PS. Also found this site which has some sample unit tests working with DataAnnotations.