C# Configuration Manager NameValueCollections从单元测试返回null或空集合

C# Configuration Manager NameValueCollections从单元测试返回null或空集合,c#,unit-testing,windows-services,app-config,C#,Unit Testing,Windows Services,App Config,我在VisualStudio中有两个项目,一个是Windows服务可执行文件的核心项目,另一个是单元测试项目 核心项目有两个像这样的原始文件 File1.cs: using static Proj.ConfigHelper; namespace Proj { class MyClass { (lots of code) } } File2.cs看起来像这样 namespace Proj { static class ConfigHelper { publ

我在VisualStudio中有两个项目,一个是Windows服务可执行文件的核心项目,另一个是单元测试项目

核心项目有两个像这样的原始文件

File1.cs:

using static Proj.ConfigHelper;

namespace Proj
{
  class MyClass
  {
     (lots of code)
  }
}
File2.cs看起来像这样

namespace Proj
{
  static class ConfigHelper
  {
    public static NameValueCollection AppSettings { get { return ConfigurationManager.AppSettings; } }
    public static NameValueCollection CustomSection { get { return ConfigurationManager.GetSection("CustomSection") as NameValueCollection; } }
  }
}
这两个类都是内部的,并通过InternalsVisibleToAttribute使单元测试项目可见

在UnitTest项目内部,该项目是同一解决方案中的一个离散项目(因此它有自己的app.config),调用ConfigHelper.AppSettings将导致0项集合,而调用ConfigHelper.CustomSection将导致null。如果我尝试在File1.cs中对依赖于这些设置的方法进行单元测试,它们将作为默认值运行,就好像根本没有配置一样。我不太明白为什么会这样。谁能帮我理解我做错了什么?ConfigHelper似乎没有为自己的项目加载App.Config


Windows服务项目的app.config设置为“始终复制”,单元测试项目的app.config设置为“从不复制”

测试将使用自己的配置,因此您需要镜像它。有一些解决方案:

您的描述不清楚,这些设置是否也在测试项目的配置中?测试将不会从另一个项目的配置中读取