Warm tip: This article is reproduced from serverfault.com, please click

c#-如何获取测试项目的构建目录?

(c# - How to get build directory of a test project?)

发布于 2012-06-20 10:17:12

我有一个测试项目,我需要在其中加载一个 XLSX 文件。为此,我添加了一个始终复制的文件,以便它最终位于构建目录中,但以下所有内容都返回错误的路径:

  1. System.Reflection.Assembly.GetAssembly(typeof(testclass)).Location;
  2. AppDomain.CurrentDomain.BaseDirectory
  3. 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\\"

我该如何做到这一点?

Questioner
Halfgaar
Viewed
0
Christophe Geers 2012-06-20 18:22:46

使用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 作为你的测试框架。