在单元测试 .Net core 3.1 后台服务时,无法解析 IConfiguration [英] While Unit Testing a .Net core 3.1 Background Service, unable to resolve IConfiguration
本文介绍了在单元测试 .Net core 3.1 后台服务时,无法解析 IConfiguration的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试为 BackgroundService Worker.cs
编写单元测试用例.我已阅读堆栈溢出问题
I'm trying to write unit test case for the BackgroundService Worker.cs
. I have read Stack Overflow Question
但我仍然收到错误
尝试激活AutoClueArchiver.Worker"时,无法解析Microsoft.Extensions.Configuration.IConfiguration"类型的服务.
"Unable to resolve service for type 'Microsoft.Extensions.Configuration.IConfiguration' while attempting to activate 'AutoClueArchiver.Worker'.
public WorkerTests()
{
_config = new ConfigurationBuilder()
.AddJsonFile("appsettings.json", true, true)
.AddJsonFile("appsettings.Development.json", true, true)
.AddJsonFile("appsettings.local.json", true, true)
.AddJsonFile("\\charon.cmiprog.com\devinet\Configuration\" + "ApiEndpoints.json", false, true)
.AddJsonFile("ApiEndpoints.local.json", true, true)
.AddJsonFile("\\charon.cmiprog.com\devinet\Configuration\" + "Kafka.json", false, true)
.AddEnvironmentVariables().Build();
_mockedKafkaTopicConsumerManager =new Mock<IKafkaTopicConsumerManager>();
_mockedMessageProcessor=new Mock<IMessageProcessingCapable>();
}
[Fact]
public async Task ExecuteAsync_Test()
{
IServiceCollection services=new ServiceCollection();
services.AddSingleton<IConfigEntriesClientService, ConfigEntriesClientServiceInjectable>();
services.AddSingleton(typeof(IProducer), s => new KafkaProducer(s.GetRequiredService<IProducer<string, string>>(), s.GetRequiredService<IConfiguration>().GetValue<string>("Shared:Kafka:TopicSuffix")));
services.AddSingleton(typeof(IProducer<string, string>), c => new ProducerBuilder<string, string>(KafkaConfigs(c)).Build());
services.AddHttpClient();
services.AddScoped<IPolicyApiClient, PolicyApiClient>();
services.AddTransient<IFilterMessages, MessageFilter>();
services.AddTransient<IArchiveAutoClues, Archiver>();
services.AddTransient<IFileSystem, FileSystem>();
services.AddTransient<ISaveDocument, DocumentManager>();
services.AddTransient<IKafkaTopicConsumerManager, KafkaTopicConsumerManager>();
services.AddTransient<IMessageProcessingCapable, ConsumerInitializer>();
services.AddTransient<Consumer>();
services.AddTransient<IExceptionPublisher, ExceptionPublisher>();
services.AddTransient<IHttpContextAccessor, HttpContextAccessor>();
services.AddScoped(sp => new HttpClientHandler { AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate });
services.AddHttpClient<IBaseApiClient, BaseApiClient>().ConfigurePrimaryHttpMessageHandler(
sp => new HttpClientHandler { AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate }
);
var worker=services.AddHostedService<Worker>();
var serviceProvider=services.BuildServiceProvider();
var backgroundService = serviceProvider.GetService<IHostedService>() as Worker;
await backgroundService?.StartAsync(CancellationToken.None);
await Task.Delay(1000);
await backgroundService?.StopAsync(CancellationToken.None);
//await backgroundService.ExecuteAsync(new CancellationToken());
//Any way to access ExecuteAsync here since I get protection level error as
//ExecuteAsync is protected
_mockedKafkaTopicConsumerManager.Verify(c=>c.StartConsumption
(It.IsAny<CancellationToken>(),
_mockedMessageProcessor.Object,
It.IsAny<string>(),
It.IsAny<string>(),
It.IsAny<List<string>>(),
It.IsAny<string>(),
It.IsAny<int>()),Times.Once);
}
推荐答案
我没有看到您将 IConfiguration
添加到服务集合的位置.您在构造函数中构建了一个,但未将其添加到测试中的服务集合中.
I do not see where you add IConfiguration
to the service collection. You build one in the constructor but do not add it to the service collection in the test.
[Fact]
public async Task ExecuteAsync_Test() {
IServiceCollection services = new ServiceCollection();
services.AddSingleton<IConfiguration>(_config);
//...
这篇关于在单元测试 .Net core 3.1 后台服务时,无法解析 IConfiguration的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文