Test and Context

For a Unit Test the most important concept, and probably the most difficult to manage is the concept of Fixture. Quite often part of the Fixture is composed by an external File. In a little project that I use as example for jQuery I have a really simple class that parses an XML file to create a menu for Asp.Net MVC enabled site.

In such a situation the fixture of the test is using different source files to test the class with different input. In a classic NUNIT unit testing you can solve this problem including the file in the project with Copy if newer. With such a setting Visual Studio at each build check if the file is changed, and eventually copies the file into the appropriate directory (bin/debug/pathofthefile in standard debug configuration)

image

image

This approach is good, but has some problems, if you simply change the XML file, and rebuild the project, the file gets no copied in the output directory. This happens because Visual Studio correctly checks that no source file was changed, so it has no need to recompile. Another stuff I do not like is that I need to find the file with the pat**h I used to insert it into the test project.

1
2
3
4
5
6
7
8
[Test]
public void GrabMenuWithActionUrl()
{ 
 MasterLogic sut = new MasterLogic(new MyTestUrlHelper());
 List<MenuItem> menu = sut.CreateMenu("SampleFiles\\MenuType1.Xml").MenuItems;
 Assert.That(menu, Has.Count.EqualTo(2));
 Assert.That(menu[1].MenuItems[0], Has.Property("Url").EqualTo("/Photo/ManageAlbum"));
}

The same test can be written in msTest, but this time I have the DeploymentItem attribute, that can be used to specfy to mstest engine, that my test really need the file SampleFiles\MenuType1.xml.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
[TestMethod()]
[DeploymentItem(@".\SampleFiles\BaseMenu1.xml")]
public void CreateMenuTest()
{
    PrivateObject param0 = new PrivateObject(new MasterLogic(new MyTestUrlHelper()));
    MasterLogic_Accessor target = new MasterLogic_Accessor(param0);
    string menuFileName = @"BaseMenu1.xml";
    MenuItem expected = new MenuItem("TEST");
    target.CreateMenu(menuFileName);
    Assert.AreEqual(expected.Text, "TEST");
}

This is a cleaner way to express the fixture, thanks to the DeploymentItem attribute it is clear that the test needs the file SampleFiles\BaseMenu.xml, and most important, the file was copied automatically before each test runs and it is located in the same dir of the test assembly, so i can simply refer to it with the BaseMenu1.xml name without any path.

alk.