我正在使用 .NET Core 中的 HostBuilder(而不是 WebHost!)。
我的应用程序中有一个托管服务,覆盖了后台服务的 ExecuteAsync/StopAsync 方法,并且我想对其进行单元测试。
这是我的 HostedService:
public class DeviceToCloudMessageHostedService : BackgroundService
{
private readonly IDeviceToCloudMessageService _deviceToCloudMessageService;
private readonly AppConfig _appConfig;
public DeviceToCloudMessageHostedService(IDeviceToCloudMessageService deviceToCloudMessageService, IOptionsMonitor<AppConfig> 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("Task Cancelled");
_deviceToCloudMessageService.EndStuff();
return base.StopAsync(cancellationToken);
}
我已经找到了这篇文章:在.NET Core中测试托管服务的集成测试
但是它是针对QueuedBackgroundService解释的,我不确定是否可以用同样的方式来测试我的服务。
我只想知道我的代码是否被执行。我不需要任何特定的结果。 你有什么办法可以帮我测试吗?