title: How can I write unit test for my background service?
body: <p>I'm working with the HostBuilder in .NET Core (not the WebHost !).</p>
  <p>I have one Hosted Service running in my application that overrides the ExecuteAsync/StopAsync methods of the background Service and I want to unit test it.</p>
  <p>Here is my HostedService:</p>
  <pre class="lang-cs prettyprint-override"><code>public class DeviceToCloudMessageHostedService : BackgroundService
  {
      private readonly IDeviceToCloudMessageService _deviceToCloudMessageService;
      private readonly AppConfig _appConfig;
  
      public DeviceToCloudMessageHostedService(IDeviceToCloudMessageService deviceToCloudMessageService, IOptionsMonitor&lt;AppConfig&gt; appConfig)
      {
          _deviceToCloudMessageService = deviceToCloudMessageService;
          _appConfig = appConfig.CurrentValue;
      }
  
      protected override async Task ExecuteAsync(CancellationToken stoppingToken)
      {
          while (!stoppingToken.IsCancellationRequested)
          {
              await _deviceToCloudMessageService.DoStuff(stoppingToken);
              await Task.Delay(_appConfig.Parameter1, stoppingToken);
          }
      }
      
      public override Task StopAsync(CancellationToken cancellationToken)
      {
          Log.Information(&quot;Task Cancelled&quot;);
          _deviceToCloudMessageService.EndStuff();
          return base.StopAsync(cancellationToken);
      }
  </code></pre>
  <p>I already found this post: <a href="https://stackoverflow.com/questions/51224146/integration-test-for-hosted-service-net-core">Integration Test for Hosted Service in .NET Core</a></p>
  <p>But it's explained for a QueuedBackgroundService and I don't really know if I can test mine the same way.</p>
  <p>I just want to know if my code is executed. I don't want any specific result.
  Do you have any idea of how I can test it?</p>