简体   繁体   中英

How to Reference File in Unit Test?

I am making some unit tests and I have a JSON file with some data in it. 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: 在此输入图像描述

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 .

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.

This way, the unit test will work in Visual Studio and also from the command line.

In Visual Studio right-click your project and choose 'Add->Existing Item'. 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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