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; }
}
Well, testing it should be pretty easy. For me, using NUnit, its like this:
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):
In the small sample above I call the runner like so:
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.