简体   繁体   English

如何在单元测试中引用文件?

[英]How to Reference File in Unit Test?

I am making some unit tests and I have a JSON file with some data in it. 我正在进行一些单元测试,我有一个包含一些数据的JSON文件。 I am writing some unit tests that take that file and use that data as well. 我正在编写一些单元测试来获取该文件并使用该数据。

So this data would be used live and for unit tests. 因此,这些数据将用于实时和单元测试。

I don't want to maintain two copies if possible so I am wondering how can I reference this file? 如果可能的话我不想保留两份副本,所以我想知道如何引用这个文件?

I think that you are looking for the "Add as a Link" feature in the Visual Studio's Add -> Existing Item... dialog: 我认为您正在寻找Visual Studio的Add - > Existing Item...对话框中的“Add as a Link”功能: 在此输入图像描述

Then you need to set the "Copy to Output Directory" parameter for this file to any value from these: 然后,您需要将此文件的“复制到输出目录”参数设置为以下值中的任何值:

  • Copy always 始终复制
  • Copy if newer 复制如果更新

Ie 在此输入图像描述

More details you can find in this MSDN article . 您可以在此MSDN文章中找到更多详细信息。

I normally use: 我通常使用:

[TestMethod]
[DeploymentItem(@"MyProject.Tests\TestFiles\file.txt")]
public void MyTest()
{
    var myfile= "file.txt";

    Assert.IsTrue(
        File.Exists(myfile),
        "Deployment failed: {0} did not get deployed.",
        myfile
        );
}

Then specify the file in the TestSettings.Settings file in the Deployment section. 然后在“部署”部分的TestSettings.Settings文件中指定该文件。

This way, the unit test will work in Visual Studio and also from the command line. 这样,单元测试将在Visual Studio中运行,也可以在命令行中运行。

In Visual Studio right-click your project and choose 'Add->Existing Item'. 在Visual Studio中,右键单击项目,然后选择“添加 - >现有项”。 Notice the 'Add' button is a drop-down button. 请注意,“添加”按钮是一个下拉按钮。 One of the choices is 'Add As Link'. 其中一个选择是“添加为链接”。 This will add the file to your project without copying it. 这将把文件添加到您的项目而不复制它。 On the file properties you can choose 'Copy if newer' for 'Copy to Output Directory'. 在文件属性上,您可以为“复制到输出目录”选择“复制如果更新”。 You can then consume the file in your test without maintaining two copies. 然后,您可以在测试中使用该文件,而无需保留两个副本。

One option is to use a post-build step to copy the file to where it needs to be. 一种选择是使用构建后步骤将文件复制到需要的位置。

Also check out this article on how to deploy test files: https://msdn.microsoft.com/en-us/library/ms182475.aspx 另请查看有关如何部署测试文件的文章: https//msdn.microsoft.com/en-us/library/ms182475.aspx

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM