Writing code that is testable is a good practice. In my very recent experience in a project involving TDD, I realized that writing unit tests ensures the code follows SOLID principles. With unit tests, you are enforced to decouple the components and make them highly cohesive.
Even though testing integrations such as Database connections, File I/O do fall under “Integration testing”, as a developer you should ensure the testability of the logic underneath. In the same previously mentioned project I have come-across a situation where I need to retrieve information from Azure Table Storage, perform some manipulations on it and present it in an API response. In this post I shall discuss how did I ensured the unit testability of the code I wrote with the help of the built in DI framework in ASP.NET Core.
Configure Cloud Table Service
In ASP.NET Core,
void ConfigureServices(IServiceCollection services) is used to add services to the container. This is the place where we inject the dependency for the
CloudTable which is a singleton object for the life time. So we shall use the following code:
INJECT THE DEPENDENCY IN CONTROLLER
The below is how the dependency for the
CloudTable is injected to the controller, its nothing new:
Unit Testing the Controller Action
To unit test, first we need to mock the
ExecuteQuery behavior in this case. The
CloudTable class has no parameter-less constructors but fortunately this is not a sealed class. So lets create a derived class and use that to mock the behavior (just to make the unit test code look simple).
Along with that lets write a test method to make sure
GetAllEntities action must return more that one entities, if it they are passed – for example.
The above is just an example to demonstrate the unit testability of the logic we’ve written involving
CloudTable class with the help of ASP.NET Core DI framework. Like wise, you shall also mock the
ExecuteAsync behavior to ensure the testability of the code that involves in writing the data back to the Azure Table Storage.
Notes: In my case, I had to write the Cloud Table Execute Query logic in the action itself. But this also can be written in a separate utility class as well, and that utility class also can be unit tested in the same manner.