Stewart Ritchie
Stewart Ritchie

Reputation: 926

Determine Solution Path During Test Execution

How would I determine the solution path from within my test code?

I'm trying to write tests for a plugin architecture. I have some fake classes that implement my plugin interface in a separate project within my solution. After these build, the dll is copied into a 'plugins' folder using a post-build event:

copy "$(TargetPath)" "$(SolutionDir)TestPlugins"

My test code looks for plugins in that location and loads plugin types into a collection for later use.

At the moment, I'm having to hard-code the 'plugins' folder path in my test, which is nasty.

Oh, and I'm using Visual Studio's built-in test projects (rather than NUnit), in case that makes a difference.

Upvotes: 4

Views: 2274

Answers (4)

Daniel Anderson
Daniel Anderson

Reputation: 275

To add to the answer by "Stewart Ritchie" (which works nicely, by the way!), the number of ".Parent" arguments depends on how far back you want to recurse up the tree to the executing assembly. So if you continue to get IOExceptions saying the directory can't be found, the thing to do is check the value of the solutionPath returned to determine whether you need to add or remove some of the recursion levels to arrive at the path you're looking for.

-- Happy coding!

Upvotes: 0

Andreas
Andreas

Reputation: 1200

One possible solution would be to create a post-build event to the test-project write a config. I.e. along the lines of:

echo $(SolutionDir)TestPlugins > $(TargetDir)PluginConfig.cfg

And read the config file from your tests.

Upvotes: 1

Stewart Ritchie
Stewart Ritchie

Reputation: 926

The relative path works, but we need to track up from the excuting binary, which is buried away in a test project.

string solutionPath = Directory
    .GetParent(Assembly.GetExecutingAssembly().Location)
    .Parent.Parent.Parent.FullName;

string pluginPath = Path.Combine(solutionPath, "TestPlugins");

Needs the following

using System.IO;
using System.Reflection;

Not the most elegant solution, but it works.

Upvotes: 2

Christopher B. Adkins
Christopher B. Adkins

Reputation: 3577

if you know the location of the plugins in relation to the actual solution you could do a relative path. This would still be hard coded, but a small sliver better than a 100% hard coded path. Another option would be to have settings file that states the path to the plugins regardless of system, so you can simply read that setting out of the file and work with it that way. Let me know if neither one of these work for you and I can let you know what elese I can come up with.

Upvotes: 0

Related Questions