Ygo*_*maz 15 tdd asp.net-mvc unit-testing data-annotations
我正在使用ASP.NET MVC 3和DataAnnotations参与一个项目.我们在ViewModels类中有DataAnnotations.
你如何为这些验证编写单元测试?
ViewModel示例:
public class AchievementVM
{
[Required(ErrorMessage = "The title field is required.")]
[StringLength(100, ErrorMessage = "Title must be 100 characters or less.")]
public string Title { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
谢谢!
Phi*_*son 16
.NET框架附带一个Validator类,可以单独执行验证逻辑.要测试的代码可能如下所示:
var achievement = new AchievementVM();
var context = new ValidationContext(achievement,
serviceProvider: null, items: null);
var results = new List<ValidationResult>();
var isValid = Validator.TryValidateObject(achievement, context, results, true);
Assert.IsTrue(results.Any(vr => vr.ErrorMessage == "The title field is required."));
achievement.Title = "Really really long title that violates "
+ "the range constraint and should not be accepted as "
+ "valid input if this has been done correctly.";
Validator.TryValidateObject(achievement, context, results, true);
Assert.IsTrue(results.Any(vr => vr.ErrorMessage == "Title must be 100 characters or less."));
Run Code Online (Sandbox Code Playgroud)
无需自定义实用程序来搜索属性的存在.Validator类为您完成工作,并且与MVC基础结构一样填充ValidationResult集合.
关于这种方法的好文章可以在K. Scott Allen的博客上找到.
| 归档时间: |
|
| 查看次数: |
3802 次 |
| 最近记录: |