gpt4 book ai didi

c# - 测试覆盖 IsValid 的 ValidationAttribute

转载 作者:太空狗 更新时间:2023-10-29 23:13:30 26 4
gpt4 key购买 nike

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

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com