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)
刚刚创建一个RegularExpressionAttribute对象.
var regularExpressionAttribute = new RegularExpressionAttribute("pattern");
Assert.IsTrue(regularExpressionAttribute.IsValid(objToTest));
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
8725 次 |
最近记录: |