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

[DummyAttribute]
public void DummyMethod() {
  return;
}

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)
        .GetMethod(nameof(YourClassName.DummyMethod))!
        .GetCustomAttributes(inherit: false)
        .OfType<DummyAttribute>()
        .SingleOrDefault();
    
    Assert.That(dummyAttribute, Is.Not.Null);
    

  • answered 2022-04-06 20:49 codeninja.sj

    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.

    typeof(YourClassName).GetMethod(nameof(YourClassName.DummyMethod)).Should().BeDecoratedWith<DummyAttribute>();
    

  • answered 2022-04-06 21:07 Charlie

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

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

    Assert.That(typeof(YourClassName).GetMethod(nameof(SomeMethod)),
        Has.Attribute(typeof(DummyAttribute)));
    

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