Testing the Web API
Now that we have a Web API created, we will look at options to validate our Web API functionality. Testing is a crucial stage in the creation of Web API development and publishing. There are a couple of different ways of doing this. We can just test it by requesting the URL in a browser or write code and leverage the System.Net.HttpClient
type. This section discusses both of these approaches.
Testing in a browser
Testing a Web API is as simple as developing it, since each action in a Web API controller represents a resource, we can just type the URL of the resource and fetch the results.
Press F5 in Visual Studio to launch the Web API in a browser.
Visit the following URL:
http://localhost:<PORT>/api/package/1
Note
Note that the port will be allocated by IIS Express and will be different for each installation.
This yields a result similar to the following in the browser:
{ "Id": 1, "AccountNumber": "43a2a3eb-e0b8-4840-9e5e-192214a79d58", "Destination": "TX", "Origin": "CA", "Weight": 2.5, "Units": 1, "StatusCode": 1, "Created": "2015-03-16T23:57:33.1372091Z", "Properties": null }
What happened here?
The client (in this case, the browser) initiated a GET
request by hitting the URL:
GET /api/package/1 HTTP/1.1 Host: localhost:49435 Cache-Control: no-cache
When the server received the request, it scanned all controllers to check for a matching route. When the route was found, PackageController
was selected to respond to the request, and its Initialize
method was invoked. The GET
action in PackageController
was then identified as a route match for the HTTP GET
request. The method gets called, and 1
is passed as the parameter.
Testing with HttpClient
In the previous section, we discussed how to use a browser to test our Web API. In scenarios where we call our Web API from within a business logic or client application, this may not work. Fortunately, the System.Net.HttpClient
type can be used to invoke an HTTP-based Web API from a .NET client.
We will use our Visual Studio test project that we created earlier to demonstrate this example:
Create a new Unit Test type
PackageControllerTest.cs
in theContoso.Transport.Services.Tests
project.Note
The Visual Studio ranger's team has built an extension to generate unit tests for class files. It is a useful tool to generate Test methods for multiple methods in the class files. The extensions can be found here: https://visualstudiogallery.msdn.microsoft.com/45208924-e7b0-45df-8cff-165b505a38d7.
Add the following assembly references to the project:
System.Net.Http
assemblyContoso.Transport.Services
Add the following NuGet packages to the project:
Newtonsoft.JSON
Replace the code in
PackageControllerTest.cs
with the following code:using System; using Microsoft.VisualStudio.TestTools.UnitTesting; using System.Net.Http; using Newtonsoft.Json; using System.Threading.Tasks; using System.Net.Http; using Contoso.Transport.Services.Models; namespace Contoso.Services.Tests { [TestClass] public class PackageControllerTests { [TestMethod] public async Task FindPackageByIdNotNullTest() { var packageid = 1; var packageUrl = string.Format("http://localhost:<PORT>/api/package/{0}", packageid); using (HttpClient client = new HttpClient()) { var response = await client.GetStringAsync(packageUrl); Assert.IsNotNull(response); var package = await Task.Factory.StartNew(() => JsonConvert.DeserializeObject<Package>(response)); Assert.IsNotNull(package); Assert.AreEqual(packageid, package.Id); } } } }
Change
packageUrl
to the URL of the created Web API.At this point, ensure that the Web API is running. Please refer to the Testing in a browser section for more details.
Build the test project.
Right-click on
Test Method
and click on Run Test (Ctrl + R + T).The test explorer should display the success results, as follows:
We verified our Web API using a .NET client as well. HttpClient
exposes a set of utility methods that allow us to perform various HTTP operations. In this case, we used the GetStringAsync
method that creates an HTTP GET
request and returns the response as a string.