2010-07-02 187 views
3

我們使用nunit.exe應用程序中使用ConnectionString,以運行我們的(集成)測試在NUnit測試

現在我遇到ConnectionString中未從app.config中從DLL拿起問題,其中的測試代碼是在。

這聽起來很合邏輯,因爲nunit.exe是開始的應用程序,而不是測試DLL(它曾經工作,當我從Visual Studio的測試框架開始測試的方式),但我應該把nunit.exe.config中的連接字符串?

我試圖在testcode(設置它們的工作原理爲的AppSettings:ConfigurationManager.AppSettings.Set("DownloadDirectory", mDir);)這樣的: ConfigurationManager.ConnectionStrings.Add(conset);(其中consetConnectionStringSettings對象),但後來我得到錯誤的connectionStrings節是隻讀的

什麼。我應該如何在我的測試中使用連接字符串?

編輯: 我們使用實體框架,所以我們不能將連接字符串放在appsettings中,因爲它直接從節中讀取,我找不到方法解決此問題。

回答

6

使用反射,你可以(在內存中)改變Configuration.ConnectionStrings [connectionName]的值,在你的情況下你可能會在SetUp或者TestFixtureSetUp中。見http://david.gardiner.net.au/2008/09/programmatically-setting.html

// Back up the existing connection string 
ConnectionStringSettings connStringSettings = ConfigurationManager.ConnectionStrings[connectionName]; 
string oldConnectionString = connStringSettings.ConnectionString; 

// Override the IsReadOnly method on the ConnectionStringsSection. 
// This is something of a hack, but will work as long as Microsoft doesn't change the 
// internals of the ConfigurationElement class. 
FieldInfo fi = typeof(ConfigurationElement).GetField("_bReadOnly", BindingFlags.Instance | BindingFlags.NonPublic); 
fi.SetValue(connStringSettings, false); 

// Set the new connection string value 
connStringSettings.ConnectionString = connectionStringNeededForNUnitTest; 
+0

如果這是從DLL運行的,那麼將不存在現有的連接字符串。在這種情況下,你需要添加一個新的連接字符串。 – Nathan 2011-06-14 13:58:30

1

您可以從ConfigurationManager.AppSettings讀取連接字符串值,它是隻讀的。你可以在App.Config中改變它。 如果您想要更改連接字符串中的某些值,例如,您可以通過代碼更改您的dataContext.URL或編碼所需的任何屬性。

+0

我們使用實體框架,因此我們無法將連接字符串置於appsettings中,因爲它從節中讀取。 – Michel 2010-07-02 08:51:17

0

我認爲單元測試可能很容易。您可以直接將連接字符串作爲硬編碼字符串放入測試類中。在簡單的單元測試中,你測試有限的邏輯範圍並且不關心輸入參數的真實性

+0

我們使用實體框架,所以我們不能將連接字符串放在appsettings中,因爲它從節中讀取 – Michel 2010-07-02 08:51:46

2

我知道這是不是你正在尋找的答案,但它是一個我用於解決您的同一個問題:

您可以修改,在EF5和EF4.3至少,你執行的DbContext並添加接受硬編碼的連接字符串的構造函數,像這樣:

public partial class MyContext : DbContext 
    { 
     public MyContext() : base("name=MyContext") 
     { 
     } 
     // --- Here is the new thing: 
     public MyContext(string entityConnectionString) : base(entityConnectionString) 
     { 
     } 
     // --- New thing ends here 

     // .... the rest of the dbcontext implementation follows below 
    } 

你將不得不粘貼每次重新生成語境時間這個東西,但恕我直言這是值得冒這個險。連接字符串必須使用元數據和所有內容格式化爲實體框架,但您可以將其弄清楚。只要將它保存在某個地方,以便在需要時粘貼它。