9

我有一个测试项目,我需要在其中加载一个 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\\"

我该如何做到这一点?

4

4 回答 4

9

使用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");
    }
}

Of course assuming you are using MSTest as your testing framework.

于 2012-06-20T10:22:46.147 回答
7

试试这个:

string dir = Path.Combine(
    Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location),
    "SupportFiles");

不要使用Directory.GetCurrentDirectory(),因为当前目录不能是您的 exe 目录,并且在程序执行期间可能会更改。

于 2012-06-20T10:18:55.477 回答
1

In case someone like me comes along, if you're using a .testsettings file and the DeploymentItem attribute on the class doesn't work even though you've set your files as Content and to Always Copy, it's because either you already have a Deployment section in your .testsettings file or you need to use DeploymentItem in the .testsettings file. Here's how ours looks now:

<Deployment>
    <DeploymentItem filename="Tests\Unit Tests\ConnectionStrings.config" />
    <DeploymentItem filename="Tests\Unit Tests\<project dir>\bin\Debug\TestFiles\" outputDirectory="TestFiles" />
</Deployment>

One does a file, the other does 13 files in a directory. Note the trailing slash for the directory's "filename"!

Solution and more info was found at:

MsTest DeploymentItem OutputDirectory in testsettings

于 2013-08-29T18:52:10.107 回答
1

Switch to xUnit or NUnit.

Then both option 2., 3. and Environment.CurrentDirectory works as needed, returning the build-output-diretory. Remove "bin\Debug" or "bin\Release" and files can be left at 'Do not copy'.

Also see the GetFileFromMethod-method and usage in ElasticSearch for a nice way to have one file per test.

于 2014-07-29T11:34:00.553 回答