Test if a class has an attribute?

前端 未结 4 610
再見小時候
再見小時候 2020-12-05 03:52

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

[SubControllerActionToViewDataAttr         


        
相关标签:
4条回答
  • 2020-12-05 04:12

    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>();
    
    0 讨论(0)
  • 2020-12-05 04:19

    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.

    0 讨论(0)
  • 2020-12-05 04:20

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

    0 讨论(0)
  • 2020-12-05 04:26

    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.

    0 讨论(0)
提交回复
热议问题