Unit Testing Hosted Services in ASP.NET WEB API
WebAPI
19 Articles
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
Introduction
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
they support 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 abstract
concept
of a 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
Microsoft.Extensions.Hosting
namespace.
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 itHostedSrviceTests
, and add a test method using the[Fact]
attribute. -
In the test method, instantiate a
DataMigrationChannel
which we used in previous article andServiceCollection
from theMicrosoft.Extensions.DependencyInjection
namespace
. This collection will act as the container for our services. -
Use
Moq
to Mock theIUnitOfWork
and add it to theServiceCollection
and callBuildServiceProvider()
to build theServiceProvider
instance. -
Finally let's use
NullLogger<DataMigrationService>.Instance
fromMicrosoft.Extensions.Logging.Abstractions
namespace
instead of Mocking it as we are not going to test the logger. Moreover mocking Logger is a complex step. -
Next Call the
MigrateData
method in theDataMigrationChannel
object to add message to the channel. -
Then, instantiate the
DataMigrationService class
with the above instantiated parameters and call theStartAsync
method withdefault CancellationToken
to start the service. -
Now call
ExecuteTask
from theDataMigrationService
class to execute the task. This will make theExecuteAsync
of actual background service to run. -
Perform
assertions
using theIsCompletedSuccessfully
result on theExecuteTask
ofDataMigrationService
. Check for its success. - Additionally, verify
IUnitOfWork
usingMoq Verify
methods.
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.
Summary
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.