How would you unit test data annotations?

一世执手 提交于 2019-11-29 10:58:55
k.m

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

How is that so? You can test whether Id property is marked with all those attributes just fine. And it falls into unit-test category.

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

This way you can assure your properties are marked with any attribute you can think of. Sure, this involves some reflection work but that's how you test attribute marking.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!