[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 ?
CodePudding user response:
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);
CodePudding user response:
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>();
CodePudding user response:
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)));