【发布时间】:2021-10-15 20:03:26
【问题描述】:
我正在使用 .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);
}
我已经找到了这个帖子:Integration Test for Hosted Service in .NET Core
但它是为 QueuedBackgroundService 解释的,我真的不知道我是否可以以同样的方式测试我的。
我只想知道我的代码是否被执行。我不想要任何具体的结果。 你知道我该如何测试它吗?
【问题讨论】:
-
您应该能够遵循相同的格式。模拟依赖并注入它们,调用被测方法并断言预期的行为
标签: c# .net-core asp.net-core-hosted-services