Question

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?

Was it helpful?

Solution

In this case I recommend split testing.

First, can write a test, which would test PasswordPolicy or StrongPasswordAttribute:

[Test]
public void PasswordPolicy_should_reject_short_passwords()
{
   PasswordPolicy policy = new PasswordPolicy();
   bool result = policy.Validate("pwd");
   Assert.IsFalse(result);
}

Second, make sure that some property of model marked with StrongPasswordAttribute attribute:

[Test]
public void Password_in_SomeModel_should_be_marked_StrongPasswordAttribute()
{
    Type type = typeof(SomeModel);

    bool hasAttribute = // use reflection here
    Assert.IsTrue(hasAttribute)
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top