In this article, let's learn about how to unit test
Hosted Services in
WebAPI in ASP.NET Core.
Note: If you have not done so already, I recommend you read the article on Perform Background Workloads in Hosted Service using Channels in ASP.NET Web API.
Table of Contents
In ASP.NET Core,
hosted services plays a vital role in simplifying background jobs which needs to run periodically
to perform operations. Most common use cases include:
Processing uploaded excel in background
Sending emails in background
Other long running operations, etc
If you are aware of
Hosted Service and
Unit Testing then you can skip the
next two sections and jump to the section on
Unit Testing Hosted Service.
Why Unit Testing ?
When writing software, we want to ensure that the code is covered by tests, which verify the required behavior and catch any regressions.
Unit testing is a crucial practice in software development as it helps identify issues early in the development
process. When it comes to service registration, unit testing offers the following benefits:
Validation: Unit tests verify that the necessary services are registered correctly, avoiding runtime errors caused by missing or misconfigured dependencies.
Refactoring: Unit tests provide a safety net when refactoring code by ensuring that service registration remains intact during code changes.
Documentation: Well-written unit tests serve as living documentation, illustrating how services should be registered and ensuring consistency across the application.
Note: If you have not done so already, I recommend you read the article on Implementing TDD in C# .Net.
What is a Hosted Service ?
Hosted services in ASP.NET Core have been available since
version 2.1, and
performing background tasks outside of the main requests flow. The best way to understand when and
where hosted services can be applied is to begin using them. Hosted services are based on the
background service. The terms
hosted service and
background service are often used interchangeably. I'll refer to them by both names throughout this article. Hosted services are available under
To know more about
Hosted Service or
Background Service is outside the scope
of this article. I'll write a separate article on Background Services in ASP.NET Core. For now lets understand walkthrough how to use Hosted Service.
Unit Testing Hosted Service
We are going to write unit tests for the
Data Migration Hosted Service which we used in our previous article on
Perform Background Workloads in Hosted Service using Channels in ASP.NET Web API.
Here is the quick reference of the hosted service used in that article.
Code Sample - Data Migration Hosted Service
To unit test the
DataMigrationService Hosted Service, follow these steps:
Create a new test
class, let's call it
HostedSrviceTests, and add a test method using the
In the test method, instantiate a
DataMigrationChannelwhich we used in previous article and
namespace. This collection will act as the container for our services.
Moqto Mock the
IUnitOfWorkand add it to the
BuildServiceProvider()to build the
Finally let's use
namespaceinstead of Mocking it as we are not going to test the logger. Moreover mocking Logger is a complex step.
Next Call the
MigrateDatamethod in the
DataMigrationChannelobject to add message to the channel.
Then, instantiate the
DataMigrationService classwith the above instantiated parameters and call the
default CancellationTokento start the service.
DataMigrationServiceclass to execute the task. This will make the
ExecuteAsyncof actual background service to run.
IsCompletedSuccessfullyresult on the
DataMigrationService. Check for its success.
- Additionally, verify
Code Sample - Unit Testing Hosted Service in ASP.NET Web API
By executing above test we can validate background services in ASP.NET Core apps. The same can be used to validate worker services in dotnet.
Unit testing hosted services in ASP.NET Core is a crucial step to ensure that they are working as expected. By writing unit tests, you can
validate behavior, identify issues early on, and maintain a reliable and robust application. The examples and
techniques covered in this article provide a solid foundation for performing unit tests on hosted services, promoting software quality and
maintainability in ASP.NET Core applications.