2016-01-13 146 views
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); 
} 

回答

1

此測試中,它沒有一個具體的模型類:

[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); 
    } 
0

最簡單的事情要做的事情就是這樣,

[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