Is it best practice to test my Web API controllers directly or through an HTTP client?

前端 未结 8 2096
故里飘歌
故里飘歌 2021-02-05 10:08

I\'m adding some unit tests for my ASP.NET Core Web API, and I\'m wondering whether to unit test the controllers directly or through an HTTP client. Directly would look roughly

8条回答
  •  庸人自扰
    2021-02-05 10:41

    You can use Swagger (aka OpenAPI).

    Install Swashbuckle.AspNetCore from nuget.

    using Microsoft.OpenApi.Models;
    
    //in  Startup.ConfigureServices
    
    public void ConfigureServices(IServiceCollection services)
    {
      services.AddSwaggerGen(c =>
      {
      c.SwaggerDoc("v1", new OpenApiInfo { Title = "My API", Version = "v1" });
      });
    }
    
    //in Startup.Configure
    
    public void Configure(IApplicationBuilder app)
    {
      app.UseSwagger();
      app.UseSwaggerUI(c =>
      {
        c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
      });
    }
    

    Finally, add "launchUrl": "swagger", in launchSettings.json

提交回复
热议问题