Monday, 23 February 2009

Referencing a template file from a Visual Studio Unit Test

As part of the test suite for the Simple OOXML project, I need to reference a .docx file in a template folder in code - the problem being that every unit test is run in it's own output folder. The solution is to copy the template files to the output folder and retrieve the path from the test context:
1. Make sure the TestContext is set when the test is run by providing a TestContext property (this is now really simple in 3.5)
    [TestClass()]
    public class SpreadsheetTests
    {
        public TestContext TestContext { get; set; }
        ...
2. Make sure that the requested file is copied to the output folder by using the DeploymentItem attribute
    [TestMethod(), DeploymentItem("Templates\\template.xlsx")]
    public void WorksheetCopyTest()
    {   ...
3. Reference from code using the TestContext.TestDeploymentDir
MemoryStream stream = SpreadsheetReader.Copy(string.Format("{0}\\template.xlsx", TestContext.TestDeploymentDir));
Note that even though we copied the template.xlsx file from the Templates folder, it ended up in the root output folder.

No comments: