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
Next Post
High CPU Usage by Windows Update on Windows RT  04 Jun 2017
Prior Post
In defense of XML  25 Apr 2017
Related Posts
Browsers and WSL  31 Mar 2024
Factory methods and functions  05 Mar 2023
Using Constructors  27 Feb 2023
An Inconvenient API  18 Feb 2023
Method Archetypes  11 Sep 2022
A bash puzzle, solved  02 Jul 2022
A bash puzzle  25 Jun 2022
Improve your troubleshooting by aggregating errors  11 Jun 2022
Improve your troubleshooting by wrapping errors  28 May 2022
Keep your promises  14 May 2022
Archives
May 2017
2017