using Microsoft.Extensions.Configuration; namespace OptionStudy.UnitApp { /// /// 5.1.3 读取结构化配置信息 /// public class LoadStructuredConfigTest : IDisposable { private readonly ITestOutputHelper? testOutput; public LoadStructuredConfigTest(ITestOutputHelperAccessor helperAccessor) { testOutput = helperAccessor.Output; } /// /// 读取结构键值对配置 /// 关键点:以:分隔 /// [Fact] public void ReadKeyValue_Test() { //配置字典 var source = new Dictionary() { ["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() { } } }