tags:

views:

135

answers:

1
+1  Q: 

xVal testing

Does anyone know how to generate a test for the xVal, or more the the point the DataAnnotations attributes

Here is some same code that I would like to test

[MetadataType(typeof(CategoryValidation))] public partial class Category : CustomValidation { }

public class CategoryValidation
{
    [Required]
    public string CategoryId { get; set; }

    [Required]
    public string Name { get; set; }

    [Required]
    [StringLength(4)]
    public string CostCode { get; set; }

}
+2  A: 

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.

Sailing Judo