我正在尝试编写 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
指定如果 value
为 null
,则抛出 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/