c# - 读取 .NET Core 测试项目中的 appsettings json 值

标签 c# unit-testing asp.net-core appsettings

我的 Web 应用程序需要从 appsettings.json 文件中读取文档数据库键。我创建了一个带有键名的类并阅读了 ConfigureServices() 中的配置部分如:

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);
}
我正在寻找读取测试项目中关键值的方法。

最佳答案

这是基于博客文章 Using Configuration files in .NET Core Unit Test Projects (为 .NET Core 1.0 编写)。

  • 在集成测试项目根目录中创建(或复制)appsettings.test.json,并在属性中将“构建操作”指定为内容并将“如果更新则复制”到输出目录。请注意,文件名(例如 appsettings.test.json )最好与正常的 appsettings.json 不同,因为如果将使用相同的名称,则主项目中的文件可能会覆盖测试项目中的文件。
  • 如果尚未包含,请包含 JSON 配置文件 NuGet 包 (Microsoft.Extensions.Configuration.Json)。
  • 在测试项目中创建一个方法,
    public static IConfiguration InitConfiguration()
            {
                var config = new ConfigurationBuilder()
                    .AddJsonFile("appsettings.test.json")
                    .Build();
                    return config;
            }
    
  • 照常使用配置
    var config = InitConfiguration();
    var clientId = config["CLIENT_ID"]
    

  • 顺便说一句:您也可能对将配置读入 IOptions 类感兴趣,如 Integration test with IOptions<> in .NET Core 中所述。 :
    var options = config.Get<MySettings>();
    

    关于c# - 读取 .NET Core 测试项目中的 appsettings json 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39791634/

    相关文章:

    c# - 托管的 PowerShell 在同一程序集中看不到 Cmdlet

    c# - CA2202 ForEach 循环警告

    c# - 当 Assert 语句在不同的方法中时使用 NUnit Multiple Assert

    javascript - ASP.net 项目图像按钮仅在双击时重定向到另一个页面

    hibernate - 域类的Grails单元测试(Gorm)

    android - 如何在 Mockito3.x 中使用 PowerMock?

    c# - 如何为 MVC .Net Core 应用创建单个管理员用户

    c# - 添加迁移 : A parameter cannot be found that matches parameter name 'Context'

    swift - 如何使用 XCTAssert 验证类方法是否被调用?

    c# - asp.net core (mvc) ViewModel请求主键