martavoi
martavoi

Reputation: 7092

nunit test working directory

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?

Upvotes: 13

Views: 13732

Answers (4)

Amit Sood
Amit Sood

Reputation: 435

You can use following to get the directory of assembly running the code something like

var AssemblyDirectory =  TestContext.CurrentContext.TestDirectory

Upvotes: 6

deadlydog
deadlydog

Reputation: 24434

We were having a problem where tests run using ReSharper and NCrunch would work, but the native VS Test Runner would not be able to find the files, when given just a relative file path for the test to use. I solved it by creating a function that you pass the relative test file path into, and it will give you the absolute file path.

private static string _basePath = Path.GetDirectoryName(typeof(NameOfYourTestClassGoesHere).Assembly.Location);
private string GetAbsoluteTestFilePath(string relativePath) => Path.Combine(_basePath, relativePath);

You would then use the function like so:

var input = File.ReadAllLines(GetAbsoluteTestFilePath(@"TestData/YourTestDataFile.txt"));

Upvotes: 0

Óscar Andreu
Óscar Andreu

Reputation: 1700

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.

Upvotes: 2

Kevin
Kevin

Reputation: 4636

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");
    //.....
}

Upvotes: 2

Related Questions