我正在使用 System.ComponentModel.DataAnnotations.CustomValidationAttribute 来验证我的 POCO 类之一,当我尝试对其进行单元测试时,它甚至没有调用验证方法。
public class Foo
{
[Required]
public string SomethingRequired { get; set }
[CustomValidation(typeof(Foo), "ValidateBar")]
public int? Bar { get; set; }
public string Fark { get; set; }
public static ValidationResult ValidateBar(int? v, ValidationContext context) {
var foo = context.ObjectInstance as Foo;
if(!v.HasValue && String.IsNullOrWhiteSpace(foo.Fark)) {
return new ValidationResult("Either Bar or Fark must have something in them.");
}
return ValidationResult.Success;
}
}
但是当我尝试验证它时:
var foo = new Foo {
SomethingRequired = "okay"
};
var validationContext = new ValidationContext(foo, null, null);
var validationResults = new List<ValidationResult>();
bool isvalid = Validator.TryValidateObject(foo, validationContext, validationResults);
Assert.IsFalse(isvalid); //FAIL!!! It's valid when it shouldn't be!
它甚至从不进入自定义验证方法。是什么赋予了?