5
我使用System.ComponentModel.DataAnnotations.CustomValidationAttribute來驗證我的POCO類之一,當我嘗試單元測試時,它甚至沒有調用驗證方法。CustomValidationAttribute指定的方法不被調用
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!
它甚至從來沒有步入自定義驗證方法。是什麼賦予了?
就是這樣。謝謝。 – 2012-04-15 20:41:12