[英]How to get build directory of a test project?
我有一個測試項目,我需要加載一個XLSX文件。 為此,我添加了一個帶有copy-always的文件,以便它最終出現在build目錄中,但以下所有內容都返回了錯誤的路徑:
System.Reflection.Assembly.GetAssembly(typeof(testclass)).Location;
AppDomain.CurrentDomain.BaseDirectory
Directory.GetCurrentDirectory();
他們都給了我:
"C:\\\\Users\\\\username\\\\Documents\\\\visual-studio-projecten\\\\projectname\\\\TestResults\\\\username_ICT003 2012-06-20 12_07_06\\\\Out"
我需要
"C:\\\\Users\\\\username\\\\Documents\\\\visual-studio-projecten\\\\projectname\\\\TestProject\\\\bin\\\\Debug\\\\SupportFiles\\\\"
我該如何做到這一點?
使用DeploymentItemAttribute屬性。 引用MSDN:
此屬性標識包含要部署的測試運行的文件的文件和目錄。 測試引擎制作部署項的副本,並根據指定的OutputDirectory或缺省目錄將它們放在測試部署目錄中。
例如:
[TestClass]
public class MyUnitTest
{
[TestMethod()]
[DeploymentItem("myfile.txt")]
public void MyTestMethod()
{
string file = "myfile.txt";
Assert.IsTrue(File.Exists(file), "deployment failed: " + file +
" did not get deployed");
}
}
當然假設您使用MSTest作為測試框架。
嘗試這個:
string dir = Path.Combine(
Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location),
"SupportFiles");
不要使用Directory.GetCurrentDirectory()
因為當前目錄不能是您的exe目錄,並且可能在程序執行期間更改。
如果你有像我一樣的人,如果你正在使用.testsettings文件並且類中的DeploymentItem屬性 不起作用,即使你已經將文件設置為內容並且總是復制,那是因為你已經有了.testsettings文件中的部署部分,或者您需要在.testsettings文件中使用DeploymentItem。 以下是我們現在的看法:
<Deployment>
<DeploymentItem filename="Tests\Unit Tests\ConnectionStrings.config" />
<DeploymentItem filename="Tests\Unit Tests\<project dir>\bin\Debug\TestFiles\" outputDirectory="TestFiles" />
</Deployment>
一個人做一個文件,另一個做一個目錄中的13個文件。 注意目錄的“文件名”的尾部斜杠!
解決方案和更多信息發現於:
切換到xUnit或NUnit 。
然后選項2.,3和Environment.CurrentDirectory
可以根據需要工作,返回build-output-diretory。 刪除“bin \\ Debug”或“bin \\ Release”,文件可以保留為“不要復制”。
另請參閱ElasticSearch中的GetFileFromMethod -method和用法 ,以獲得每次測試一個文件的好方法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.