【问题标题】:Testing ValidationAttribute that overrides IsValid测试覆盖 IsValid 的 ValidationAttribute
【发布时间】:2016-04-18 09:04:49
【问题描述】:

我在测试我的自定义验证属性时遇到了一些麻烦。由于方法签名是protected,当我在单元测试中调用IsValid 方法时,我无法传入Mock<ValidationContext> 对象,而是调用基类virtual bool IsValid(object value)

ValidationAttribute

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);
}

如果我无法传入模拟验证上下文,那么如何正确测试这个类?

【问题讨论】:

    标签: c# asp.net-mvc unit-testing moq validationattribute


    【解决方案1】:

    您可以使用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; }
    }
    

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

    【讨论】:

    • 这实际上是我最终做的,但忘了把答案放在这里。
    • 你应该在Validator.TryValidateObject中设置validateAllProperties arg,否则它不会检查属性,var isValid = Validator.TryValidateObject(target, context, results, true);
    • 感谢@FeiyuZhou,没有 validateAllProperties = true 它不会验证我的自定义属性并且每次都返回 IsValid = true。
    猜你喜欢
    • 2016-12-15
    • 1970-01-01
    • 1970-01-01
    • 2012-11-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多