Loading test data files in Microsoft Test Projects without fixed paths

I sorted a problem today that has been going on a while, how to load test data in unit tests without resorting to fixed paths.

We had an class library assembly and an associated test project in Visual Studio 2005 Team Developer Edition. The problem was the methods we needed to test (via a unit test) had to load some data from a file at run time.

In the 'real' application the file was loaded using the code

     string filename = Application.StartupPath + \datafile.dat";     

This all worked fine, as the data file was included in the project and set to be 'contents' so copied with the assembly to the build directory. (It was not put in a resource bundle as the user many need to edit the file with other tools)

So I wrote my unit test for one of these methods, ran it and it failed (OK I know I should have written the test first to true TDD). The reason the test failed was because the Application.StartupPath was that of the running application's path, not the assembly under test i.e. Visual Studio in. C:Program FilesMicrosoft Visual Studio 8Common7IDE.

To fix this problem took two steps. The first was to alter the logic to load the data file to use the path of the assembly containing the function under test (not the path of the application that is calling the assembly)

    string filepath = System.Reflection.Assembly.GetExecutingAssembly().Location;
    filepath = filepath.Substring(0,filepath.LastIndexOf("\"));

First I tested my 'real' application and it still worked, so I  re- ran the test and it still failed. This for a while had me consfused until I realised that the way the tester instide Visual Studio works is that it copies the files to a special test directory, each test run will create a new directory.

I realised that the tester copies all the assemblies in the project - BUT NOT ANY OTHER CONTENTS FILES. The fix was to edit the test configuration file (found on the test menu, the the edit test run configuration file). On the deployment tab add the test data files. Once this is done the files will be copied with the assemblies and the test started to work.

Now to look to get the running of unit tests to be part of the build process.