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

后端 未结 4 1590
天涯浪人
天涯浪人 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:28

    I added an appsettings.Development.json to the root of my test project. Then I added the appsettings file via the .ConfigureAppConfiguration() method. It will then call the main application's Startup() method but use the configuration settings in appsettings.Development.json.

    
        string Environment = "Development";
    
        var server = new TestServer(new WebHostBuilder()                
            .UseEnvironment(Environment)
            .ConfigureAppConfiguration(x => {
                x.SetBasePath(Directory.GetCurrentDirectory());
                x.AddJsonFile($"appsettings.{Environment}.json", optional: false, reloadOnChange: true);
                x.AddEnvironmentVariables();
                })
            .UseStartup()                
            );
    
        httpClient = server.CreateClient();
    
    

    The httpClient can then be used to e.g. make web requests such as:

    var response = await httpClient.GetAsync(url);
    var responseString = await response.Content.ReadAsStringAsync();
    

提交回复
热议问题