【发布时间】:2019-12-17 00:42:37
【问题描述】:
我正在尝试编写一个 XUnit 测试来测试我的自定义验证器。验证器检查其他属性的值,该值指示已验证的属性是否应该为 null 或具有值。但是,当我使用 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
在表演部分。我只想测试这一个属性,因为在模型中我有很多其他属性需要属性,我希望让测试尽可能简单,只测试我的自定义验证器。有什么办法可以解决这个问题吗?
【问题讨论】:
标签: c# unit-testing data-annotations validationattribute