Using ASP.NET Core ConfigurationBuilder in a test project

I want to use IHostingEnvironment and ConfigurationBuilder in my functional test project, so depending on the environment, functional tests are performed using a different set of settings. I want to use the following code:

 public IConfigurationRoot ConfigureConfiguration(IHostingEnvironment hostingEnvironment) { var builder = new ConfigurationBuilder() .AddJsonFile("appsettings.json") .AddJsonFile($"appsettings.{hostingEnvironment.EnvironmentName}.json", true) .AddEnvironmentVariables(); return builder.Build(); } 

I want to have the appSettings.json and appSettings.Production.json file to indicate my functional tests in production. Is it possible? How can this be achieved? I need an instance of IHostingEnvironment .

+6
source share
2 answers

You can use ConfigurationBuilder in a test project with a few steps. I do not think that you will need the IHostingEnvironment interface IHostingEnvironment .

First add two NuGet packages to the project that have ConfigurationBuilder extension methods:

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

Secondly, put the necessary environment variables in the properties of the test project:

environment variable dialog

Then you can create your own builder in a 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 exactly the same settings file (not a copy), then you will need to add a path to it.

+7
source

This is possible, according to the ASP.NET Core documentation ( http://docs.asp.net/en/latest/fundamentals/configuration.html ) you can build this inside the Startup method and add the appSettings Environment Variables. If you specify an optional flag, you can use appSettings.Production.json for the production environment and appSettings.json for development if there is no appSettings.Development.json application. Appsettings {Env.EnvironmentName} .json is used only when the file is present, and backup is appsettings.json by default.

 public Startup(IHostingEnvironment env) { // Set up configuration providers. var builder = new ConfigurationBuilder() .AddJsonFile("appsettings.json") .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true); if (env.IsDevelopment()) { // For more details on using the user secret store see http://go.microsoft.com/fwlink/?LinkID=532709 builder.AddUserSecrets(); } builder.AddEnvironmentVariables(); Configuration = builder.Build(); } 
0
source

All Articles