我是 C# 和單元測驗的新手。我有一個組態檔存盤在 Source 檔案夾中(在服務器上)。我需要在我的單元測驗類中讀取該檔案。這將在構建服務器上運行,因此需要找到一種解決方法。類似 GetExecutingAssembly 的東西
uj5u.com熱心網友回復:
將檔案添加到同一個專案中,最好是在資料檔案夾或類似的地方。
右鍵單擊visual studio中的檔案并選擇屬性,將操作設定為嵌入資源
根據您希望加載的防御程度,執行類似的操作
using var stream = Assembly .GetAssembly(this.GetType()) .GetManifestResourceStream("<mynamspecase>.<myfilename>.<ext>"); Assert.NotNull(stream); var reader = new StreamReader(stream); string serialized = reader.ReadToEnd(); var dto = System.Text.Json.JsonSerializer.Deserialize<myfiletype>(serialized); Assert.NotNull(dto);
或者,如果不想將您的配置帶到未知的測驗服務器......但出于某種原因盲目地偏移您所在的位置,您可以使用您所在的位置作為導航點。
string[] pathParts =
Assembly.GetAssembly(this.GetType()).Location.Split(@"\");
//Go to party
// now your text assembly is in last position, you will not be looking for that
pathParts[pathParts.GetUpperBound(0)] = "";
string basePathWhereWeExecute = string.Join(@"\", pathParts);
var di = new DirectoryInfo(basePathWhereWeExecute);
//You can combine, just jump up and down the path and use the following
FileInfo[] whatFilesAreThere = di.GetFiles();
DirectoryInfo[] whatDirectoriesAreThere = di.GetDirectories();
// I'd suspect you can get more info that just anywhere with a name if it's legit with somebody wanting you to succeed :D
uj5u.com熱心網友回復:
您使用 NUnit、MSTest 或其他東西作為您的測驗框架嗎?您可以使用 NUnit 的TestContext.TestDirectory或 MSTest 的TestContext.TestRunDirectory獲取單元測驗 dll 的目錄。然后我將組態檔添加到測驗專案,并將其設定為復制到輸出目錄。如果配置在您的存盤庫樹中的其他位置,則可以將其作為鏈接檔案添加到您的測驗專案中。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/330739.html
