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

时间:2016-01-13 11:48:27

标签: c# asp.net-mvc unit-testing moq

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

3 个答案:

答案 0 :(得分:2)

在没有具体模型类的情况下测试它:

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

答案 1 :(得分: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 
}

答案 2 :(得分:0)

我正在使用以下代码测试我的自定义验证器类

[TestMethod]
public void IsValid_Test()
{
    var modelObj = new youModelClass {
        requiredProp = value
    };
    var validatorClassObj = new yourValidatorClass();

    var validationResult = validatorClassObj.GetValidationResult( valueToValidate, new ValidationContext( modelObj ) );

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

很高兴知道是否还有其他测试方法。