简体   繁体   中英

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?

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

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.

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"));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM