Search code examples
c#asp.net-coreswaggerxunitfluent-assertions

Fluent Assertions check if all endpoints have a specific swagger attribute


I want to check if all endpoints of my ASP.NET Core API controllers have an attribute that looks line this:

[SwaggerResponse(HttpStatusCode.OK,typeof(*different types*))]

I used xUnit and Fluent Assertions to write this:

[Fact]
public void EndpointsSwaggerAttribute()
{
      typeof(BaseController).Methods().Should().BeDecoratedWith<SwaggerResponseAttribute>(s =>(s.StatusCode == HttpStatusCode.OK.ToString()));
}

But it does not quite work. It always passes the test. Base controller is a helper class that inherits ControllerBase and all controllers inherit Base Controller.


Solution

  • For you want to check if all endpoints of API controllers have SwaggerResponse attribute,you need firstly get the assembly of your api project and then get all the methods in project:

    public class UnitTest1
    {
        [Fact]
        public void Test1()
        {
            //if the unit test exsit in the api project...
            //Assembly asm = Assembly.GetExecutingAssembly();
    
            //if your unit test project seprate from the api project
            //you could get the api project assembly like below
            var asm = typeof(WeatherForecastController).Assembly;
            
            //get all the methods in project
            var methods = asm.GetTypes()
            .Where(type => typeof(ControllerBase).IsAssignableFrom(type)) 
            .SelectMany(type => type.GetMethods(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly)).ToList();
                        
            foreach (var method in methods)
            {              
                //check if the method has SwaggerResponse attribute  
                var result = Attribute.IsDefined(method, typeof(SwaggerResponseAttribute));
                Assert.True(result, $"{method.Name} should be declared with SwaggerResponse Attribute");
            }
    
        }
    }