Software maintenance is the inevitable part of the development process and one that could give developers the most trouble. We’ve all been there, whether we left our code in someone else’s care, or we’ve inherited some legacy code.

This doesn’t necessarily need to be a bad thing and there are ways to improve our code and make it more maintainable. Unit testing plays a very important role in making the software more maintainable.

Our intention in this post is to make an intro to unit testing of ASP.NET Core Web API application.

You can download the source code from the repo on GitHub.

In this article, we are going to talk about different segments of unit testing:

About Unit Testing in General

What is unit testing in the first place? It begins by defining what a „unit“ is and although this is not strictly defined, the unit represents a unit of work – usually a single method in our code.

We test these units individually, making sure that each of them is doing exactly that what it is written for.

Nothing more, nothing less.

What is important to understand is that we are not testing the behavior of the dependencies of that method. That is what the integration tests are for.

We have a great series of articles dedicated to Testing ASP.NET Core Application. So, if you want to learn even more about the testing, we strongly recommend reading ASP.NET Core MVC Testing Series.

Preparing the Example Project

We will use Visual Studio 2019 to create our example project and it will be ASP.NET Core Web API application. Let’s start by creating a new ASP.NET Core Web Application:

starting project - unit testing with .NET Core

After choosing the name for our solution and the project which is web-api, we get to chose which type of web application we want to create. In our case that would be the API project:

choosing project - unit testing with .NET Core

When we create the ASP.NET Core API application initially, it comes with the default controller class.

Let’s delete that one and create our own example controller named ShoppingCartController. Here we can define CRUD operations you would typically have on an entity based controller:

Nothing special about the code here, we’ve got a simple example of a shopping cart controller where we have methods to get, add and remove items from the cart.

ShoppingCartService Explanation

To access the data source, we are using ShoppingService class which implements IShoppingService interface. This allows us to follow the dependency injection principle, which is used heavily for the purpose of unit testing.

Using dependency injection, we can inject whatever implementation of IShoppingCart interface we want into our test class.

Please note that methods of the service are not implemented in the example project, because we are not focusing on the service implementation here, testing the controller is the main goal. In the real project, you would probably use some data access logic in your service methods:

IShoppingService contains signatures of all the methods seen in the ShoppingCartService:

ShoppingItem is our main (and only 🙂 ) entity with just a few fields:

As we are using dependency injection to create instances of our services, make sure not to forget to register the service in the Startup class:

Creating a Testing Project

Finally, we come to the point when we need to create a new project where our tests are going to be. Conveniently for us, there is a xUnit testing project template out-of-the-box when using visual studio 2019, so we are going to make use of that.

The xUnit is an open-source unit testing tool for the .NET framework that simplifies the testing process and allows us to spend more time focusing on writing our tests:

xUnit project - unit testing with .NET Core

We are going to name it web-api-tests.

Now we have a new project in our solution named web-api-tests. Next thing we should do is to add the reference to the project we are about to write tests for:

reference project

At this time we should create our fake implementation of the IShoppingCartService interface, which we are going to inject to our controller at the time of testing.

It has an in-memory collection which we are going to fill up with our dummy data:

Instead of creating fake service manually, we could’ve used one of the many mocking frameworks available. One of those frameworks is called Moq. You can get more information about it in the Testing MVC Controllers article, where we use the Moq library to isolate our dependencies.

Let’s write some unit tests!

Now we are all set and ready to write tests for our first unit of work – the Get method in our ShoppingCartController.

We will decorate test methods with the [Fact] attribute, which is used by the xUnit framework, marking them as the actual testing methods. Besides the test methods, we can have any number of helper methods in the test class as well.

When writing unit tests it is usually the practice to follow the AAA principle (Arrange, Act, and Assert):

Arrange – this is where you would typically prepare everything for the test, in other words, prepare the scene for testing (creating the objects and setting them up as necessary)

Act – this is where the method we are testing is executed

Assert – this is the final part of the test where we compare what we expect to happen with the actual result of the test method execution

Test method names should be as descriptive as possible. In most of the cases, it is possible to name the method so that it is not even necessary to read the actual code to understand what is being tested.

In the example we use the naming convention in which the first part represents the name of the method being tested, the second part tells us more about the testing scenario and the last part is the expected result.

Generally, the logic inside our controllers should be minimal and not so focused on business logic or infrastructure (ec. data access). We want to test the controller logic and not the frameworks we are using.

We need to test how the controller behaves based on the validity of the inputs and controller responses based on the result of the operation it performs.


Testing Our Actions

The first method we are testing is the Get method and there we will want to verify the following:

  • Whether the method returns the OkObjectResult which represents 200 HTTP code response
  • Whether returned object contains our list of ShoppingItems and all of our items

Testing the Get Method

So let’s see how we go about testing our method:

We create an instance of the ShoppingCartController object in the test class and that is the class we want to test. It is important to note here that this constructor is called before each test method, meaning that we are always resetting the controller state and performing the test on the fresh object.

This is important because the test methods should not be dependant on one another and we should get the same testing results, no matter how many times we run the tests and in which order we run them.

Testing the GetById method

Now let’s see how we can test the GetById method:

Firstly we verify that the controller will return 404 status code (Not Found) if someone asks for the non-existing ShoppingItem. Secondly, we test if 200 code is returned when the existing object is asked for and lastly we check if the right object is returned.

Testing the Add Method

Let’s see how we can deal with the Add method:

Once again we are testing that the right objects are returned when someone calls the method, but there is something important to note here.

Among other things, we are testing if ModelState is validated and the proper response is returned in the case that the model is not valid. But to achieve this, it is not enough to just pass the invalid object to the Add method. That wouldn’t work anyway since model state validation is only triggered during runtime. It is up to integration tests to check if the model binding works properly.

What we are going to do here instead is add the ModelError object explicitly to the ModelState and then assert on the response of the called method.

Remove method

Testing the remove method is pretty straightforward:

Remove method tests take care that valid response is returned and that object is indeed removed from the list.


This concludes the tests scenarios for our ShoppingCartController and we just want to summarize the general advice about unit testing. There are few guidelines or best practices you should strive for when writing unit tests. Respecting these practices will certainly make your (and life of your fellow developer) easier.

Unit tests should be readable

No one wants to spend time trying to figure out what is that your test does. Ideally, this should be clear just by looking at the test name.

Unit tests should be maintainable

We should try to write our tests in a way that minor changes to the code shouldn’t make us change all of our tests. The DRY (don’t repeat yourself) principle applies here, and we should treat our test code the same as the production code. This lowers the possibility that one day someone gets to the point where he/she needs to comment out all of our tests because it has become too difficult to maintain them.

Unit sets should be fast

If tests are taking too long to execute, it is probable that people will run them less often. That is certainly a bad thing and no one wishes to wait too long for tests to execute.

Unit tests should not have any dependencies

It is important that anyone who is working on the project can execute tests without the need to provide access to some external system or database. Tests need to run in full isolation.

Make tests trustworthy rather than just aiming for the code coverage

Good tests should provide us with the confidence that we will be able to detect errors before they reach production. It is easy to write tests that don’t assert the right things just to make them pass and to increase code coverage. But there is no point in doing that. We should try to test the right things to be able to rely on them when the time comes to make some changes to the code.


In this post, we’ve learned what unit testing is and how to set up the unit testing project with xUnit.

We’ve also learned the basic scenarios of testing the controller logic on some CRUD operations.

These examples should give you a great starting point for writing your own unit tests, and test the more complex projects.

Thanks for reading and hopefully this article will help you grasp the unit concepts and unit testing in ASP.NET Core a little bit better.