编程语言
首页 > 编程语言> > c# – 测试覆盖IsValid的ValidationAttribute

c# – 测试覆盖IsValid的ValidationAttribute

作者:互联网

我在测试自定义验证属性时遇到了一些麻烦.由于在我的单元测试中调用IsValid方法时方法签名受到保护,我无法传入Mock< ValidationContext>对象,它调用基础虚拟bool IsValid(对象值).

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

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

解决方法:

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

    Assert.That(isValid, Is.True);
}

private class ValidationTarget
{
    public string X { get; set; }

    [OptionalIf(nameof(X))]
    public string OptionalIfX { get; set; }
}

您可以选择对结果进行断言.

标签:c,unit-testing,asp-net-mvc,moq,validationattribute
来源: https://codeday.me/bug/20190609/1201769.html