W jaki sposób można przypisać adnotacje danych testowych?
Dwie właściwości klasy mają następujące adnotacje:
[Key]
[Column]
[Required]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
[MaxLength(25)]
public string Name { get; set; }
Rozumiem, że testowanie atrybutów Key, Column i Required nie jest już testem jednostkowym, jest testem integracji, ponieważ zależałoby od bazowej bazy danych, ale jak przejść do testowania atrybutu MaxLength (25)?
Jedną z alternatyw, o których mogę pomyśleć, jest dodanie umowy dotyczącej kodu do nieruchomości.
Aktualizacja
Zgodnie z sugestią napisałem następujący pomocnik:
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;
}
}
Przetestowałem wtedy mojego pomocnika:
[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);
}
Wszystko działa dobrze, oprócz tego, że metody i właściwości muszą być publiczne, abym mógł użyć refleksji. Nie mogę wymyślić żadnych przypadków, w których musiałbym dodać atrybuty do prywatnych właściwości / metod.
A następnie testowanie adnotacji EF:
public void IdProperty_Has_KeyAttribute()
{
// Arrange
var helper = new AttributeHelper<Player>();
// Act
var result = helper.PropertyHasAttribute(typeof (KeyAttribute), "Id");
// Assert
Assert.IsTrue(result);
}