使用具有注入依赖关系的验证器的单元测试模型

时间:2013-12-03 19:22:43

标签: c# asp.net-mvc unit-testing ninject ninject.web.mvc

我在MVC 5应用程序中的某些模型上使用自定义验证器。此验证器依赖于通过具有Ninject.MVC3包的属性注入的服务。 (见https://github.com/ninject/ninject.web.mvc/wiki/Injection-of-validators

这就是验证器的样子:

public class StrongPasswordAttribute : ValidationAttribute
{
    [Inject]
    public IConfigurationProvider Configuration { get; set; }

    public override bool IsValid(object value)
    {
        return Configuration.GetPasswordPolicy().IsValid(value.ToString());
    }
}

注入在应用程序中工作正常,但我想对使用此验证器的模型进行单元测试。这是我通常触发model验证的方法:

ValidationContext context = new ValidationContext(model, null, null);
List<ValidationResult> results = new List<ValidationResult>();

bool isValid = Validator.TryValidateObject(model, context, results, true);

此时它失败,因为Configuration属性为null

有没有办法在测试期间手动将(模拟的)对象注入属性?

1 个答案:

答案 0 :(得分:1)

在这种情况下,我建议进行拆分测试。

首先,可以编写测试,测试PasswordPolicyStrongPasswordAttribute

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

其次,确保标有StrongPasswordAttribute属性的模型的某些属性:

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

    bool hasAttribute = // use reflection here
    Assert.IsTrue(hasAttribute)
}