Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I want to use the IHostingEnvironment and ConfigurationBuilder in my functional test project, so that depending on the environment the functional tests run using a different set of configuration. I want to make use of the code below:

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 an appSettings.json and appSettings.Production.json file to point my functional tests at production. Is this possible? How can it be achieved? I would need an instance of IHostingEnvironment.

like image 898
Muhammad Rehan Saeed Avatar asked Apr 29 '16 16:04

Muhammad Rehan Saeed


People also ask

How do I get value from IConfiguration?

Using IConfiguration The IConfiguration is available in the dependency injection (DI) container, so you can directly access JSON properties by simply injecting IConfiguration in the constructor of a controller or class. It represents a set of key/value application configuration properties.

Can you use C# in core?

Supports Multiple Languages: You can use C#, F#, and Visual Basic programming languages to develop . NET Core applications. You can use your favorite IDE, including Visual Studio 2017/2019, Visual Studio Code, Sublime Text, Vim, etc.


1 Answers

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:

environment variable dialog

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.

like image 103
Will Ray Avatar answered Oct 03 '22 19:10

Will Ray