数据注释的单元测试

时间:2013-01-22 06:46:42

标签: unit-testing data-annotations

我为模型添加了数据注释,找到了代码,

public class DownloadInfo
{
    [Required]
    public string Name { get; set; }

    [Required]
    [Email]
    public string Email { get; set; }
} 

我想通过提供如下无效的电子邮件ID来为此数据注释编写单元测试。

    [Test]
    public void InvalidTestPost()
    {
        TestControllerBuilder builder = new TestControllerBuilder();
        DownloadController downloadController = builder.CreateController<DownloadController>();

        DownloadInfo downloadInfo = new DownloadInfo();
        downloadInfo.Email= "some invaild email";

        Assert.IsTrue(!downloadController.ModelState.IsValid);
    }

我如何对数据注释进行单元测试?

此致 KARTHIK。

1 个答案:

答案 0 :(得分:0)

一个显而易见的老问题,但这是一个答案,以防任何人看起来不动。

using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.ComponentModel.DataAnnotations;
using DataAnnotationsTesting;

namespace UnitTest
{
    [TestClass]
    public class OurDataValidationClassShould
    {
        [TestMethod]
        public void ReturnAnErrorIfAnEmailIsInvalid()
        {
            DownloadInfo downloadInfo = new DownloadInfo()
            {
                Email = "Invalid Email",
                Name = "Name"
            };

            Validator.ValidateObject(downloadInfo, new ValidationContext(downloadInfo, null, null) { MemberName = "Email" });
        }
    }
}