From 2df0e4df3afd116ab760207979711f5148e84fa1 Mon Sep 17 00:00:00 2001 From: abdulrahmanshabeekmohamed Date: Fri, 13 Dec 2024 19:00:18 +0530 Subject: [PATCH] updated unit testing hosted services --- CommonComponents/wwwroot/atom.xml | 2 +- SharedModels/WebAPILearningPath.cs | 2 +- .../UnitTestingHostedServicesInASPNET.razor | 135 ++++++++++-------- .../wwwroot/sitemap-blog-webapi.xml | 2 +- 4 files changed, 76 insertions(+), 65 deletions(-) diff --git a/CommonComponents/wwwroot/atom.xml b/CommonComponents/wwwroot/atom.xml index 0bf7ea6f93..f2d3ccc54e 100644 --- a/CommonComponents/wwwroot/atom.xml +++ b/CommonComponents/wwwroot/atom.xml @@ -583,7 +583,7 @@ https://ilovedotnet.org/blogs/unit-testing-hosted-services-in-asp-net-webapi https://ilovedotnet.org/blogs/unit-testing-hosted-services-in-asp-net-webapi In this post I will teach how to unit test hosted services in ASP.NET web api. All with live working demo. - Sun, 13 Aug 2023 22:30:00 +0530 + Sun, 15 Dec 2024 22:30:00 +0530 Improving performance and memory use while accessing APIs using HTTPClient in dotnet diff --git a/SharedModels/WebAPILearningPath.cs b/SharedModels/WebAPILearningPath.cs index fd7551eca9..e61f08eb4e 100644 --- a/SharedModels/WebAPILearningPath.cs +++ b/SharedModels/WebAPILearningPath.cs @@ -209,7 +209,7 @@ public WebAPILearningPath() Channel = "WebAPI", Type = "blogs", CreatedOn = new DateTime(2023, 8, 13, 22, 30, 0, DateTimeKind.Utc), - ModifiedOn = new DateTime(2023, 8, 13, 22, 30, 0, DateTimeKind.Utc), + ModifiedOn = new DateTime(2024, 12, 15, 22, 30, 0, DateTimeKind.Utc), Keywords = ["Unit Test", "Hosted Service", "Background Service"] }, new ContentMetaData diff --git a/WebAPIDemoComponents/Pages/Blogs/UnitTestingHostedServicesInASPNET.razor b/WebAPIDemoComponents/Pages/Blogs/UnitTestingHostedServicesInASPNET.razor index 5c011357ca..a1ed6e7bae 100644 --- a/WebAPIDemoComponents/Pages/Blogs/UnitTestingHostedServicesInASPNET.razor +++ b/WebAPIDemoComponents/Pages/Blogs/UnitTestingHostedServicesInASPNET.razor @@ -3,66 +3,56 @@ -

- 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

+

Table of Contents

-
    +
    1. - - Introduction + + What we gonna do?
    2. - - Why Unit Testing? + + Why we gonna do?
    3. - - What is a Hosted Service? + + How we gonna do?
    4. - - Unit Testing Hosted Service - -
    5. -
    6. - + Summary
    -

    Introduction

    +

    What we gonna do?

    + +

    + In this article, let's learn about how to unit test Hosted Services in WebAPI in ASP.NET Core. +

    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
      • +
      • Performing data migration
      • +
      • Syncing data between two data sources
      • 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. + 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.

      - - -

      Why Unit Testing ?

      +

      Why we gonna do?

      When writing software, we want to ensure that the code is covered by tests, which verify the required behavior and catch any regressions. @@ -70,7 +60,7 @@ 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.
        • @@ -78,48 +68,26 @@

          Note: If you have not done so already, I recommend you read the article on - Implementing TDD in C# .Net. + 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

          +

          How we gonna do?

          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. + 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.

          - -

          To unit test the DataMigrationService Hosted Service, follow these steps:

          -
            +
            1. - Create a new test class, let's call it HostedSrviceTests, and add a test method + Create a new test class, let's call it HostedServiceTests, and add a test method using the [Fact] attribute.
            2. @@ -160,15 +128,58 @@ - +

              + Here is an another examples of background service using PeriodicTimer to Sync data. Let's see how to unit test this service. +

              + +

              - 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. + To unit test the DataSyncService Hosted Service, follow these steps:

              - +
                +
              1. + Create a new test class, let's call it HostedServiceTests, and add a test method + using the [Fact] attribute. +
              2. +
              3. + In the test method, instantiate a FakeTimeProvider To adjust time and test. This is available from + Microsoft.Extensions.TimeProvider.Testing namespace. +
              4. +
              5. + Finally let's use FakeLogger<DataSyncService> from + Microsoft.Extensions.Diagnostics.Testing + namespace instead of Mocking it as we are going to test the logger. Moreover mocking Logger is a + complex step. +
              6. +
              7. + Then, instantiate the DataSyncService class with the above instantiated parameters and call the + StartAsync method with default CancellationToken to start the service. +
              8. +
              9. + Now call ExecuteTask from the DataSyncService class to + execute the task. This will make the ExecuteAsync of actual background service to run. +
              10. +
              11. + Now adjust the time using by calling Advance from FakeTimeProvider. + This will execute the SyncData callback passed to the periodic timer in the + DataSyncService Background Service. +
              12. +
              13. + Perform assertions using the IsCompletedSuccessfully result on the + ExecuteTask of DataSyncService. Check for its success. +
              14. +
              15. Additionally, make assertions as per your needs.
              16. +
              + + + +

              + 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

              +

              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 diff --git a/WebAPIDemoComponents/wwwroot/sitemap-blog-webapi.xml b/WebAPIDemoComponents/wwwroot/sitemap-blog-webapi.xml index 598ec05056..17c617830b 100644 --- a/WebAPIDemoComponents/wwwroot/sitemap-blog-webapi.xml +++ b/WebAPIDemoComponents/wwwroot/sitemap-blog-webapi.xml @@ -68,7 +68,7 @@ https://ilovedotnet.org/blogs/unit-testing-hosted-services-in-asp-net-webapi - 2023-08-13T22:30:00+05:30 + 2024-12-15T22:30:00+05:30 weekly 0.5