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

标签 c# validation unit-testing data-annotations dynamic-data

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

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

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

然后在单元测试中:

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

    Assert.IsTrue(dude.IsValid);
}

甚至

Assert.IsTrue(dude.PhoneNumber.IsValid);

最佳答案

我最终使用了来自 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);
}

关于c# - 如何调用验证属性进行测试?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5354894/

相关文章:

css - Visual Studio 2008 CSS 验证级别

angularjs - 使用 AngularJS 进行输入和复选框验证

android - 运行单元测试用例时达到 Multidex 限制

c# - 在 GDI+ 中绘制带渐变的折线

c# - 是否可以结合两个条件

validation - 为什么我们需要对 Web 应用程序进行服务器端和客户端验证?

C#-WPF : testing strategies

java - void 方法的单元测试和断言案例

c# - 从数据库中的对象检索数组或列表

c# - 如何使用 PInvoke 传递图像