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.

67 lines
2.0 KiB
C#

using Microsoft.Extensions.Configuration;
namespace OptionStudy.UnitApp
{
/// <summary>
/// 5.1.3 读取结构化配置信息
/// </summary>
public class LoadStructuredConfigTest : IDisposable
{
private readonly ITestOutputHelper? testOutput;
public LoadStructuredConfigTest(ITestOutputHelperAccessor helperAccessor)
{
testOutput = helperAccessor.Output;
}
/// <summary>
/// 读取结构键值对配置
/// 关键点:以:分隔
/// </summary>
[Fact]
public void ReadKeyValue_Test()
{
//配置字典
var source = new Dictionary<string, string?>()
{
["AppName"] = "MemoryAppName",
["AppVersion"] = "2.1.2.3",
["EMail:ReceiveAddress"] = "memory@163.com",
["EMail:Recipient"] = "memory",
};
var config = new ConfigurationBuilder().AddInMemoryCollection(source).Build();
var appOption = new AppOption()
{
AppName = config["AppName"] ?? "",
AppVersion = config["AppVersion"] ?? "",
};
var emailConfig = config.GetSection("EMail");
var receiveMail = new ReceiveMailOption()
{
ReceiveAddress = emailConfig["ReceiveAddress"] ?? string.Empty,
Recipient = emailConfig["Recipient"] ?? string.Empty,
};
//断言
Assert.NotNull(appOption);
Assert.Equal("MemoryAppName", appOption.AppName);
Assert.Equal("2.1.2.3", appOption.AppVersion);
//子配置节:采用扁平化处理
Assert.NotNull(receiveMail);
Assert.Equal("memory@163.com", receiveMail.ReceiveAddress);
Assert.Equal("memory", receiveMail.Recipient);
testOutput?.WriteLine("读取结构化配置,关键点是:分隔!");
}
public void Dispose()
{
}
}
}