Visual Studio Unit Tests – DeploymentItem

I’ve run into this before, and I ran into it again this week, so now I’m writing it down so that *we all* won’t forget about it next time.  :)

I have an XML data provider class library that relies on the presence of an XML file to parse at runtime.  I am writing tests for that data provider using Visual Studio test framework.

The issue is that the tests are run in the funny “TestResults” sub directories, by default named based on the date/time of the test run.  When the test runs from this foreign directory, the test and data provider assemblies are copied there, but not the XML data file.

The Visual Studio test framework provides an attribute called DeploymentItem that you can use for just this issue.  It allows you to mark a test with the attribute to describe that you need other items besides the assemblies for the test to run.  In the example below, I’m specifying that from the unit test directory, go up and over (relative pathing) to the data provider directory and find the Data.xml file.

[TestMethod]
[DeploymentItem( @"..\UnitTestDeploymentItems\Data.xml" )]
public void TestMethod1()
{    
    var c = new SomeClass();    
    Assert.IsTrue( c.CanYouSeeTheFile() );
}

 

What they DON’T tell you, or at least I can’t find documented, are the other 2 things you have to do to get this to work.

#1 – the required file must be marked as Content & Copy (if newer/always).  This is usually the case already, since I almost always need that file with the data provider assembly up to the consuming app directory. 

#2 (and not obvious at all) – you must go into the .testsettings properties for the unit test and select “Enable Deployment”.   Double click the .testsettings project (in the Solution Items folder) and select the Deployment item in the left side list. 

VsTestsEnableDeployment_093679B9

There you have it – the test should now succeed, since the dependent file(s) are there are test runtime.

One thought on “Visual Studio Unit Tests – DeploymentItem

Leave a Reply

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>