我在测试自定义验证属性时遇到了一些麻烦。由于方法签名是 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);
}
如果我无法传入模拟验证上下文,那么我该如何正确测试此类?
最佳答案
您可以使用 Validator
类来手动执行验证,而无需模拟任何东西。上面有一篇简短的文章here .我可能会做类似的事情
[Test]
public void Should_BeValid_WhenPropertyIsNullAndOtherPropertyIsNull()
{
var target = new ValidationTarget();
var context = new ValidationContext(target);
var results = new List<ValidationResult>();
var isValid = Validator.TryValidateObject(target, context, results, true);
Assert.That(isValid, Is.True);
}
private class ValidationTarget
{
public string X { get; set; }
[OptionalIf(nameof(X))]
public string OptionalIfX { get; set; }
}
您可以选择对结果
进行断言。
关于c# - 测试覆盖 IsValid 的 ValidationAttribute,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34765859/