You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

99 lines
3.6 KiB
C#

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

using Microsoft.Extensions.Configuration;
namespace OptionStudy.UnitApp
{
/// <summary>
/// 5.1.6 根据环境动态加载配置文件
/// </summary>
public class DynamicLoadConfigFileTest : IDisposable
{
private readonly ITestOutputHelper? testOutput;
public DynamicLoadConfigFileTest(ITestOutputHelperAccessor helperAccessor)
{
testOutput = helperAccessor.Output;
}
/// <summary>
/// 动态加载json配置文件
/// </summary>
[Theory]
[InlineData("product")]
[InlineData("development")]
[InlineData("custom")]
public void LoadJsonFile_ByPara_Test(string env)
{
var config = new ConfigurationBuilder()
.AddJsonFile($"Configs/appsettings.{env}.json", true, true)
.Build();
var appOption = config.Get<AppOption>();
//断言
Assert.NotNull(appOption);
Assert.Equal($"{env}AppNmae", appOption.AppName);
Assert.Equal("0.0.0.1", appOption.AppVersion);
//子配置节父配置对象的属性名必须和配置KEY保持一致否则不能自动绑定。
Assert.NotNull(appOption.EMail);
Assert.Equal($"{env}@163.com", appOption.EMail.ReceiveAddress);
Assert.Equal($"{env}", appOption.EMail.Recipient);
testOutput?.WriteLine("根据参数名动态加载json配置文件");
}
/// <summary>
/// 根据环境变量动态加载json配置文件
/// 环境变量类别:系统环境变量、用户环境变量、进程环境变量
/// 环境变量使用:
/// 1、对操作系统设置
/// 2、项目启动文件项目/Properties/launchSettings.json
/// 3、编程实现 System.Environment.SetEnvironmentVariable("环境变量名","值",环境变量类型)
/// 4、使用cmd命令行参数运行程序
/// <code>
/// set 环境变量名=环境变量值
/// dotnet xx.dll
/// # 或者
/// xx.exe
/// </code>
/// </summary>
[Theory]
[InlineData("product")]
[InlineData("development")]
[InlineData("custom")]
public void LoadJsonFileByEnv_Test(string env)
{
//设置进程系统变量为参数值
var envName = "DOTNET_XUNIT_TEST";
//设置进程环境变量
System.Environment.SetEnvironmentVariable(envName, env, EnvironmentVariableTarget.Process);
//获取变量值
var envValue = System.Environment.GetEnvironmentVariable(envName, EnvironmentVariableTarget.Process);
var config = new ConfigurationBuilder()
.AddJsonFile($"Configs/appsettings.json", false, true)
.AddJsonFile($"Configs/appsettings.{envValue}.json", true, true)
.Build();
var appOption = config.Get<AppOption>();
//断言
Assert.NotNull(appOption);
Assert.Equal($"{envValue}AppNmae", appOption.AppName);
Assert.Equal("0.0.0.1", appOption.AppVersion);
//子配置节父配置对象的属性名必须和配置KEY保持一致否则不能自动绑定。
Assert.NotNull(appOption.EMail);
Assert.Equal($"{envValue}@163.com", appOption.EMail.ReceiveAddress);
Assert.Equal($"{envValue}", appOption.EMail.Recipient);
testOutput?.WriteLine("根据环境变量值动态加载json配置文件");
}
public void Dispose()
{
}
}
}