c# - 您将如何对数据注释进行单元测试?

标签 c# unit-testing tdd data-annotations

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

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


    [MaxLength(25)]
    public string Name { get; set; }

我知道测试 Key、Column 和 Required 属性不再是单元测试,而是集成测试,因为它取决于底层数据库,但是您如何测试 MaxLength(25) 属性?

我能想到的备选方案之一是在属性中添加代码契约(Contract)。

更新

按照建议,我编写了以下帮助程序:

    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;
        }

    }

然后我测试了我的助手:

    [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);
    }

除了方法和属性必须公开以便我使用反射之外,一切正常。我想不出任何我必须向私有(private)属性/方法添加属性的情况。

然后测试 EF 注释:

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

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

            // Assert
            Assert.IsTrue(result);
        }

最佳答案

I understand that testing Key, Column and Required attributes is no longer a unit test, it's an integration test as it would depend on the underlying database

怎么会这样?您可以测试 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);
}

这样您就可以确保您的属性标有您能想到的任何属性。当然,这涉及一些反射工作,但这就是您测试属性标记的方式。

关于c# - 您将如何对数据注释进行单元测试?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10259793/

相关文章:

c# - 是否建议在 Windows 服务中运行 Visual Studio Tools for Office?

c# - 设置单元测试以使用 Unity 测试 Controller

ruby-on-rails - RSpec 和 Capybara 设置,have_no_content 似乎不起作用

unit-testing - 是否应该在编写代码之前编写单元测试?

c# - 无法在 Visual Studio 中调试单元测试

c# - 图像打印的宽高比不正确?

javascript - 如何在单击按钮时从代码后面调用 javascript 函数并存储其输出并进一步继续

c# - 如何以编程方式绑定(bind)数据网格列?

unit-testing - 为什么我从 npm 运行 Jest 时得到 0 覆盖率?

javascript - `nyc mocha`没有覆盖率数据