Kai Hartmann
Kai Hartmann

Reputation: 3154

Get path of referenced project during unit testing

I'm trying to test the functionality of a class in my (ASP.Net) web application, using unit tests. This class loads some files from the hard drive (to perform xsl transformations):

Xsl = GetXSLFromFile(AppDomain.CurrentDomain.BaseDirectory + "\XML Transformationen\Transformation_01.xslt")

This path is correctly resolved during debugging of the web application itself. But whenever I start the unit test (which resides in a separate testing project, referencing the project of the web application), I get the path of the testing project instead.

Is it possible to get the path of the web application in this scenario, or do I have to use a different approach? Any hints are appreciated.

Upvotes: 6

Views: 6304

Answers (3)

Kai Hartmann
Kai Hartmann

Reputation: 3154

Ok, this gave the hint: Can a unit test project load the target application's app.config file?

In the .testsettings file, added by the testing project to my webapplication project, I can add files and folders which should be copied to the testing projects debug folder each time the test is executed.

So after this I can reference the xsl-files per AppDomain.CurrentDomain.BaseDirectory.

Additionally, to keep also the folder structure, I had to do what has been described here: Visual Studio Test Project - Does not copy folder on deployment

I had to edit the .testsettings file with a text editor, and add the outputDirectory parameter. After that I restarted Visual Studio, and when started the testing project the folder and files have been copied correctly.

Upvotes: 0

Jordy Langen
Jordy Langen

Reputation: 3591

I suggest you do something like this:

public class MyXslFileLoader
{
    public void Load()
    {
        Load(AppDomain.CurrentDomain.BaseDirectory + "\XML Transformationen\Transformation_01.xslt");
    }

    public void Load(string path)
    {
        Xsl = GetXSLFromFile(path);
    }
}

You would call Load() in your web application, but use the overloaded version of this method in your unittest application. You could consider adding the xslt file as a resource to your project.

You would be able to load the path like this:

var webApplicationDllPath = Path.GetDirectoryName(typeof(ClassInTheWebApplicationDll).Assembly.GetName().CodeBase);

Upvotes: 5

Paritosh
Paritosh

Reputation: 11568

string path;
path = System.IO.Path.GetDirectoryName( 
  System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase );

HOW TO: Determine the Executing Application's Path

Getting the path of a executable file in C#

Hope this is helpful.. :)

Upvotes: 2

Related Questions