.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."));
无需自定义实用程序来搜索属性的存在。Validator 类为您完成工作并填充与 MVC 基础结构相同的 ValidationResult 集合。
可以在K. Scott Allen 的博客上找到有关此方法的优秀文章。