Two of the class properties have the following annotations:
[Key]
[Column]
[Required]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
[MaxLength(25)]
public string Name { get; set; }
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, but how do you go about testing MaxLength(25) attribute?
One of the alternatives that I can think of, is to add a code contract into the property.
Update
As suggested, I wrote the following helper:
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;
}
}
I have then tested my helper:
[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);
}
Everything works fine, apart from the fact that methods and properties must be public in order for me to use reflection. I can't think of any cases where I had to add attributes to the private properties/methods.
And then testing the EF annotations:
public void IdProperty_Has_KeyAttribute()
{
// Arrange
var helper = new AttributeHelper<Player>();
// Act
var result = helper.PropertyHasAttribute(typeof (KeyAttribute), "Id");
// Assert
Assert.IsTrue(result);
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…