Friday 30 March 2018

Unit Testing Web API Using Swagger


Unit Testing Web API Using Swagger



 Introduction

In  this post we will use ASP.NET Web API to create a RESTful service and use a NuGet package to create Swagger(Open API) specification.  

Background

What is ASP.NET Web API?
ASP.NET Web API is a framework that makes it easy to build HTTP services that reach a broad range of clients, including browsers and mobile devices. ASP.NET Web API is an ideal platform for building RESTful applications on the .NET Framework.

What is Swagger? 

Swagger is a simple yet powerful representation of your RESTful API. With the largest ecosystem of API tooling on the planet, thousands of developers are supporting Swagger in almost every modern programming language and deployment environment.

Advantages of Swagger


·       It's comprehensible for developers and non-developers. Product managers, partners, and even potential clients can have input into the design of your API, because they can see it clearly mapped out in this friendly UI.
·       It's human readable and machine readable. This means that not only can this be shared with your team internally, but the same documentation can be used to automate API-dependent processes.
·       It's easily adjustable. This makes it great for testing and debugging API problems.

 Using the code


Step 1 Adding Swagger to Web API Project

To add Swagger to Web API, we just need to install an open source project called Swashbuckle via NuGet.

Unit Testing Web API Using Swagger




Step 2 .  Install NuGet Packages

Install "Swashbuckle.AspNetCore" NuGet package in the solution. 


After Installation, you can see the swaggerconfig.cs under app_start folder in your project.

Step 3 View the Swaggerconfig.cs 



Step 4 Configure Swagger

At minimum, we need this line to enable Swagger and Swagger UI. 


Unit Testing Web API Using Swagger




Step 5 Now, run your API application and Just type swagger after service. You will get the UI of swagger with list API including whatever we wrote in services.

http://localhost:59400/swagger/ui/index#/Values





Unit Testing with API

 Click on Try it out button It will send a response for Get and Post Method.

Unit Testing Web API Using Swagger




Happy Programming!!

Don’t forget to leave your feedback and comments below!

If you have any query mail me to Sujeet.bhujbal@gmail.com     

Regards
Sujeet Bhujbal
--------------------------------------------------------------------------------
------------------------------------------------------------------------------