我在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
。
有没有办法在测试期间手动将(模拟的)对象注入属性?
答案 0 :(得分:1)
在这种情况下,我建议进行拆分测试。
首先,可以编写测试,测试PasswordPolicy
或StrongPasswordAttribute
:
[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)
}