VS Tricks: How to load test files from within a Unit Test

It is a little-known secret that I moonlight as a computer-Go programmer.  (What is the game of 'Go' you ask?)  Anyways, I am writing my Go-bot using Visual Studio Team System to take advantage of all the great Unit Testing tools it offers. 

What I would like to share here is a trick that I use to load test files from within a Unit Test without having to resport to hard-coded file paths.  By adding the test file as an embedded resource you can extract it from within the test assembly so you don't have to worry about where it is located on disk.

To accomplish this, do the following:

I. Add the file to the solution

The first step is to add the file to your solution.

II. Set the Build Action to "Embedded Resource"

Right click on the file and set the file's build action to Embedded Resource.  This will tell the .Net compiler to burn that badboy right into your assembly.

III. Load the resource and enjoy!

Try the following code snippet to extract the embedded resource:

using

System;
using System.Reflection;
using System.IO;

namespace UnitTestsLibrary
{
/// <summary>
/// Extracts embedded resources from the host DLL.
/// </summary>
public abstract class EmbeddedResourceExtractor
{

public static string ExtractEmbeddedString(string resourceName)
   {
Assembly asm = this.GetType().Assembly;
using( Stream stream = asm.GetManifestResourceStream(resourceName) )
      {

         if (stream == null)
throw new Exception("Unable to get manifest resource stream!");
        
try
         {
using( StreamReader reader = new StreamReader(stream) )
            {
return reader.ReadToEnd();
            }
         }
catch(Exception e)
{
throw new Exception("Error obtaining resource [" + resourceName + "]);
         }
      }
}
}
}

You can simply call that method from within a unit test to get the embedded resource for testing.  I use that to load SGF files to test my parsing utilities.

[Edit 5/25/06]
John Atwood pointed out something I failed to mention - that in order to load the resource you need to the fully-qualified name, which includes the namespace.  Thanks John!

Disclaimer
As with all code snippets on my blog, it doesn’t offer any warranty.  If it those 30 lines of C# manage to do something really, really bad please don't blame me or Microsoft.