I'm using a custom validator on some of my models in a MVC 5 application. This validator has a dependency on a service that is injected via a property with the Ninject.MVC3 package. (See https://github.com/ninject/ninject.web.mvc/wiki/Injection-of-validators)
This is what the validator looks like:
public class StrongPasswordAttribute : ValidationAttribute
{
[Inject]
public IConfigurationProvider Configuration { get; set; }
public override bool IsValid(object value)
{
return Configuration.GetPasswordPolicy().IsValid(value.ToString());
}
}
The injection works fine in the application, but I want to unit test the models that use this validator. This is my usual method of triggering the validation of model:
ValidationContext context = new ValidationContext(model, null, null);
List<ValidationResult> results = new List<ValidationResult>();
bool isValid = Validator.TryValidateObject(model, context, results, true);
At this point it fails because the Configuration property is null.
Is there a way to manually inject a (mocked) object into the attribute for the duration of the test?
In this case I recommend split testing.
First, can write a test, which would test
PasswordPolicyorStrongPasswordAttribute:Second, make sure that some property of model marked with
StrongPasswordAttributeattribute: