我有一个包含 3 个项目的解决方案,其中包括我的 DAL、一个程序集和我的单元测试项目。我正在使用 ReSharper。
在我的 DAL 中,以下字段为对象 SectionHandler 返回 NULL:
public static DatabaseFactorySectionHandler SectionHandler =
(DatabaseFactorySectionHandler) ConfigurationManager.GetSection("DatabaseFactoryConfiguration");
这是来自工厂类的一行。另一个继承自它的类尝试从其构造函数初始化该字段。
我记得我需要将我的 App.config 文件添加到我的单元测试项目(它指向 Machine.config)。但是,它并没有解决问题。尝试运行测试时我得到的是:
> failed: Configuration system failed to initialize System.Configuration.ConfigurationErrorsException: Configuration > system failed to initialize ---> > System.Configuration.ConfigurationErrorsException: Unrecognized > configuration section section. > (C:\projects\MyAssembly.Tests\bin\Debug\MyAssembly.Tests.dll.temp.config > line 3)
我不明白的是配置文件的命名。在我的目录中,我可以看到 App.config 已正确重命名 (MyAssembly.Tests.dll.config),但没有 temp.config 的迹象。
这是我的 app.config(这是我的测试项目中当前的内容,解决方案中没有其他 App.config)
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="DatabaseFactoryConfiguration" type="MyClass.DatabaseFactorySectionHandler, MyClass.DBConnector, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" />
</configSections>
<connectionStrings>
<clear/>
<add name="Connector1" providerName="MyProvider" connectionString="myConnString" />
<add name="DB2Connector" providerName="IBM.Data.DB2" connectionString="myConnString2" />
</connectionStrings>
<DatabaseFactoryConfiguration Name="MyClassHere" ConnectionStringName="Connector1" />
<DatabaseFactoryConfiguration Name="MyOtherClassHere" ConnectionStringName="DB2Connector" />
</configuration>
为什么我不能让单元测试项目识别我的配置文件?谢谢。
最佳答案
原来这个问题与 app.config 文件中的多个 DatabaseFactory 配置元素有关。
关于c# - 使用 App.Config 对 C# 程序集进行单元测试返回异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8841682/