0
我創建了一個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);
}
這是測試模型並沒有驗證屬性雖然 – ediblecode
我知道,但你無法測試一個沒有其他, –
當然嘲諷'ValidationContext'將使那好吧。 – ediblecode