Syntax Highlighting

Saturday 27 October 2012

MSTest and the DeploymentItem Attribute

I was writing Unit Tests today with MsTest and came across what I thought was a straightforward problem. My test needed to load an Xml document from the file system. Easy, right?


Wrong.

Here is the part of the code that was causing the problem - two lines that I've written in applications, a hundred times before without any issue.

XmlDocument testXmlDocument = new XmlDocument(); testXmlDocument.Load(@".\TestXml\SWHNewFormat.xml");

But when the test ran, it threw the following error

System.IO.DirectoryNotFoundException: Could not find a part of the path 'D:[Path to test project]\bin\Debug\TestXml\SWHNewFormat.xml'.

Turns out that when you run your tests they are deployed to a folder (the path of which is configurable). Any files you want to be deployed with the tests (for example xml files which your tests may need to read) have to be flagged up on the test method (or test class) with the DeploymentItem attribute.

Finding that out was the easy part. Actually getting the fire to deploy to the folder was another matter.

Google. Rinse. Repeat.


Firstly, in Visual Studio I had to set the "Copy to Output Folder" property to "Copy Always" on the files I wanted to deploy with your my tests. Once that was set I then needed to set the DeploymentItem attribute.

The attribute accepts two parameters. The first is the path to the folder that contains the file(s) you want to deploy and the second is optional and the name of the folder that will be created in the deployed folder.

But with both parameters set on the attribute, still my file did not appear in the deploy folder.

Gotcha!


The thing that caught me out was the path in the first parameter is relative to the bin\[CONFIGURATIONNAME] of the test project, so in my case the path I specified in the attribute was
  • @".\XmlMangerTests\TestXml"
This translated to the file path 
  • "D:[Path to test project]\bin\Debug\XmlMangerTests\TestXml"
The second parameter is the folder name within the test run folder for the copied files. Again in my case I set
  • "TestXml"
which translated to the folder path
  • D:\[Path to Solution]\TestResults\Deploy_CompName 2012-10-25 11_10_16\Out\TestXml
Once this was set (and if I'm honest after correcting the odd type of two!) the test ran as expected. Of course it failed, but that's a whole other post.