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.
Does the BaseController
have methods at all? If not, you'll need to first list the concrete types and use the Methods
extension method on that.
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.
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");
}
}
}
Currently you're only looking the methods directly inside BaseController, you have to get all children class:
var baseControllerType = typeof(BaseController);
var controllerTypes = baseControllerType.Assembly.GetTypes().Where(t => t.IsClass && t != type
&& type.IsAssignableFrom(BaseController))
Then for each controller you can apply the same logic.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.