Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

nunit test working directory

Tags:

c#

nunit

I have the following code (sample1.evol - file attached to my unit test project):

[Test]
public void LexicalTest1()
{
     var codePath = Path.GetFullPath(@"\EvolutionSamples\sample1.evol");
     //.....
}

I found that the working directory of test execution is not the assembly directory: (in my case codepath variable assigned to d:\EvolutionSamples\sample1.evol).

So, how can I change the execution working directory (without hardcode)? What will be the best practice to load any files attached to test case?

like image 839
Dzmitry Martavoi Avatar asked Apr 11 '13 21:04

Dzmitry Martavoi


2 Answers

I use this for integration tests that need to access data files.

On any machine the test needs to run create a system environment variable named TestDataDirectory that points to the root of where your test data is.

Then have a static method that gets the file path for you..

public static class TestHelper
{
    const string EnvironmentVariable = "TestDataDirectory";
    static string testDataDir = Environment.GetEnvironmentVariable(EnvironmentVariable);

    public static string GetTestFile(string partialPath)
    {
        return Path.Combine(testDataDir, partialPath);
    }
}

...

[Test]
public void LexicalTest1()
{
    var codePath = TestHelper.GetTestFile(@"\EvolutionSamples\sample1.evol");
    //.....
}
like image 72
Kevin Avatar answered Sep 30 '22 14:09

Kevin


I am using this code:

   var str = Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetName().CodeBase);
   if (str.StartsWith(@"file:\")){
       str = str.Substring(6);
   }

Getting in str variable the assembly directory.

like image 22
Óscar Andreu Avatar answered Sep 30 '22 14:09

Óscar Andreu