我对为什么我的一个单元测试失败感到非常震惊。这是一个简单的测试,用于查看是否返回了正确的连接字符串。我的 App.config 看起来像这样:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<system.web>
<compilation defaultLanguage="c#" debug="true" />
</system.web>
<connectionStrings>
<add name="DbConnectionString" connectionString="Test_HighOnCoding_Db" />
</connectionStrings>
</configuration>
这是我的简单单元测试,它总是抛出 null 异常:
[TestFixture]
public class when_retrieving_database_name_from_config
{
[Test]
public void should_get_the_correct_database_name()
{
var dbName = ConfigurationManager.ConnectionStrings["DbConnectionString"].ConnectionString;
// dbName is always null
Assert.AreEqual("Test_HighOnCoding_Db",dbName);
}
}
最佳答案
根据您在下方的评论,我的原始答案不适用。
然后我建议检查一件事;您的 app.config
文件是否与您的程序一起移动到目录中,并重命名为与程序相同的名称,并添加了 .config?
所以,program.exe
将 program.exe.config
作为配置文件?`
看起来您这里有一个 Web 应用程序;如果是这样,您的配置文件应该是 web.config
而不是 app.config
。然后,您应该使用 System.Web.Configuration
命名空间中的 WebConfigurationManager
。
关于c# - ConfigurationManager ConnectionString 抛出错误并返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4306050/