Во время модульного тестирования фоновой службы. Net core 3.1, не удается разрешить IConfiguration - PullRequest
2 голосов
/ 25 февраля 2020

Я пытаюсь написать тестовый блок для BackgroundService Worker.cs. Я прочитал Вопрос переполнения стека

Но все равно я получаю сообщение об ошибке

"Невозможно разрешить службу для типа" Microsoft.Extensions.Configuration.IConfiguration " при попытке активировать 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);
}

1 Ответ

2 голосов
/ 25 февраля 2020

Я не вижу, куда вы добавляете IConfiguration в коллекцию сервисов. Вы создаете его в конструкторе, но не добавляете его в коллекцию сервисов в тесте.

[Fact]
public async Task ExecuteAsync_Test() {

    IServiceCollection services = new ServiceCollection();
    services.AddSingleton<IConfiguration>(_config);

    //...
...