Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 611
emseetea Avatar asked Oct 18 '15 01:10

emseetea


People also ask

Can we automate API testing using Swagger?

Swagger Inspector provides capabilities to easily inspect API request-responses, and make sure they work as expected. Automating your API testing and verifying that it functions correctly in different scenarios is dead simple with ReadyAPI. You can import your API definitions to: easily validate schema rules.

How do I get Swagger endpoint?

In Swagger, click on region : region CRUD operations to list all the available endpoints for accessing regions. In the list of region endpoints, click on the GET /v1 endpoint link. The page displays additional request and response information about the API. Click the Try it out!


2 Answers

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
like image 170
emseetea Avatar answered Oct 04 '22 17:10

emseetea


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

like image 39
Helder Sepulveda Avatar answered Oct 04 '22 15:10

Helder Sepulveda