Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get path of referenced project during unit testing

Tags:

c#

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.

like image 905
Kai Hartmann Avatar asked Jun 26 '13 07:06

Kai Hartmann


People also ask

How do you add references to unit testing?

In your unit test project, add a reference to the code under test. To add a reference to a code project in the same solution: Select the test project in Solution Explorer. On the Project menu, select Add Reference.

What is the correct order of the unit test layout?

A typical unit test contains 3 phases: First, it initializes a small piece of an application it wants to test (also known as the system under test, or SUT), then it applies some stimulus to the system under test (usually by calling a method on it), and finally, it observes the resulting behavior.


2 Answers

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);
like image 168
Jordy Langen Avatar answered Oct 17 '22 03:10

Jordy Langen


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.. :)

like image 29
Paritosh Avatar answered Oct 17 '22 03:10

Paritosh