How would you unit test data annotations?

后端 未结 1 852
不知归路
不知归路 2020-12-19 09:56

Two of the class properties have the following annotations:

    [Key]
    [Column]
    [Required]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity         


        
相关标签:
1条回答
  • 2020-12-19 10:52

    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.

    0 讨论(0)
提交回复
热议问题