I’ve got some integration tests that need to know where their source code lives as they require loading sample files when they run. Hard coding the path into the tests is possible - and I did that for a time - but it’s also fragile and has odd error modes.

My catalyst for change was one time when I checked out a parallel copy of my source to try an experiment. I was getting some very odd results from my tests that were hard to diagnose until I realized it was picking up test files from the other copy that was checked out.

To avoid that (and related) issues, I’ve been using this little routine to find the source folder for any method:

public static DirectoryInfo FindSourceFolder()
{
    var trace = new StackTrace(fNeedFileInfo: true);
    var frame = trace.GetFrame(1);
    var filename = frame.GetFileName();
    var assemblyLocation = new FileInfo(filename);
    return assemblyLocation.Directory;
}

Once I’ve got the source folder, other goodness can be easily built. If memory serves, I found this trick by reading the source code for Approval Tests.

I was perturbed the other day when I tried to use this routine with a .NET Core project targeting .NET Standard 1.6.

The .GetFileName() call was returning null.

Fortunately, the fix was relatively straightforward, though it took me a while (far too long!) to find it:

Modify your .NET Core project to output full debug information instead of portable (the default).

Go to Project Properties | Build | Output | Advanced | Debugging Information and set the option to full.

Comments

blog comments powered by Disqus