Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/319.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 测试依赖于其他属性的验证属性_C#_Asp.net Mvc_Unit Testing_Moq - Fatal编程技术网

C# 测试依赖于其他属性的验证属性

C# 测试依赖于其他属性的验证属性,c#,asp.net-mvc,unit-testing,moq,C#,Asp.net Mvc,Unit Testing,Moq,我创建了一个ValidationAttribute,它基本上检查另一个属性是否有值,如果有,该属性将成为可选属性。假设此属性依赖于另一个属性,那么如何在ValidationContext OptionalFattribute [AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = false)] public class OptionalIfAttribute : ValidationAttrib

我创建了一个
ValidationAttribute
,它基本上检查另一个属性是否有值,如果有,该属性将成为可选属性。假设此属性依赖于另一个属性,那么如何在
ValidationContext

OptionalFattribute

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

最简单的方法就是这样

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

这将在不使用具体模型类的情况下对其进行测试:

    [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);
    }
[TestMethod]
当两个属性重置时公共无效\u SuccessResult()
{
var mockModel=new Mock();
Setup(m=>m.SomeProperty).Returns(“something”);
var属性=新的OptionalFattribute(“SomeProperty”);
var context=新的ValidationContext(mockModel.Object,null,null);
var result=attribute.IsValid(string.Empty,context);
Assert.AreEqual(ValidationResult.Success,result);
}
[测试方法]
当\u SecondPropertyIsNotSet\u ErrorResult()时公共无效
{
常量字符串应为ErrorMessage=“哇!”;
var mockModel=new Mock();
Setup(m=>m.SomeProperty).Returns((string)null);
var属性=新的OptionalFattribute(“SomeProperty”);
attribute.ErrorMessage=ExpectedErrorMessage;
var context=新的ValidationContext(mockModel.Object,null,null);
var result=attribute.IsValid(string.Empty,context);
Assert.AreEqual(ExpectedErrorMessage、result.ErrorMessage);
}

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

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

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

这是测试模型,而不是验证属性,虽然我知道,但如果没有其他方法,您就无法测试其中一种,当然模仿
验证上下文
也可以。但您的意图是“已经创建了一个uValidationAttribute,该属性基本上检查另一个属性是否有值,如果有,该属性将成为可选属性。”u通过模拟,您将如何证明这一点,因为您从-validationContext.ObjectType和validationContext.ObjectInstance获取对象。请始终思考我的测试给出了什么。。。。