你如何指示 NUnit 從特定目錄載入程序集的 dll.config 文件?
如果程序集包含 app.config 文件,
ConfigurationManager只要它與通過 NUnit-Gui 執行的 NUnit 項目位於同一目錄中,就會載入它。為了說明,請考慮以下文件夾結構。+ TestFolder testProject.nunit + AssemblyAFolder assemblyA.dll assemblyA.dll.config + AssemblyBFolder assemblyB.dll assemblyB.dll.config
AssemblyA和呼叫.AssemblyB_ConfigurationManager如果我在 NUnit-Gui 中獨立執行這些測試程序集,ConfigurationManager將正確解析本地配置文件。但是,如果我載入
testProject.nunit到 NUnit-Gui(其中包含對AssemblyA和的引用AssemblyB),無論目前正在執行哪個程序集,都會在其中ConfigurationManager查找配置文件。TestFolder有沒有辦法指示 NUnit 將應用程序配置重新載入到目前程序集目錄中的配置?
以下是 的內容
testProject.nunit:<NUnitProject> <Settings activeconfig="Debug" /> <Config name="Debug" binpathtype="Auto"> <assembly path="AssemblyAFolder\assemblyA.dll" /> <assembly path="AssemblyBFolder\assemblyB.dll" /> </Config> </NUnitProject>
Nunit 無法在我們的項目中找到 App.config 文件的路徑。所以我們需要手動告訴 Nunit App.config 文件在我們項目中的位置(顯然是在根文件夾中)。
就我而言,項目結構如下
+ProjectWEBApp//web pages +Modules +aspx pages +web.Config +projectBusinesslogic //business logic .cs files +Modules +.cs +ProjectTestName// a seperate Nunit test cases project +Modules +App.ConfigProjectWebApp 使用包含業務邏輯的 projectBusinesslogic 的引用。+ProjectTestName 使用 projectBusinesslogic 的引用對業務邏輯進行測試。問題從這裡開始,Nunit 測試項目需要自己的 app.config 文件。它不會像 projectBusinesslogic 那樣使用 web.config 文件,所以當你執行 Nunit 時它會提示錯誤
-Null 引用異常…….對象瞬間未設置為……
解決方案 - 當您執行 Nunit GUI 時
- Project->Edit 將打開一個新的彈出視窗
- 屬性 -> 正常 -> 配置文件名 -> 添加您的app.config文件名
- 文件->保存並關閉彈出視窗
- ON Nunit Gui-File-> 重新載入項目
這是解決您問題的簡單方法
MarkLawrence 給出的
configSource元素解決方案正是我一直在尋找的,並且效果很好。然而,實現此解決方案的挑戰是在從顯式 NUnit 項目(如我的情況)執行測試時以及在單獨執行程序集的單元測試時(無顯式項目)載入程序集配置。為此,需要對我的文件佈局進行以下修改。+ TestFolder testProject.nunit testProject.config + AssemblyAFolder assemblyA.dll assemblyA.dll.config assemblyA.dll.configfragment + AssemblyBFolder assemblyB.dll assemblyB.dll.config assemblyB.dll.configfragment創建這些
configfragment文件以包含曾經在相應config文件中的程序集配置。之後,config文件被修改為只包含一個configSource元素,該元素具有對應configfragment文件的相對路徑。請注意,這種方法唯一不起作用的情況是assemblyA.dll兩者assemblyB.dll都需要相同的配置部分,因為在創建testproject.config.在嘗試了這種方法後,我決定依靠在執行時生成程序集配置,並一起刪除靜態配置文件。這裡有一些程式碼展示瞭如何生成配置,並且無論如何載入被測程序集,都可以訪問它。
void WithConfigurationFile(Action method) { // Create the assembly configuration. string settingsSection = "myConfigSectionName"; Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); config.Sections.Add( settingsSection, new ConfigSectionType(/*config element values*/); config.Save(); try { // Invoke the method with the new configuration. ConfigurationManager.RefreshSection(settingsSection); method(); } finally { // Revert the assembly configuration. File.Delete(config.FilePath); ConfigurationManager.RefreshSection(settingsSection); } }通過使用不接受路徑的ConfigurationManager.OpenExeConfiguration()重載,我們從主機應用程序的工作目錄載入配置,該目錄會根據您執行 NUnit 測試的方式而變化。此外,try/finally 塊保證您的程序集配置不會干擾其他測試,這些測試可能需要也可能不需要此類配置。
最後,在單元測試中使用:
[Test] void VerifyFunctionality { WithConfigurationFile(delegate { // implement unit test and assertions here }); }我希望這對可能遇到類似問題的其他人有所幫助!