MSTest Headaches. I just need a file!

Last week I was very frustrated trying to get a file to be copied into the running test directory automatically. The test needs to be able to read data from a sample file and then test the logic of the class that would normally parse that file. After a lot of searching, I ended up finding one way to ensure that the file is copied. That is the DeployementItem attribute.

At first glance, I thought it would be easy enough.  Add the attribute to the test method or class, and I’m good to go.  Unfortunately though, it was not quite that easy and what I found is that you also have to change the Copy to Output Directory property of the file in Visual Studio to be Copy always.  After this is done, perform a clean on the test project.  This will insure the file is copied to the bin directory when the test project is compiled.  And then since we have our DeploymentItem attribute set, that will force the file to be copied to the running directory of the test.

using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Xml;

namespace TestProject1
{
    [TestClass]
    [DeploymentItem("CustomerData.xml")]
    public class UnitTest1
    {
        [TestMethod]
        public void VerifyJohnDoe_Exists()
        {
            XmlDocument xDoc = new XmlDocument();
            xDoc.Load("CustomerData.xml");

            XmlNode johnDoe = xDoc.SelectSingleNode("//Customers/Customer[@name='John Doe']");
            Assert.IsNotNull(johnDoe, "Unable to find the John Doe customer in the data file.");
        }

        [TestMethod]
        public void VerifyDennisDoe_DoesNotExist()
        {
            XmlDocument xDoc = new XmlDocument();
            xDoc.Load("CustomerData.xml");

            XmlNode dennisDoe = xDoc.SelectSingleNode("//Customers/Customer[@name='Dennis Doe']");
            Assert.IsNull(dennisDoe, "Expected result to be null, Dennis Doe does not exist.");
        }
    }
}
<?xml version="1.0"?>
<Customers>
 <Customer name="John Doe" ID="1" />
 <Customer name="Jane Doe" ID="2" />
</Customers>