两个类属性具有以下注释:
我知道测试Key,Column和Required属性已经不再是单元测试,因为它会依赖底层数据库,但是如何测试MaxLength(25)属性呢?
我能想到的其中一个替代方案是将代码约束添加到属性中。
更新:
如建议所示,我编写了以下帮助程序:
我已经测试了我的助手:
[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);
}