加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net-mvc – TDD:在ASP.NET MVC 3中测试DataAnnotations的最

发布时间:2020-12-15 23:31:17 所属栏目:asp.Net 来源:网络整理
导读:我正在使用ASP.NET MVC 3和DataAnnotations参与项目.我们在ViewModels类中有DataAnnotations. 您如何为这些验证编写单元测试? ViewModel示例: public class AchievementVM{ [Required(ErrorMessage = "The title field is required.")] [StringLength(100,
我正在使用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上找到.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读