您将如何单元测试数据注释
本文关键字:单元 测试数据 注释 何单元 | 更新日期: 2023-09-27 18:31:48
其中两个类属性具有以下注释:
[Key]
[Column]
[Required]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
[MaxLength(25)]
public string Name { get; set; }
我知道测试键、列和必需属性不再是单元测试,而是集成测试,因为它取决于底层数据库,但是如何测试 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);
}
我知道测试键、列和必需属性不再是单元测试,而是集成测试,因为它取决于底层数据库
怎么会这样?您可以测试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);
}
通过这种方式,您可以确保您的属性标有您能想到的任何属性。当然,这涉及一些反射工作,但这就是您测试属性标记的方式。