Self-Contained Unit Tests

by Jacob 19. July 2007 14:44

Phil Haack's latest on creating a sane build process is interesting. I've been using a technique for some time now that bypasses this technique, however, and thought I'd share. Essentially, you get Visual Studio to copy files to your output directory on compile.

A recent project involves processing EDI documents, so it'd be nice if my unit tests include an actual EDI file or two to test against. To facilitate this, I've added a couple of EDI files to the project (and thus, to source control). Once added, I can set the "Build Action" property to "Content" and the "Copy to Output Directory" to "Copy Always".

Property

These settings ensure that the file will be copied to bin/Debug or bin/Release (or wherever the target of your compile is set).

If the file in question is a config file (as, say, for unit testing), you're pretty much done at this point.

In addition, I like to add a couple of static methods to my UnitTestHelper class that help me access these files.

internal static string executingPath = null;
internal static string GetLocalPath()
{
    if (string.IsNullOrEmpty(executingPath))
    {
      Uri uriPath = new Uri(Path.GetDirectoryName(
        Assembly.GetExecutingAssembly().CodeBase));
      executingPath = uriPath.LocalPath;
    }
    StringAssert.IsNonEmpty(executingPath);
    return executingPath;
}

internal static string GetTestFile(string file)
{
    string localFile = Path.Combine(
        GetLocalPath(), file);
    FileAssert.Exists(localFile);
    return localFile;
}

The extra asserts (FileAssert and StringAssert) are some marvelous features of MbUnit and you'll need to add System.IO for the "Path" class and System.Reflection for the "Assembly". Once this is done, you can access any file by its name:

UnitTestHelper.GetTestFile("EDI997.txt")
 

Tags: , , , , , , , ,

Programming

scruffylookingcatherder.com

Information

    Recent Posts

    Calendar

    <<  September 2010  >>
    MoTuWeThFrSaSu
    303112345
    6789101112
    13141516171819
    20212223242526
    27282930123
    45678910

    View posts in large calendar
    Disclaimer
    The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.

    © Copyright 2010 Scruffy-looking Cat Herder