Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can relative paths in my C# class work with NUnit 3.x?

I have a C# class with the following code.

class Database
{
    private const string DatabaseFilepath = @"Settings\Database.xml";
    ...
    private void LoadDatabase()
    {
        XmlDocument databaseDocument = new XmlDocument();
        databaseDocument.Load(DatabaseFilepath);
    }
}

Now this code executes fine when I compile it, and it is able to read from the Database.xml file. However, when I run a unit test that happens to execute this code using NUnit, I get the following exception.

Result Message: System.IO.DirectoryNotFoundException : Could not find a part of the path 'C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE\Settings\Database.xml'.

Now, when I was using Visual Studio Test Tools, this worked perfectly fine. However, upon switching to NUnit, it looks like it is searching in a different working directory. How can I change this?

Note: I have found other questions that ask how to use relative paths in test code. In my example, my relative paths are are in my class code.

like image 367
ArKi Avatar asked Dec 14 '22 01:12

ArKi


1 Answers

Charlie gave a great explanation for why they decided not to change the current directory. For my code under test, I found using AppDomain.CurrentDomain.BaseDirectory and combining it with my relative path using Path.Combine(...) to work fine for NUnit 3.x.

like image 61
ArKi Avatar answered Dec 17 '22 01:12

ArKi