TDD:什么是ASP.NET MVC 3测试DataAnnotations最佳做法? [英] TDD: What is best practice to test DataAnnotations in ASP.NET MVC 3?

查看:198
本文介绍了TDD:什么是ASP.NET MVC 3测试DataAnnotations最佳做法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用ASP.NET MVC 3和DataAnnotations参与的项目。我们拥有的ViewModels类DataAnnotations。

I'm participating in a project using ASP.NET MVC 3 and DataAnnotations. We have DataAnnotations in ViewModels classes.

你怎么写这些验证单元测试?

How do you write unit tests for these validations?

视图模型的例子:

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框架提供了<一个href=\"http://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.validator.aspx\">Validator类可以行使孤立的验证逻辑。在code测试可能看起来像这样:

The .NET framework comes with a Validator class which can exercise your validation logic in isolation. The code to test could look like this:

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类做的工作对你和填充的ValidationResult集合一样的MVC架构。

No need for custom utilities to search for the existance of attributes. The Validator class does the work for you and populates a ValidationResult collection the same as the MVC infrastructure.

在这种方法一个很好的书面记录可以在<一个找到href=\"http://odeto$c$c.com/Blogs/scott/archive/2011/06/29/manual-validation-with-data-annotations.aspx\">K.斯科特·艾伦的博客。

A good writeup on this method can be found on K. Scott Allen's blog.

这篇关于TDD:什么是ASP.NET MVC 3测试DataAnnotations最佳做法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆