Unit Testing of WEB API

In my previous article Create WEB API Using Repository Using Visual Studio 2013 I created a Web API. Now in this article, I will explain how to create a unit test for the created Web API.

Step 1

Add a new project to the existing project as in the following:

existing project 
Add new Project  

Step 2

In this unit test project, add a project reference to the original project.

project reference 
 
 
 
Install NuGet packages in the test project

Right-click the UnitTestProject project and select Manage NuGet Packages as in the following:

 

Find and install the Microsoft ASP.NET Web API 2 Core package as in the following:

 

The Microsoft ASP.NET Web API 2.1 Core libraries will be installed in the UnitTestProject project.

 

Add a new class called TestEmployeeController.cs to the UnitTestProject project and implement a method. Build the solution.

 
 
All of the methods that are marked with the TestMethod attribute will be tested. Select Test -> Run -> All Tests to run the tests.

 
 

The test has passed.

Now add one more record to the List<Employee> as in the following:

 

Build the solution and run the tests.

 
 
Now the expected result is 4 but the actual result is 3. So the test failed.