Integration Test For Hosted Service .Net-Core`

后端 未结 1 1151
挽巷
挽巷 2020-12-16 14:05

I have a QueueTask Hosted service (.Net-Core\'s new background service) that I\'d like to test. My queuedHosted service looks like so:

public QueuedHostedSe         


        
相关标签:
1条回答
  • 2020-12-16 14:32

    Hosted services are started by the framework as part of the WebHost's start process

    // Fire IHostedService.Start
    await _hostedServiceExecutor.StartAsync(cancellationToken).ConfigureAwait(false);
    

    Source

    via the HostedServiceExecutor which would take a collection of all the registered IHostedService, enumerate them and start them in turn

    public HostedServiceExecutor(ILogger<HostedServiceExecutor> logger, IEnumerable<IHostedService> services)
    {
        _logger = logger;
        _services = services;
    }
    
    public async Task StartAsync(CancellationToken token)
    {
        try
        {
            await ExecuteAsync(service => service.StartAsync(token));
        }
        catch (Exception ex)
        {
            _logger.ApplicationError(LoggerEventIds.HostedServiceStartException, "An error occurred starting the application", ex);
        }
    }
    

    Source

    But since you are testing the hosted service on its own, you have to act as the framework and start the service yourself.

    [TestMethod]
    public async Task Verify_Hosted_Service_Executes_Task() {
        IServiceCollection services = new ServiceCollection();
        services.AddSingleton<ILoggerFactory, NullLoggerFactory>();
        services.AddHostedService<QueuedHostedService>();
        services.AddSingleton<IBackgroundTaskQueue, BackgroundTaskQueue>();
        var serviceProvider = services.BuildServiceProvider();
    
        var service = serviceProvider.GetService<IHostedService>() as QueuedHostedService;
    
        var backgroundQueue = serviceProvider.GetService<IBackgroundTaskQueue>();
    
        await service.StartAsync(CancellationToken.None);
    
        var isExecuted = false;
        backgroundQueue.QueueBackgroundWorkItem(async (sp, ct) => {
            isExecuted = true;
        });
    
        await Task.Delay(10000);
        Assert.IsTrue(isExecuted);
    
        await service.StopAsync(CancellationToken.None);
    }
    
    0 讨论(0)
提交回复
热议问题