Check if the class has an attribute?

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 assign a unit test to this class class?

+75
c # unit-testing attributes
Aug 04 '09 at 7:44
source share
4 answers

check that

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

non-null ( Assert.IsNotNull or similar)

(the reason I use this, rather than IsDefined , is because in most cases I want to check some attribute properties as well ....)

+94
Aug 04 '09 at 7:47
source share

You usually check the same for an attribute in a class.

Here is a sample code.

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

I think in many cases, testing for an attribute in a unit test is incorrect. Since I did not use the functions of the MVC contrib subcontroller, I cannot comment on whether this is appropriate in this case.

+53
Aug 04 '09 at 7:47
source share

You can also use generics:

 var type = typeof(SomeType); var attribute = type.GetCustomAttribute<SomeAttribute>(); 

This way you don't need another typeof(...) that can make the code cleaner.

+7
Mar 12 '16 at 19:19
source share

I know that this branch is really old, but if someone stumbles upon it, you can find a fluentassertions project that is very convenient for such statements.

 typeof(MyPresentationModel).Should().BeDecoratedWith<SomeAttribute>(); 
+5
Sep 25 '15 at 11:23
source share



All Articles