c# - ConfigurationManager 在测试中看不到 NUnit appSettings 文件属性(链接的配置文件)

标签 c# .net unit-testing nunit

我有NUnit测试(版本2.6.4)测试。它使用 ConfigurationManager.AppSettings["foo"]app.config 文件(位于测试项目中)检索配置设置。这是我的 App.config 文件:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <appSettings file="bar.config">
    <add key="thisSettingIsVisible" value="yes, indeed"/>
  </appSettings>
</configuration>

这是 bar.config 文件:

<appSettings>
  <add key="foo" value="this setting isn't visible"/>
</appSettings>

我正在使用 ReSharper 10 测试运行程序来执行测试。 bar.config 文件复制到 bin/Debug 目录。事实上,该配置不久前还可以工作,但后来停止了。有什么线索可能是错误的吗?

现在,我已经找到了解决方法,但我对此解决方案并不满意:

private static void InitializeAppSettings()
{
    var exeAssembly = System.Reflection.Assembly.GetExecutingAssembly();
    var assemblyName = exeAssembly.GetName().Name + ".dll";
    var testDllFolder = new Uri(System.IO.Path.GetDirectoryName(exeAssembly.CodeBase)).LocalPath;
    var openExeConfiguration = ConfigurationManager.OpenExeConfiguration(Path.Combine(testDllFolder, assemblyName));
    foreach (var setting in openExeConfiguration.AppSettings.Settings.AllKeys)
    {
        ConfigurationManager.AppSettings[setting] = openExeConfiguration.AppSettings.Settings[setting].Value;
    }
}
顺便说一句。我无法从现有的遗留代码中抽象出 ConfigurationManager 的使用。

最佳答案

我复制了您的用例,发现我的附加配置在 ASP.NET 站点的上下文中有效,但在测试项目中附加的 appSetting 为空,直到我更改了复制到输出目录属性到始终复制

enter image description here

关于c# - ConfigurationManager 在测试中看不到 NUnit appSettings 文件属性(链接的配置文件),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35155481/

相关文章:

c# - 如何测试返回 Ok(object) 的 ASP.NET Core 2.2 Web API GET IActionResult?

c# - CoCreateInstance 失败,返回 0x80131500

c# - 清理字符串: Replace consecutive nonalphanum Character with single seperator

c# - 在 C# 中对一个段落进行正则表达式

c# - 异常堆栈跟踪中不包含行号(使用 Roslyn 动态编译的代码)

android - 为什么基于 ActivityUnitTestCase 的单元测试需要(虚拟)设备?

java - Android 单元测试不会使用正确的应用程序类

c# - 在请求 URL 中使用命名参数进行路由

c# - OleDbAdapter 读取列数据

c# - 获取回发触发器