2013-07-10 40 views
13

我想爲我的項目編寫單元測試,但它不會讓我使用配置管理器。現在我的項目的設置類似於不能在單元測試項目中使用ConfigurationManager

ASP.Net應用程序(所有aspx頁面)

ProjectCore(所有的C#文件 - 模型)

ProjectTest(所有測試)

在我ProjectCore

,我能夠從System.Configuration訪問ConfigurationManager對象並將信息傳遞到項目中。然而,當我跑了一個測試,ConfigurationManager中涉及,我得到的錯誤

System.NullReferenceException: Object reference not set to an instance of an object. 

下面是測試的一個例子

using System.Configuration; 

[TestMethod] 
public void TestDatabaseExists() 
{ 
    //Error when I declare ConfigurationManager 
    Assert.IsNotNull(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString 
} 
我在其他測試中

,ConfigurationManager.ConnectionStrings [「的ConnectionString」 ] .ConnectionString是我將數據適配器的配置字符串設置爲,並在測試中返回空錯誤,但在實際使用網站時不會返回空錯誤。有任何想法嗎?

+0

你正在做單元測試和單元測試你的注意力應該是想測試特定的方法和應該刪除多餘的依賴。在這種情況下,嘗試嘲笑/摩爾(使用MS Mole/Pex)system.configuration類;那肯定會給出一個解決方案。 – Rahul

+0

@JohnSaunders所以在我的測試中,NullReferenceException是當我實際分配字符串到配置管理器。例如... String cs = ConfigurationManager.ConnectionStrings [「ConnectionString」]。ConnectionString – willykao

+0

@JohnSaunders除非如果ConfigurationManager僅在單元測試的情況下爲空(因爲我在實際的ASP中沒有得到這個錯誤。網絡應用程序),想知道我是否真的可以在測試中使用配置管理器 – willykao

回答

21

這可能是幾個問題之一:

  1. 您還沒有添加的app.config到您的ProjectTest項目。
  2. 您沒有在您的app.config中添加連接字符串。

+2

haha​​ha oops,我有一個web.config文件,而不是app.config。原因是我有ASP.net項目中的web.config,並且由於核心不需要它在那裏工作的配置文件,我以爲我可以使用相同的一個,但多數民衆贊成noob,感謝提醒 – willykao

+0

謝謝,也有同樣的問題。 –

+0

你是一個傳奇人物謝謝你! – Danrex

2

你正在做單元測試和單元測試你的注意力應該是想測試特定的方法和應該刪除多餘的依賴。在這種情況下,嘗試嘲笑/ mole((使用Microsoft Mole和Pex)system.configuration class;那肯定會給出一個解決方案。

我說的是,一旦你在你的測試項目解決方案中安裝了MS moles-and-pex->右鍵單擊系統程序集並選擇create mole。

這將給你一個配置類的mole'ed版本,反過來將有一個configuration class嘲笑版本 - 使用它,你可以繞過你面臨的問題。

0

它與mstest.exe命令行中的/ noisolation參數有關。 省略/ noisolation參數,它工作。

+0

這實在是一個評論,而不是一個答案。一旦你獲得了足夠的聲望,[你將能夠發表評論](// stackoverflow.com/privileges/comment)。 –

0

您還可以使用特殊配置的路徑與ExeConfigurationFileMap

// Get the machine.config file. 
ExeConfigurationFileMap fileMap = new ExeConfigurationFileMap(); 
// You may want to map to your own exe.config file here. 
fileMap.ExeConfigFilename = @"C:\test\ConfigurationManager.exe.config"; 
// You can add here LocalUserConfigFilename, MachineConfigFilename and RoamingUserConfigFilename, too 
System.Configuration.Configuration config = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None); 
相關問題