在.NET Core测试项目中读取appsettings json值 [英] Read appsettings json values in .NET Core Test Project

查看:271
本文介绍了在.NET Core测试项目中读取appsettings json值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的Web应用程序需要从appsettings.json文件读取Document DB密钥.我创建了一个具有键名的类,并在ConfigureaServices()中将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 ConfigureaServices() 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);
}

我正在寻找在Test项目中读取键值的方法.

I'm looking for the ways to read the Key values in Test project.

推荐答案

这是基于博客帖子

This is based on the blog post Using Configuration files in .NET Core Unit Test Projects (written for .NET Core 1.0).

  1. 在集成测试项目的根目录中创建(或复制)appsettings.test.json,并在属性中将"Build Action"指定为Content,将"Copy if newnew"复制到Output Directory.请注意,最好使用与常规appsettings.json不同的文件名(例如appsettings.test.json),因为如果使用相同的名称,则主项目中的文件可能会覆盖测试项目中的文件.

  1. 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")
                .Build();
                return config;
        }

  • 照常使用配置

  • Use the configuration as usual

    var config = InitConfiguration();
    var clientId = config["CLIENT_ID"]
    

  • 顺便说一句:您还可能很感兴趣,如

    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值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    相关文章
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆