title: How would you unit test data annotations?
body: <p>Two of the class properties have the following annotations:    </p>
  
  <pre><code>    [Key]
      [Column]
      [Required]
      [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
      public int Id { get; set; }
  
  
      [MaxLength(25)]
      public string Name { get; set; }
  </code></pre>
  
  <p>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?</p>
  
  <p>One of the alternatives that I can think of, is to add a code contract into the property.</p>
  
  <p><strong>Update</strong></p>
  
  <p>As suggested, I wrote the following helper:</p>
  
  <pre><code>    public class AttributeHelper &lt;T&gt; 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;
          }
  
      }
  </code></pre>
  
  <p>I have then tested my helper:</p>
  
  <pre><code>    [TestMethod]
      public void ThisMethod_Has_TestMethod_Attribute()
      {
          // Arrange
          var helper = new AttributeHelper&lt;AttributeHelperTests&gt;();
  
          // Act
          var result = helper.MethodHasAttribute(typeof (TestMethodAttribute), "ThisMethod_Has_TestMethod_Attribute");
  
          // Assert
          Assert.IsTrue(result);
      }
  </code></pre>
  
  <p>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.</p>
  
  <p>And then testing the EF annotations:</p>
  
  <pre><code>        public void IdProperty_Has_KeyAttribute()
          {
              // Arrange
              var helper = new AttributeHelper&lt;Player&gt;();
  
              // Act
              var result = helper.PropertyHasAttribute(typeof (KeyAttribute), "Id");
  
              // Assert
              Assert.IsTrue(result);
          }
  </code></pre>