markti
markti

Reputation: 4528

Unit Test Swagger Output

I am using Swagger in an ASP.NET MVC WebAPI project. This project has Swashbuckle nugget package installed and generates Swagger UI and Swagger/docs/v1. A consistent problem I'm having is developers will break the swagger file by not carefully naming their webAPI operations. I would like to add a unit test to prevent me from finding out that swagger/docs/v1 isn't available by going to the Swagger UI site after deployment and seeing an HTTP 500 displayed in the swagger UI. Does anybody know how to write a unit test to validate that Swashbuckle can successfully generate the swagger docs?

Upvotes: 11

Views: 8272

Answers (3)

Julio Nobre
Julio Nobre

Reputation: 4395

To whom may be looking for a Asp.Net Core Swagger testing solution, I suggest taking a closer look at Cristophe Blin's aproach

Upvotes: 0

markti
markti

Reputation: 4528

Found a great way to do what I want:

[Fact]
public async Task TestSwagger()
{
   var webHostBuilder = new WebHostBuilder()
                    .UseEnvironment("Test") // You can set the environment you want (development, staging, production)
                    .UseStartup<Startup>(); // Startup class of your web app project

   using (var server = new TestServer(webHostBuilder))
   {
      using (var client = server.CreateClient())
      {
         string result = await client.GetStringAsync("/swagger/v1/swagger.json");
         JObject root = JObject.Parse(result);
      }
   }
}

This uses the following nuget package:

  • Microsoft.AspNetCore.TestHost

Upvotes: 11

Helder Sepulveda
Helder Sepulveda

Reputation: 17594

Look at the UnitTests we have on Swashbuckle : https://github.com/domaindrivendev/Swashbuckle/tree/master/Swashbuckle.Tests/Swagger

I'm sure one of those is really close to what you are looking for.

...But if is just the naming of the webAPI operations you could just loop over those using GetApiExplorer and make sure they follow your rules

Upvotes: 2

Related Questions