具有2个后台服务的集成测试
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了具有2个后台服务的集成测试相关的知识,希望对你有一定的参考价值。
我有一个点网核心项目,试图在我的两个BackgroundServices
之间编写集成测试。
下面是我当前的xUnit
测试:
[Fact]
public async Task FileWatcherIntegration()
IServiceCollection services = new ServiceCollection();
services.AddHostedService<FileWatcherService>();
services.AddHostedService<FailedTradesWorker>();
services.AddSingleton(fileWatcherOptions);
services.AddSingleton<ILogger<FileWatcherService>>(logger);
var serviceProvider = services.BuildServiceProvider();
var tradeServiceProdiver = tradeServices.BuildServiceProvider();
var fileWatcher = serviceProvider.GetService<IHostedService>() as FileWatcherService;
var tradeWorker = serviceProvider.GetService<IHostedService>() as FailedTradesWorker;
// act
await tradeWorker.StartAsync(CancellationToken.None);
await fileWatcher.StartAsync(CancellationToken.None);
/* Ommited */
await tradeWorker.StopAsync(CancellationToken.None);
await fileWatcher.StopAsync(CancellationToken.None);
// assert
Assert.True(File.Exists(fileWatcherOptions.DestinationPathAndName));
我的测试在行var fileWatcher = serviceProvider.GetService<IHostedService>() as FileWatcherService;
上失败,并显示错误消息:Unable to resolve service for type
为此测试设置我的服务的正确方法是什么?
答案
这看起来很奇怪:
var serviceProvider = services.BuildServiceProvider();
var tradeServiceProdiver = tradeServices.BuildServiceProvider();
var fileWatcher = serviceProvider.GetService<IHostedService>() as FileWatcherService;
var tradeWorker = serviceProvider.GetService<IHostedService>() as FailedTradesWorker;
我会使用一个服务提供者,并且会按其类型获得服务:
var serviceProvider = services.BuildServiceProvider();
var fileWatcher = serviceProvider.GetService<FileWatcherService>();
var tradeWorker = serviceProvider.GetService<FailedTradesWorker>();
以上是关于具有2个后台服务的集成测试的主要内容,如果未能解决你的问题,请参考以下文章