Using ASP.NET Core's ConfigurationBuilder in a Test Project

后端 未结 4 1595
天涯浪人
天涯浪人 2021-02-13 03:21

I want to use the IHostingEnvironment and ConfigurationBuilder in my functional test project, so that depending on the environment the functional tests

4条回答
  •  情话喂你
    2021-02-13 04:26

    I'll add this answer here for completeness, as I experienced the same issue as @vaindil describes in Will's answer here. The reason was that we populated our IConfiguration from environment variables in the code under test. This overrode any config we set in test using say an appsettings.json. Our solution was to create environment variables for the test process using System.Environment.SetEnvironvironmentVariable("variableName", "variableValue")

    Effectively, the instance of WebHostBuilder in our tests is created the same as our hosted API:

    // Code omitted for brevity
    var builder = new WebHostBuilder()                 
                    .UseEnvironment("Development")
                    .ConfigureAppConfiguration(configurationBuilder => configurationBuilder.AddEnvironmentVariables())
                    .UseStartup();
    
    var testServer = new TestServer(builder); // test against this
    

提交回复
热议问题