I have a custom validator attribute which I am trying to unit test. In my unit test I am doing the following.
var testModel = new TestModel();
var testContext = new ValidationContext(testModel, null, null);
var attribute = new MyCustomAttribute();
attribute.Validate(testModel, testContext);
When calling attribute.Validate it correctly calls my IsValid method but attribute.Validate is void so obviously doesn’t return anything. Any ideas on how I can get a hook into the ValidationResult would be greatly appreciated.
After doing some reading on the ValidationAttribute.Validate Method it looks like if it fails validation it will throw a ValidationException, so this kind of answers my question.
You can invoke the validation the same way MVC does using the ModelValidator. Something like this (your mileage here may vary, can’t remember all the calls off the top of my head, will try to replace with working code later):