I have a custom attribute named: requiredIf. This attribute is related to a custom DataAnnotationsModelValidator, named RequiredIfValidator.
I declare this mapping in file Global.asax.cs :
DataAnnotationsModelValidatorProvider.RegisterAdapter( typeof( RequiredIfAttribute ), typeof( RequiredIfValidator ) );
On runtime it works fine :)
But I want to test via a unit test the validation of my model. Guess than we have the following
public class MyModel
{
public bool A {get;set;}
[RequiredIf ("A", true)]
public bool? B {get;set;}
}
This model is valid when A is false, and when A is true B need to set to true or false.
I try to test this validation with the following Unit Test:
var viewModel = new MyModel();
var context = new ValidationContext( viewModel, null, null );
var results = new List<ValidationResult>();
viewModel.A = false;
var isModelStateValid = Validator.TryValidateObject( viewModel, context, results, true );
Assert.IsFalse( isModelStateValid );
And the assertion failed. It's logic because my RequiredIfValidator is not setted. So my question is how can I set this custom validator to run my Unit Test?
Thanks,