测试覆盖 IsValid 的 ValidationAttribute

Testing ValidationAttribute that overrides IsValid

我在测试自定义验证属性时遇到了一些麻烦。由于方法签名是 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);
}

如果我无法传入模拟验证上下文,那么我该如何正确测试此 class?

您可以使用Validator class to perform the validation manually without having to mock anything. There is a brief article on it 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; }
}

您可以选择对 results 进行断言。