Configuration Manager NameValueCollections从单元测试中返回空或空集合

问题描述 投票:0回答:1

我在Visual Studio中有两个项目,核心项目是Windows Service可执行文件,而单元测试项目。

核心项目有两个原始文件,像这样分解

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设置为“从不复制”

c# unit-testing windows-services app-config
1个回答
0
投票

测试将使用其自己的配置,因此您需要对其进行镜像。有一些解决方法:Can a unit test project load the target application's app.config file?

© www.soinside.com 2019 - 2024. All rights reserved.