1
[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 ?

Milan
  • 1,547
  • 1
  • 24
  • 47

3 Answers3

3

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);
kardo
  • 96
  • 3
  • Thank you very much ! I was going on the way to find all the methods with said custom attribute in loaded assembly, then look for my method, but this is way more efficient – Milan Apr 06 '22 at 20:12
1

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>();
codeninja.sj
  • 3,452
  • 1
  • 20
  • 37
1

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)));
Charlie
  • 12,928
  • 1
  • 27
  • 31