ConfigurationManager在测试

时间:2016-02-02 13:59:43

标签: 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用法。

2 个答案:

答案 0 :(得分:2)

我复制了您的用例,发现我的附加配置在ASP.NET站点的上下文中工作,但是在我将Copy to Output Directory属性更改为Copy Always之前,测试项目中的其他appSetting为null

enter image description here

答案 1 :(得分:1)

如果您使用R#10.0.0或R#10.0.1 - 它是a known issue for such builds并且已在R#10.0.2版本中修复。

相关问题