簡體   English   中英

您如何對數據注釋進行單元測試?

[英]How would you unit test 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)屬性呢?

我能想到的其中一個替代方案是在屬性中添加代碼契約。

更新

正如所建議的那樣,我寫了以下幫助:

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

一切都運行正常,除了方法和屬性必須公開以便我使用反射。 我無法想到我必須向私有屬性/方法添加屬性的任何情況。

然后測試EF注釋:

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

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

            // Assert
            Assert.IsTrue(result);
        }

我知道測試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);
}

這樣,您可以確保您的屬性標記有您可以想到的任何屬性。 當然,這涉及一些反思工作,但這就是你如何測試屬性標記。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM