我的 Web 应用程序需要从 appsettings.json 文件中读取文档数据库密钥.我创建了一个具有键名的类,并在 ConfigureServices() 中阅读了 Config 部分:
My Web application needs to read the Document DB keys from appsettings.json file. I have created a class with the key names and reading the Config section in ConfigureServices() as:
public Startup(IHostingEnvironment env) { var builder = new ConfigurationBuilder() .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true) .AddEnvironmentVariables(); Configuration = builder.Build(); } public IConfigurationRoot Configuration { get; } public void ConfigureServices(IServiceCollection services) { services.AddMvc().AddJsonOptions(options => options.SerializerSettings.ContractResolver = new DefaultContractResolver()); services.AddSession(); Helpers.GetConfigurationSettings(services, Configuration); DIBuilder.AddDependency(services, Configuration); }我正在寻找读取测试项目中键值的方法.
I'm looking for the ways to read the Key values in Test project.
推荐答案这是基于博客文章 在 .NET Core 单元测试项目中使用配置文件(为 .NET Core 1.0 编写).
This is based on the blog post Using Configuration files in .NET Core Unit Test Projects (written for .NET Core 1.0).
在集成测试项目根目录中创建(或复制)appsettings.test.json,并在属性中指定Build Action";作为内容和如果更新则复制"到输出目录.请注意,文件名(例如 appsettings.test.json )最好与普通的 appsettings.json 不同,因为主项目中的文件可能会覆盖来自测试项目的文件,如果将使用相同的名称.
Create (or copy) the appsettings.test.json in the Integration test project root directory, and in properties specify "Build Action" as Content and "Copy if newer" to Output Directory. Note that it’s better to have file name (e.g. appsettings.test.json ) different from normal appsettings.json, because it is possible that a file from the main project override the file from the test project, if the same name will be used.
如果尚未包含,请包含 JSON 配置文件 NuGet 包 (Microsoft.Extensions.Configuration.Json).
Include the JSON Configuration file NuGet package (Microsoft.Extensions.Configuration.Json) if it's not included yet.
在测试项目中创建一个方法,
In the test project create a method,
public static IConfiguration InitConfiguration() { var config = new ConfigurationBuilder() .AddJsonFile("appsettings.test.json") .AddEnvironmentVariables() .Build(); return config; }AddEnvironmentVariables(建议在 @RickStrahl 博客 ) 如果您想传递一些您不希望存储在 appsettings.test.json 中的秘密
AddEnvironmentVariables (suggested in @RickStrahl blog ) is useful if you want to pass some secrets, that you prefer not store in appsettings.test.json
照常使用配置
Use the configuration as usual var config = InitConfiguration(); var clientId = config["CLIENT_ID"]
顺便说一句:您也可能对将配置读入 IOptions 类感兴趣,如与 IOptions 的集成测试在 .NET Core 中:
BTW: You also may be interesting in reading the configuration into the IOptions class as described in Integration test with IOptions<> in .NET Core:
var options = config.Get<MySettings>();更多推荐
读取 .NET Core 测试项目中的 appsettings json 值
发布评论