在测试项目中使用ASP.NET Core的ConfigurationBuilder [英] Using ASP.NET Core's ConfigurationBuilder in a Test Project
问题描述
我想在我的功能测试项目中使用 IHostingEnvironment
和 ConfigurationBuilder
,以便根据环境,功能测试使用不同的配置集运行.我想利用下面的代码:
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();
}
我想要一个 appSettings.json
和 appSettings.Production.json
文件,以将功能测试指向生产环境.这可能吗?如何实现?我需要一个 IHostingEnvironment
的实例.
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
.
推荐答案
您可以通过几个步骤在测试项目中使用 ConfigurationBuilder
.我认为您本身不需要 IHostingEnvironment
接口.
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.
首先,向您的项目中添加两个具有 ConfigurationBuilder
扩展方法的NuGet软件包:
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.
这篇关于在测试项目中使用ASP.NET Core的ConfigurationBuilder的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!