1

Is there a way with xUnit to test that a method has specific attributes on it?

[HttpGet]
[SwaggerOperation(OperationId = "blah", Summary = "blah", Description = "blah")]
[ProducesResponseType((int)HttpStatusCode.OK)]
public async Task<ActionResult<IList<string>>> GetSomething
(
    [Required, FromRoute(Name = "blah")] Guid aGuid,
)
{}

I would like to be able to test that [HttpGet] and all of the other attributes exist on the GetSomething method. Also, if possible would like to check that the [Required] attribute is on the method parameter aGuid

Ryan
  • 4,354
  • 2
  • 42
  • 78
  • check https://stackoverflow.com/questions/1226161/test-if-a-class-has-an-attribute and https://stackoverflow.com/questions/55419864/c-sharp-webapi-how-to-unit-test-if-a-controller-action-is-decorated-with-an-auth – Mate May 17 '19 at 00:09

1 Answers1

1

You can access attributes and their data by using reflection:
Accessing Attributes by Using Reflection (C#)
Retrieving Information Stored in Attributes

But I would suggest to use FluentAssertions library, which provide same approach in a fluently readable way.

[Fact]
public void GetAll_ShouldBeDecoratedWithHttpGetAttribute()
{
    var getSomething = nameof(_controller.GetSomething);
    typeof(MyController).GetTypeInfo()
        .GetMethod(getSomething)
        .Should()
        .BeDecoratedWith<HttpGetAttribute>();
}
Fabio
  • 31,528
  • 4
  • 33
  • 72