我在测试我的自定义验证属性时遇到了一些麻烦。由于方法签名是protected
当我IsValid
在单元测试中调用方法时,我不能传入Mock<ValidationContext>
对象,而是调用基virtual bool IsValid(object value)
类。
验证属性
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
var otherPropertyInfo = validationContext.ObjectType.GetProperty(this.otherPropertyName);
var otherPropertyValue = otherPropertyInfo.GetValue(validationContext.ObjectInstance, null);
if (value != null)
{
if (otherPropertyValue == null)
{
return new ValidationResult(FormatErrorMessage(this.ErrorMessage));
}
}
return ValidationResult.Success;
}
测试
[Test]
public void Should_BeValid_WhenPropertyIsNullAndOtherPropertyIsNull()
{
var attribute = new OptionalIfAttribute("test");
var result = attribute.IsValid(null);
Assert.That(result, Is.True);
}
如果我无法通过模拟验证上下文,那么我该如何正确测试这个类?