Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HostBuilder in Unit Test: HostContext.Configuration.GetSection returns value null

Tags:

c#

.net-core

I'm trying to use the HostBuilder class in an MsTest test case in the following way:

        [TestMethod]
        public  void SomeTest()
        {
            var builder = new HostBuilder()
                .ConfigureAppConfiguration((hostingContext, config) =>
                {
                    config.AddJsonFile("appsettings.json", optional: true);
                })
                .ConfigureServices((hostContext, services) =>
                {
                    var section = hostContext.Configuration.GetSection("AppConfig");
                    Assert.IsNotNull(section.Value, "Appconfig sections was not loaded");
                });
            var host = builder.Build();
        }

So I've an appsettings.json file that is added to the config object.

Problem: When calling hostContext.Configuration.GetSection("AppConfig") section.Value is null (Assert is fired up). If I debug the code I can see that hostContext.Configuration has an JsonConfigurationProvider which has parsed the appropriate values defined in appsettings.json.

Environment: netcoreapp3.1

Update1: I've uploaded the source code to Github.

Any help would be appreciated.

Thx.

like image 986
Moerwald Avatar asked Sep 13 '26 21:09

Moerwald


1 Answers

Not sure if you were able to resolve this, but I ran into a similar problem as well! How I was able to resolve it was that upon inspection of appsettings.json properties, it appears that the default action for this file was never. Hence, when the project was built in the target folder the appsettings.json file was never copied over. Changing this setting to "copy always" or "copy if newer" solved it and now I get the updated json file in the target executing folder.

The code you have up there seems to be fine -- mine is very similar.

To test if this is the problem indeed you have, change

config.AddJsonFile("appsettings.json", optional: true);

to

config.AddJsonFile("appsettings.json", optional: false);

This will force the app to fail if the file doesn't exist. this was also how I found the problem after an embarrasingly long amount of time.

To check the properties of this file, right click on it on the solution explorer and select properties. In the default VS 2019, the properties panel is right below the solution explorer.

like image 113
soler Avatar answered Sep 16 '26 20:09

soler



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!