Can I assert that a C# method has a certain attribute?

public void DummyMethod() {

I want to write a Nunit test that will assert that DummyMethod is decorated with DummyAttribute, can I do that ?

3 answers

  • answered 2022-04-06 20:08 kardo

    Yes, with reflection. One possible solution:

    var dummyAttribute = typeof(YourClassName)
        .GetCustomAttributes(inherit: false)
    Assert.That(dummyAttribute, Is.Not.Null);

  • answered 2022-04-06 20:49

    These kinds of tests are often useful to define the functional specification of the codebase.

    @kardo's code is absolutely fine and seems it solved your problem as well.

    However, if anyone looks for more descriptive unit tests later to specify the functional specs, then I would suggest giving a try on fluent assertions.


  • answered 2022-04-06 21:07 Charlie

    Yes, you can reflect or use "fluent assertions" package.

    Alternatively, since you're using NUnit already...


How many English words
do you know?
Test your English vocabulary size, and measure
how many words do you know
Online Test
Powered by Examplum