Testing ASP.NET Core Web APIs

Testing ASP.NET Core Web APIs

When designing and developing a wide variety of APIs using ASP.NET Core 2.1 Web API, it is important to understand that this is only the first step in creating a productive and stable solution. Having a stable environment for your solution is also very important. The key to a great solution is not only to build the API correctly, but also to thoroughly test it to eliminate the possibility of negative user experience while using your API.

ASP.NET Core is a new web framework created by Microsoft as a replacement for the legacy technology that has existed since ASP.NET 1.0. Dropping legacy dependencies and designed from the ground up, ASP.NET Core 2.1 is designed for cross-platform execution and gives the developer much better productivity.

What is Unit Testing?

Software testing may be new to some people, but it’s not complicated. Let’s start with unit testing (or unit testing). The formal definition from Wikipedia is “a process in programming that allows you to check for correctness individual modules of the source code of a program, sets of one or more program modules, together with the corresponding control data, procedures for use and processing.” I prefer to use a more accessible definition: unit testing is used to make sure that after adding new functionality or fixing bugs, the code in your application works as expected.

A good unit test has three parts. The first is the Arrange part, which is used to prepare any resources your test might need. In the above example, I don’t need any preconfiguration, so the Arrange part is empty (but I still leave a comment on it). The next part, called Act, is the part where the tested action is performed. In this example, I call the data repository on an entity of type Album to get the entire set of albums from the data source that uses the repository. In the last part of the test, we make sure or Assert that the result of the performed action was correct. In this test, I verify that I only got one album from the data repository.

I will be using the xUnit unit testing tool for this article. xUnit is an open source package for the .NET Framework and .NET Core. We’ll take a look at the .NET Core version of xUnit that ships with the .NET Core 2.1 SDK. You can create a new Unit Test project using the .NET Core dotnet test cli command, or from the xUnit Test project template in your favorite IDE such as Visual Studio 2017, Visual Studio Code, or JetBrain’s Rider.

How should web APIs be tested

How should web APIs be tested?

How Should Web APIs be Tested?