2016-01-22 62 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