Test if a class has an attribute?

JoshRivers picture JoshRivers · Aug 4, 2009 · Viewed 58.3k times · Source

I'm trying to do a little Test-First development, and I'm trying to verify that my classes are marked with an attribute:

[SubControllerActionToViewDataAttribute]
public class ScheduleController : Controller

How do I unit test that the class has that attribute assigned to it?

Answer

Marc Gravell picture Marc Gravell · Aug 4, 2009

check that

Attribute.GetCustomAttribute(typeof(ScheduleController),
    typeof(SubControllerActionToViewDataAttribute))

isn't null (Assert.IsNotNull or similar)

(the reason I use this rather than IsDefined is that most times I want to validate some properties of the attribute too....)