如何调用验证属性进行测试?

Cob*_*eek 24 c# validation unit-testing dynamic-data data-annotations

我使用DataAnnotations中的RegularExpressionAttribute进行验证,并希望测试我的正则表达式.有没有办法直接在单元测试中调用属性?

我希望能够做类似的事情:

public class Person
{
    [RegularExpression(@"^[0-9]{3}-[0-9]{3}-[0-9]{4}$")]
    public string PhoneNumber { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

然后在单元测试中:

[TestMethod]
public void PhoneNumberIsValid
{
    var dude = new Person();
    dude.PhoneNumber = "555-867-5309";

    Assert.IsTrue(dude.IsValid);
}
Run Code Online (Sandbox Code Playgroud)

甚至

Assert.IsTrue(dude.PhoneNumber.IsValid);
Run Code Online (Sandbox Code Playgroud)

Cob*_*eek 22

我最终使用DataAnnotations命名空间中的静态Validator类.我的测试现在看起来像这样:

[TestMethod]
public void PhoneNumberIsValid()
{
    var dude = new Person();
    dude.PhoneNumber = "666-978-6410";

    var result = Validator.TryValidateObject(dude, new ValidationContext(dude, null, null), null, true);

    Assert.IsTrue(result);
}
Run Code Online (Sandbox Code Playgroud)

  • 这个解决方案的问题在于它测试了你在该属性上的所有验证器,而不仅仅是正则表达式,所以你不能很好地隔离你的测试用例.您是否考虑过在资源文件或Web配置中将Regex存储在全球可访问的位置?由于您只是想在那时验证您的正则表达式,您可以使用Regex.Match()来单独测试模式. (3认同)
  • 由于您只是尝试验证单个属性,因此您可能需要考虑[`Validator.TryValidateProperty`](https://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.validator.validateproperty %28v = vs.110%29.aspx)方法.假设你的`Person`类实际上不只是一个电话号码. (2认同)

Mar*_*tin 7

刚刚创建一个RegularExpressionAttribute对象.

var regularExpressionAttribute = new RegularExpressionAttribute("pattern");

Assert.IsTrue(regularExpressionAttribute.IsValid(objToTest));
Run Code Online (Sandbox Code Playgroud)