Test if a class has an attribute?

C#Unit TestingAttributes

C# Problem Overview


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?

C# Solutions


Solution 1 - C#

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

Solution 2 - C#

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

Here's some sample code.

typeof(ScheduleController)
.IsDefined(typeof(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.

Solution 3 - C#

It is also possible to use generics on this:

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

This way you do not need another typeof(...), which can make the code cleaner.

Solution 4 - C#

I know this thread is really old, but if somebody stumble upon on it you may find fluentassertions project very convenient for doing this kind of assertions.

typeof(MyPresentationModel).Should().BeDecoratedWith<SomeAttribute>();

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJoshRiversView Question on Stackoverflow
Solution 1 - C#Marc GravellView Answer on Stackoverflow
Solution 2 - C#RichardODView Answer on Stackoverflow
Solution 3 - C#KroltanView Answer on Stackoverflow
Solution 4 - C#Aleksey L.View Answer on Stackoverflow