我正在使用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; } }
谢谢!
解决方法
.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,true); Assert.IsTrue(results.Any(vr => vr.ErrorMessage == "Title must be 100 characters or less."));
无需自定义实用程序来搜索属性的存在. Validator类为您的工作,并填充与MVC基础结构相同的ValidationResult集合.
这个方法的一个很好的写法可以在K. Scott Allen’s blog上找到.