.NET Core 中的单元测试托管服务

hav*_*vij 6 c# unit-testing .net-core asp.net-core-hosted-services

我有一个由 .NET Core 中的托管服务实现的后台任务。这个类中的逻辑很少:

public class IndexingService : IHostedService, IDisposable
{
    private readonly int indexingFrequency;

    private readonly IIndexService indexService;

    private readonly ILogger logger;

    private bool isRunning;

    private Timer timer;

    public IndexingService(ILogger<IndexingService> logger, IIndexService indexService, IndexingSettings indexingSettings)
    {
        this.logger = logger;
        this.indexService = indexService;

        this.indexingFrequency = indexingSettings.IndexingFrequency;
    }

    public void Dispose()
    {
        this.timer?.Dispose();
    }

    public Task StartAsync(CancellationToken cancellationToken)
    {
        this.timer = new Timer(this.DoWork, null, TimeSpan.Zero, TimeSpan.FromSeconds(this.indexingFrequency));
        return Task.CompletedTask;
    }

    public Task StopAsync(CancellationToken cancellationToken)
    {
        this.timer?.Change(Timeout.Infinite, 0);
        return Task.CompletedTask;
    }

    private void DoWork(object state)
    {
        if (this.isRunning)
        {
            // Log
            return;
        }

        try
        {
            this.isRunning = true;
            this.indexService.IndexAll();
        }
        catch (Exception e)
        {
            // Log, The background task should never throw.
        }
        finally
        {
            this.isRunning = false;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我的Startup样子:

public void ConfigureServices(IServiceCollection services)
{
    services.AddHostedService<IndexingService>();
    services.AddTransient<IIndexService, IndexService>();
    // 'IndexingSettings' is read from appsetting and registered as singleton
}
Run Code Online (Sandbox Code Playgroud)

如何对方法中的逻辑进行单元测试DoWork?问题是托管服务是由框架管理的,我不知道如何隔离此类。

Chr*_*att 7

不知道你所说的隔离班级是什么意思。这些并不神奇。ASP.NET Core 只是使用任何所需的依赖项实例化该类,然后调用StartAsync,然后StopAsync在应用程序关闭时调用。没有什么是您自己无法手动完成的。

换句话说,要对其进行单元测试,您需要模拟依赖项、实例化该类并调用StartAsync它。但是,我认为整体托管服务更适合集成测试。您可以将任何实际工作分解到帮助程序类中,这对于单元测试来说更加简单,然后只需对服务运行集成测试即可确保它通常执行其应该执行的操作。

  • 您有任何存储库/代码示例可以与我们分享吗? (2认同)