C#C
C#3mo ago
28 replies
TauFrisch

Populating IOptions in integration tests

Hi, I'm struggling with IOptions when building integration tests specifically, as I'm getting the 'InvalidOperationException: Section 'MySection' not found in configuration' on startup. Those options are mandatory.

I know two approach, which both didn't seem to work. First is with AddInMemoryCollection

protected override void ConfigureWebHost(IWebHostBuilder builder)
    {
        builder.ConfigureAppConfiguration((context, configBuilder) =>
        {
            var inMemorySettings = new Dictionary<string, string?>
            {
                { "ConnectionStrings:DefaultConnection", connectionString },
                { "MySection:SomeAttribute", "Hello there!" },
            };
            configBuilder.AddInMemoryCollection(inMemorySettings);
        });
        // ....
    }


here I have no idea why I have no problem with the connection string, but with the option.

Second approach I tried was to add a testing appsettings:

protected override void ConfigureWebHost(IWebHostBuilder builder)
    {
        builder.ConfigureAppConfiguration((context, configBuilder) =>
        {
            var inMemorySettings = new Dictionary<string, string?>
            {
                { "ConnectionStrings:DefaultConnection", connectionString }
            };
            configBuilder.AddInMemoryCollection(inMemorySettings);
            configBuilder
                .SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile("appsettings.Integrationtests.json", optional: false, reloadOnChange: true);
        });
        // ....
    }


which I expected to work ... but it didn't either.

So I guess I'm making a pretty obvious mistake, but I don't see it.
I hope somebody can help me
Was this page helpful?