views:

578

answers:

2

Is there a way to find out the project path at compile time?

I want to create a unit test that tests if the configurartion in the default web.config (the one in the project folder). Mainly to reduce human error.

I cannot rely on assembly locations at runtime (for the test), so I need to know where the project folder is to access web.config there.

I need a "generic" solution since I'd like to use the same (base) test code for multiple projects, and the physical location is different anyway for most development machines.

Thanks.

+2  A: 

If you want the Visual Studio project path, at compile time, you could use a Pre-Build Event (see the Project Properties dialog) to run a command line that will create a source file used in your project.

The source file will contain some code, say a variable definition. Your testing code uses this variable. The value of the variable will come from VS; when it runs your Pre-Build Event command, it substitutes project properties for certain macros. The macro you want is probably ProjectDir.

So in the end, you have something like this for your Pre-Build Event's command:

echo 'const char * PROJECT_PATH = "$(ProjectDir)";' > source.cpp

Not sure what language you're using, so adjust accordingly.

rkb
Good plan, but it doesn't entirely do what I need, since the web config I want to test is in another project. Still, I can work from here.
Inferis
+4  A: 

Based on rkb's answer,

As it sounds like you've got a C# project, use this post build step.

echo namespace ProjectPath { static public class ProjectPath { public static readonly string Path = @"$(ProjectDir)";} } > $(ProjectDir)path.cs

Then include path.cs as an existing item to your test project. Then you can access it via:

string path = ProjectPath.ProjectPath.Path;
Simeon Pilgrim
While a more complete answer for my needs, rkb was first, so I'll give him credit.
Inferis
This is awesome for unit test projects. Well done.
BC