カスタム検証属性のテストに頭を悩ませています。メソッドのシグネチャは、単体テストでメソッドprotected
を呼び出すときであるため、オブジェクトを渡すことはできません。代わりにベースを呼び出しています。IsValid
Mock<ValidationContext>
virtual bool IsValid(object value)
検証属性
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);
}
モックされた検証コンテキストを渡すことができない場合、どうすればこのクラスを適切にテストできますか?