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

5 c# tdd unit-testing data-annotations

其中两个类属性具有以下注释:

    [Key]
    [Column]
    [Required]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }


    [MaxLength(25)]
    public string Name { get; set; }
Run Code Online (Sandbox Code Playgroud)

我知道测试Key,Column和Required属性不再是单元测试,它是一个集成测试,因为它依赖于底层数据库,但是你如何测试MaxLength(25)属性呢?

我能想到的其中一个替代方案是在属性中添加代码契约.

更新

正如所建议的那样,我写了以下帮助:

    public class AttributeHelper <T> where T : class
    {
        private Type GivenClass 
        { 
            get { return typeof (T); }
        }

        public bool HasAnnotation(Type annotation)
        {
            return GivenClass.GetCustomAttributes(annotation, true).Single() != null;
        }

        public bool MethodHasAttribute(Type attribute, string target)
        {
           return GivenClass.GetMethod(target).GetCustomAttributes(attribute, true).Count() == 1;
        }

        public bool PropertyHasAttribute(Type attribute, string target)
        {
            return GivenClass.GetProperty(target).GetCustomAttributes(attribute, true).Count() == 1;
        }

    }
Run Code Online (Sandbox Code Playgroud)

然后我测试了我的助手:

    [TestMethod]
    public void ThisMethod_Has_TestMethod_Attribute()
    {
        // Arrange
        var helper = new AttributeHelper<AttributeHelperTests>();

        // Act
        var result = helper.MethodHasAttribute(typeof (TestMethodAttribute), "ThisMethod_Has_TestMethod_Attribute");

        // Assert
        Assert.IsTrue(result);
    }
Run Code Online (Sandbox Code Playgroud)

一切都运行正常,除了方法和属性必须公开以便我使用反射.我无法想到我必须向私有属性/方法添加属性的任何情况.

然后测试EF注释:

        public void IdProperty_Has_KeyAttribute()
        {
            // Arrange
            var helper = new AttributeHelper<Player>();

            // Act
            var result = helper.PropertyHasAttribute(typeof (KeyAttribute), "Id");

            // Assert
            Assert.IsTrue(result);
        }
Run Code Online (Sandbox Code Playgroud)

k.m*_*k.m 8

我知道测试Key,Column和Required属性不再是单元测试,它是一个集成测试,因为它依赖于底层数据库

怎么会这样?您可以测试Id属性是否标记了所有这些属性.它属于单元测试类别.

[Test]
public void Id_IsMarkedWithKeyAttribute()
{
    var propertyInfo = typeof(MyClass).GetProperty("Id");

    var attribute = propertyInfo.GetCustomAttributes(typeof(KeyAttribute), true)
        .Cast<KeyAttribute>()
        .FirstOrDefault();

    Assert.That(attribute, Is.Not.Null);
}
Run Code Online (Sandbox Code Playgroud)

这样,您可以确保您的属性标记有您可以想到的任何属性.当然,这涉及一些反思工作,但这就是你如何测试属性标记.