7

我正在使用 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!

它甚至从不进入自定义验证方法。是什么赋予了?

4

1 回答 1

8

Try using the overload that takes a bool that specifies if all properties should be validated. Pass true for the last parameter.

public static bool TryValidateObject(
    Object instance,
    ValidationContext validationContext,
    ICollection<ValidationResult> validationResults,
    bool validateAllProperties
)

If you pass false or omit the validateAllProperties, only the RequiredAttribute will be checked. Here is the MSDN documentation.

于 2012-04-15T19:16:23.983 回答