chobo2
chobo2

Reputation: 85715

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?

Upvotes: 10

Views: 19853

Answers (4)

peval27
peval27

Reputation: 1309

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.

Upvotes: 6

Igor Kustov
Igor Kustov

Reputation: 3276

I think that you are looking for the "Add as a Link" feature in the Visual Studio's Add -> Existing Item... dialog: enter image description here

Then you need to set the "Copy to Output Directory" parameter for this file to any value from these:

  • Copy always
  • Copy if newer

I.e. enter image description here

More details you can find in this MSDN article.

Upvotes: 10

Kip Morgan
Kip Morgan

Reputation: 738

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.

Upvotes: 1

Dave
Dave

Reputation: 617

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

Upvotes: 0

Related Questions