To access a file from another project in a Microsoft Visual Studio unit test, without specifying the absolute path, you can use DeploymentItems.

 

DeploymentItems

DeploymentItems are files that will be copied to the output folder of the test. Microsoft Visual Studio tests are not run in the bin directory, but for each test a new directory is created, like: C:\Temp\Rli.Common\TestResults\rlisdonk_L084 2012-03-13 09_30_34\Out. DeploymentItems will be copied to this directory.

 

Enable DeploymentItems

Double click on the Solution Item > Local.testsettings in the Solution Explorer > Click on Deployment > check the "Enable deployment" checkbox > Apply > Close.

image

 

Add DeploymentItems

Now you can add DeploymentItems to your TestClass or TestMethod:

using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace Rli.TestProject
{
    [TestClass]
    [DeploymentItem(@"Rli.Common\Settings.xml")]
    public class UnitTest1
    {
        [TestMethod]
        public void TestMethod1()
        {
            Assert.IsTrue(System.IO.File.Exists("Settings.xml"));
        }
    }
}

The file [Settings.xml] in the Rli.Common project, can now be accessed in the unit test "UnitTest1.TestMethod1" in the Microsoft Visual Studio test project "Rli.TestProject".

 

image

 

 

Notes

  • The relative path used in [DeploymentItem(@"Rli.Common\Settings.xml")]  is relative to the Solution Folder!
  • If you want the file to be copied for all tests, you can add the file to the deployment files in the Local.testsettings. If you add the file to the deployment files, you don’t have to specify the DeploymetItem attribute on your TestClass or TestMethod, because the files will automatically be deploy to the test output folder:
  • image
  • If you only want to use a content file from another project, the test project does not have to reference the other project.
  • Adding files as linked content files (Project > Add Existing Item… > browse to the file, select it and click on Add As Link) and setting the file property "Copy to Output Directory" property to "Copy Always" will not work in this case. You will need to use DeploymentItems.
  • If you are using TFS with build templates, make sure the setting "TestSettings File" is set to a testsettings file that has Deployment files set to enabled. As testsettings file you can use, the Local.testsettings edited above.

image

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.