【发布时间】:2016-01-13 11:48:27
【问题描述】:
我创建了一个ValidationAttribute,它基本上检查另一个属性是否有值,如果有,则该属性变为可选。鉴于此属性依赖于另一个属性,我如何才能正确地模拟该属性,我假设 ValidationContext
OptionalIfAttribute
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = false)]
public class OptionalIfAttribute : ValidationAttribute
{
#region Constructor
private readonly string otherPropertyName;
public OptionalIfAttribute(string otherPropertyName)
{
this.otherPropertyName = otherPropertyName;
}
#endregion
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("OtherProperty");
var result = attribute.IsValid(null);
Assert.That(result, Is.True);
}
【问题讨论】:
标签: c# asp.net-mvc unit-testing moq