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

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

    You can use the ConfigurationBuilder in a test project with a couple of steps. I don't think you will need the IHostingEnvironment interface itself.

    First, add two NuGet packages to your project which have the ConfigurationBuilder extension methods:

    "dependencies": {
      "Microsoft.Extensions.Configuration.EnvironmentVariables": "1.0.0-rc1-final",
      "Microsoft.Extensions.Configuration.Json": "1.0.0-rc1-final"
    }
    

    Second, put your desired environment variables into the test project's properties:

    Then you can create your own builder in the test project:

    private readonly IConfigurationRoot _configuration;
    
    public BuildConfig()
    {
        var environmentName = Environment.GetEnvironmentVariable("Hosting:Environment");
    
        var config = new ConfigurationBuilder()
            .AddJsonFile("appsettings.json")
            .AddJsonFile($"appsettings.{environmentName}.json", true)
            .AddEnvironmentVariables();
    
        _configuration = config.Build();
    }
    

    If you want to use precisely the same settings file (not a copy), then you'll need to add in a path to it.

提交回复
热议问题