c# - 测试依赖于其他属性的属性的自定义验证会返回 ArgumentNullException

标签 c# unit-testing data-annotations validationattribute

我正在尝试编写 XUnit 测试来测试我的自定义验证器。验证器检查其他属性的值,指示已验证的属性是否应该为空或有值。但是,当我使用 TryValidateProperty 方法时,测试返回 ArgumentNullException。

验证器:

public class ConcatenatedDataValidator : ValidationAttribute
{
    public string PropertyName { get; private set; }
    public ConcatenatedDataValidator(string propertyName)
    {
        this.PropertyName = propertyName;
    }


    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        var property = validationContext.ObjectType.GetProperty(PropertyName);
        if(property == null && value != null)
        {
            return new ValidationResult(string.Format("{0} is null", PropertyName));
        }
        var chosenValue = property.GetValue(validationContext.ObjectInstance, null);

        if(chosenValue.Equals("00") && (value == null || value.Equals(string.Empty))
            ||  chosenValue.Equals("01") && value != null) 
        {
            return new ValidationResult(this.FormatErrorMessage(validationContext.DisplayName));
        }

        return null;
    }  
}

测试:

public class ConcatenatedDataValidatorTests
{
    private TestedModel model;
    private ValidationContext context;
    private List<ValidationResult> results;

    [Fact]
    public void IsValid_OtherValueIs00ThisValueIsNull_ReturnFalse()
    {
        // arrange
        var concatenatedDataValidator = new ConcatenatedDataValidator("OtherProperty");
        model = new TestedModel();
        model.OtherProperty = "00";
        model.ThisProperty = null;
        context = new ValidationContext(model);
        results = new List<ValidationResult>();

        // act
        var result = Validator.TryValidateProperty(model.ThisProperty, context, results);

        // assert
        Assert.False(result);

    }
}

测试返回

System.ArgumentNullException : Value cannot be null. Parameter name: propertyName

在行动部分。我只想测试这一个属性,因为在模型中我有很多具有必需属性的其他属性,并且我希望使测试尽可能简单并仅测试我的自定义验证器。有什么办法可以解决这个问题吗?

最佳答案

这是预期的行为。作为Validator.TryValidateProperty指定如果 valuenull,则抛出 System.ArgumentNullException

如果您想测试此行为/属性值为 null 的情况,那么您应该捕获异常并检查它 - 尽管这基本上是测试 .NET 框架。

这也表明您可以删除 IsValid 方法中的 value == null 检查,因为它永远不会触发。

更新

整个错误是指在 TryValidateProperty 内部调用的私有(private)方法 EnsureValidPropertyType (请参阅 here )。

这是由于ValidationContext.MemberName引起的.

要解决此问题,您必须在创建 ValidationContext 期间设置 MemberName(如果是 .NET 4.7.2 及更早版本)

ValidationContext context = new ValidationContext(model)
{
        MemberName = "ThisProperty"
};

或更改应用配置中的默认行为 (.NET 4.8)。

<configuration>
   <appSettings>
      <add key="aspnet:GetValidationMemberName" value="true" />
   </appSettings>
</configuration>

关于c# - 测试依赖于其他属性的属性的自定义验证会返回 ArgumentNullException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57427245/

相关文章:

c# - Selenium webdriver 窗口处理 c# switchTo 失败

c# - 你使用 NDepend 吗?

javascript - testing-library/react 如何在动态生成错误消息时测试无效输入

c# - 数据注释 - 长类型的范围属性

asp.net-mvc-3 - 如何同步模型和 View 模型之间的数据注释

c# - 在 ASP.net core mvc 3.1 中的 HtmlHelper 扩展方法中使用 DataAnnotation localizer

c# - Java 与 C# 中的 UTF-16 编码

c# - 如何使用 Azure.Storage.Blobs 上传流

java - 测试时使用 spring messagesource

java - 使用 try-with-resource 时调用断言 close