【发布时间】:2016-04-18 09:04:49
【问题描述】:
我在测试我的自定义验证属性时遇到了一些麻烦。由于方法签名是protected,当我在单元测试中调用IsValid 方法时,我无法传入Mock<ValidationContext> 对象,而是调用基类virtual bool IsValid(object value)。
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);
}
如果我无法传入模拟验证上下文,那么如何正确测试这个类?
【问题讨论】:
标签: c# asp.net-mvc unit-testing moq validationattribute