2016-01-22 100 views
0

与位于项目内的以下web.conig文件(在这种情况下,一个单元测试项目):ConfigurationManager.AppSettings无法找到设置

... 
<appSettings> 
    ... 
    <add key ="SmtpPort" value="00"/> 
    <add key="SmtpHost" value="site.site.com"/> 
    <add key=""/> 
</appSettings> 
... 

下面的单元测试失败:

[TestMethod] 
public void VerifyAppSettingsAreRead() 
{ 
    string port = System.Web.Configuration.WebConfigurationManager.AppSettings["SmtpPort"]; 
    string host = System.Web.Configuration.WebConfigurationManager.AppSettings["SmtpHost"]; 

    Assert.IsTrue(!String.IsNullOrEmpty(port) && !String.IsNullOrEmpty(host)); 
} 

此外,System.Web.Configuration.WebConfigurationManager.AppSettings.AllKeys正好有一个密钥列出,它根本没有在web.config文件中找到。实际上,搜索整个解决方案的关键点什么都没有。

如何更正WebConfigurationManager不返回正确密钥的行为?

+0

如果它的测试项目中,它可能不应该叫web.config中。将它重命名为app.config。 –

+0

我试图找出一个ASP.net项目的问题,因为从web.config中读取的问题完全相同,所以理想情况下我尽可能地重现它。 –

回答

0

我看你引用app.config和web.config。

如果你正在尝试使用web.config设置你或许应该使用

WebConfigurationManager

,如:

[TestMethod] 
public void VerifyAppSettingsAreRead() 
{ 
    string port = System.Web.Configuration.WebConfigurationManager.AppSettings["SmtpPort"]; 
    string host = System.Web.Configuration.WebConfigurationManager.AppSettings["SmtpHost"]; 

    Assert.IsTrue(!String.IsNullOrEmpty(port) && !String.IsNullOrEmpty(host)); 
} 
+0

我按照你的建议对它进行了测试(并且编辑了我的原始文章进行调整,因为我认为这是必需的),但是端口和主机仍然评估为空。 –

+0

您的web.config是否在单元测试项目之外? – Santiago

相关问题