Home > other >  Unit Test: How to get a Configure class from the ServiceCollection
Unit Test: How to get a Configure class from the ServiceCollection

Time:12-30

I am writing unit tests for my .Net Core 5 web application. In the Startup.cs, I have 4 different calls similar to the following:

services.Configure<ServicesSettings>(Configuration.GetSection("ServicesSettings"));

each injecting a different class. I have tried the following:

ServicesSettings _serviceSettings = services.BuildServiceProvider().GetService<ServicesSettings>();
Assert.NotNull(_serviceSettings);

but it returns null. I am surprised that I could not find a similar question. I tried to look at ServiceCollection, but could not find a method.

CodePudding user response:

get service for IOptions

IOptions<ServicesSettings> _serviceSettingOption = services.BuildServiceProvider().GetService<IOptions<ServicesSettings>>();
_serviceSetting = _serviceSettingOption.Value;

Assert.NotNull(_serviceSetting);

I believe you are unit testing config injection capability/functionality, which is not required

  • Related