Search code examples
c#attributesnunit

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 ?


Solution

  • 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);