[英]Fluent Assertions check if all endpoints have a specific swagger attribute
我想檢查我的 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 是一個 helper class,它繼承了 ControllerBase,所有的控制器都繼承了 Base Controller。
BaseController
有方法嗎? 如果沒有,您需要首先列出具體類型並使用Methods
擴展方法。
However, I would actually write HTTP API tests (using the ASP.NET Core HostBuilder
) that verify that the observable output of your Swagger endpoint is correct.
要檢查 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 中直接查看方法,您必須獲取所有子 class:
var baseControllerType = typeof(BaseController);
var controllerTypes = baseControllerType.Assembly.GetTypes().Where(t => t.IsClass && t != type
&& type.IsAssignableFrom(BaseController))
然后對於每個 controller 您可以應用相同的邏輯。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.