Jus*_*vey 4 c# asp.net-mvc unit-testing code-first
在我的单元测试中,我想强制验证代码首先在其上有DataAnnotations的POCO.
MVC框架必须在幕后进行,基本上我想知道如何,所以我希望能够使用它.
MVC框架正在幕后进行,基本上我想知道如何,所以我希望能够利用它.
它是默认的模型绑定器,负责在模型与请求值绑定后调用模型的验证.
您可以使用a手动调用验证过程ValidationContext.
我们假设您有一个模型:
public class Foo
{
[Required(ErrorMessage = "the Bar is absolutely required")]
public string Bar { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
然后你可以对它进行单元测试:
[TestMethod]
public void The_Bar_Is_Required()
{
// arrange
var foo = new Foo();
var results = new List<ValidationResult>();
var context = new ValidationContext(foo, null, null);
// act
var actual = Validator.TryValidateObject(foo, context, results);
// assert
Assert.IsFalse(actual);
}
Run Code Online (Sandbox Code Playgroud)
或者使用DataAnnotations,您可以使用FluentValidation.NET对视图模型执行验证.它与ASP.NET MVC很好地集成,它允许您以非常优雅的方式对验证器进行单元测试.
| 归档时间: |
|
| 查看次数: |
421 次 |
| 最近记录: |