Visual studio tests and external files


Writing unit tests should be an easy task. The hard task is writing the code. So it came as a suprise that using a file in a unit test is such a cryptic task. Why? Well just try to use it in a test written on the visual studio test framework. To be honest I have no clue how to call it! I guess that tells us a lot about it. I searched the net high and wide and foud that other people have the same problem and that “it” has many names like:

  • VSTS
  • TFS test

Blah blah blah. I am drigting off. Back to the topick.

So I wanted to write a unit test that will:

  1. Initialize all my little classes
  2. Read the contents of a XML
  3. Get a value out of it
  4. And check if the my classes have correctly interpreted the class

Simple right? Done it a million times, using nUnit. So I wrote my test as every “sane” developer (if something like this exists). And lord behold it did not work. All I got was a System.FileNotFoundException.

Long story shord and to not take the fun out of a good day of reverse enginering the framework. Well as it turn out the output directory of the test project is not used to run the tests. So you have to tell “it” that it has to deploy this additional file. How do you do this? With an attribute, what else!

And now finally the time for some code.

[TestMethod]
[DeploymentItem("Sources\\ProjectName\\default.xml")]
public void GetXmlResourceValue()
{
    MyLittleClass reader = new MyLIttleClass("dafault.xml");
    reader.Initialize();
    Assert.AreEqual("ExpectedValue", reader.GetValue("testKey"));
}

The important attribute is the DeploymentItem attribute which has to be added for each file we want to use. In my opinion this can get pretty ugly pretty fast. Because a unit test with 5 lines of test code attributed with 10 Deployment attributes can not be good for the code readability and maintainability.

But we will have to live with that.

Hope this will help someone.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s