views:

344

answers:

2

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?

+4  A: 

The same you would normally check for an attribute on a class.

Here's some sample code.

typeof(ScheduleController)
.IsDefined(SubControllerActionToViewDataAttribute, false);

I think in many cases testing for the existence of an attribute in a unit test is wrong. As I've not used MVC contrib's sub controller functionality I can't comment whether it is appropriate in this case though.

RichardOD
+9  A: 

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....)

Marc Gravell
damn you :)
annakata
to only check if the attribute is present, which is usually all that is needed for parameterless/propertyless attributes, it's cheaper to use .IsDefined, as it will query the metadata, and not deserialize and instantiate the attribute object.
Lasse V. Karlsen
Valid point Marc :)
Lasse V. Karlsen
As is the point about IsDefined being cheaper... but in most cases (and in particular unit tests) you are unlikely to notice the difference. Maybe if it was a tight loop in production code...
Marc Gravell
@Marc- I agree about that the difference in performance would probably not be noticeable in a unit test. I'd get the attribute if I needed to use it, which as you say is the scenario in most cases. I recently used IsDefined in a framework I was writing to exclude a column in a dropdown of sortable fields- this worked well as I didn't need to use to the attribute itself.
RichardOD