.NET 6单元测试项目迁移后无法读取App.config及CustomConfig报错
解决方案
1. 确认安装必要的NuGet包
确保单元测试项目已安装System.Configuration.ConfigurationManager NuGet包,版本需兼容.NET 6(推荐6.0及以上),这是使用传统ConfigurationManager API的基础。
2. 修改自定义配置节的定义
在app.config中,原.NET Framework的配置节定义可能为:
<section name="CustomConfig" type="System.Configuration.NameValueSectionHandler"/>
.NET 6中NameValueSectionHandler已不再被支持,需替换为AppSettingsSection,修改后:
<section name="CustomConfig" type="System.Configuration.AppSettingsSection, System.Configuration, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"/>
读取配置的代码可保持原有逻辑:
var customConfig = (NameValueCollection)ConfigurationManager.GetSection("CustomConfig"); var targetValue = customConfig["YourConfigKey"];
3. 确保配置文件正确输出
右键点击app.config文件,在属性中设置:
- 复制到输出目录:选择「如果较新则复制」或「始终复制」
- 生成操作:设置为「内容」
这能保证测试运行时配置文件被正确加载,避免AppSettings返回null的问题。
4. 改用.NET 6推荐的配置系统(可选)
若想脱离旧配置系统的限制,可切换到Microsoft.Extensions.Configuration:
- 安装
Microsoft.Extensions.Configuration.Json、Microsoft.Extensions.Configuration.BinderNuGet包 - 添加
appsettings.json文件,配置内容改为JSON格式:
{ "CustomConfig": { "Key1": "Value1", "Key2": "Value2" }, "ApplicationName": "TestApplication" }
- 在测试类中初始化配置:
private readonly IConfiguration _config; public YourTestClass() { _config = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("appsettings.json", optional: false) .Build(); } [Fact] public void VerifyConfigValues() { var appName = _config["ApplicationName"]; var customVal = _config["CustomConfig:Key1"]; // 也可绑定到强类型类 var customConfig = _config.GetSection("CustomConfig").Get<CustomConfigModel>(); } public class CustomConfigModel { public string Key1 { get; set; } public string Key2 { get; set; } }
5. 排查AppSettings返回null的额外要点
- 确认
app.config中appSettings节结构正确:
<appSettings> <add key="ApplicationName" value="YourAppName"/> </appSettings>
- 检查
.runsettings文件,确保未覆盖配置路径或禁用配置加载。
内容的提问来源于stack exchange,提问作者baibhav
相关产品推荐
相关产品推荐

