Fluent Assertions 检查是否所有端点都具有特定的 swagger 属性

问题描述

我想检查我的 ASP.NET Core API 控制器的所有端点是否都有一个看起来像这样的属性

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

我用 xUnit 和 Fluent Assertions 来写这个:

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

但它并不完全有效。它总是通过测试。 Base Controller是一个继承ControllerBase的辅助类,所有的Controller都继承Base Controller。

解决方法

BaseController 是否有方法?如果没有,您需要首先列出具体类型并对其使用 Methods 扩展方法。

但是,我实际上会编写 HTTP API 测试(使用 ASP.NET Core HostBuilder)来验证您的 Swagger 端点的可观察输出是否正确。

,

如果你想检查 API 控制器的所有端点是否都有 SwaggerResponse 属性,你需要先获取你的 api 项目的程序集,然后获取项目中的所有方法:

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");
        }

    }
}
,

目前您只在 BaseController 中直接查看方法,您必须获取所有子类:

        var baseControllerType = typeof(BaseController);
        var controllerTypes = baseControllerType.Assembly.GetTypes().Where(t => t.IsClass && t != type
                                                      && type.IsAssignableFrom(BaseController))

然后对于每个控制器,您可以应用相同的逻辑。