测试依赖于另一个属性的验证属性

问题描述:

我创建了一个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); 
} 

此测试中,它没有一个具体的模型类:

[TestMethod] 
    public void When_BothPropertiesAreSet_SuccessResult() 
    { 
     var mockModel = new Mock<ISomeModel>(); 
     mockModel.Setup(m => m.SomeProperty).Returns("something"); 
     var attribute = new OptionalIfAttribute("SomeProperty"); 
     var context = new ValidationContext(mockModel.Object, null, null); 

     var result = attribute.IsValid(string.Empty, context); 

     Assert.AreEqual(ValidationResult.Success, result); 
    } 

    [TestMethod] 
    public void When_SecondPropertyIsNotSet_ErrorResult() 
    { 
     const string ExpectedErrorMessage = "Whoops!"; 

     var mockModel = new Mock<ISomeModel>(); 
     mockModel.Setup(m => m.SomeProperty).Returns((string)null); 
     var attribute = new OptionalIfAttribute("SomeProperty"); 
     attribute.ErrorMessage = ExpectedErrorMessage; 
     var context = new ValidationContext(mockModel.Object, null, null); 

     var result = attribute.IsValid(string.Empty, context); 

     Assert.AreEqual(ExpectedErrorMessage, result.ErrorMessage); 
    } 

最简单的事情要做的事情就是这样,

[Test] 
public void Should_BeValid_WhenPropertyIsNullAndOtherPropertyIsNull() 
{ 
    var attribute = new OptionalIfAttribute("OtherProperty"); 
    //********************** 
    var model = new testModel;//your model that you want to test the validation against 
    var context = new ValidationContext(testModel, null, null); 
    var result = attribute.IsValid(testModel, context); 

    Assert.That(result.Count == 0, Is.True); //is valid or Count > 0 not valid 
} 
+0

这是测试模型并没有验证属性虽然 – ediblecode

+0

我知道,但你无法测试一个没有其他, –

+0

当然嘲讽'ValidationContext'将使那好吧。 – ediblecode