64

I am currently using the standard Microsoft Unit Test suite in VS 2008. ReSharper 4.5 is also installed. My unit tests rely on an TestInitialize method which pre-loads a data file. The path to this test data file will differ depending on if I run the unit test from within VS 2008 using the standard Ctrl-R + Ctrl-T command versus the Resharper unit test execution command.

How can my TestInitialize method know the correct path to the unit test data files?

Update:

The test data is sizable enough that I don't want to push it into a string so prefer to keep it as an external file. The file structure of my test project is that of the standard unit test project created with an MVC application. Under the root of the test project, a new folder was created called 'Test Data'. It's this folder I'd like to access regardless of test runner.

BigBrother
  • 1,100
  • 1
  • 9
  • 17

2 Answers2

94

You're saying the test file's location will differ depending on the test runner, so I assume it's included in the project and copied together with the dll's.

string path = AppDomain.CurrentDomain.BaseDirectory;

This will get you the folder where you're executing the test from.

[Edit]

In Visual Studio.

Resharper -> Options -> Tools -> Unit Testing -> Run Results from: Specified Folder (or change the project output folder of your test project)

Where you can specify the folder of your test data, or relative to the specified folder.

Mikael Svenson
  • 39,181
  • 7
  • 73
  • 79
  • 1
    Huge thanks. I was mucking about using the ExecutingAssembly and got a strange path pointing deep into my windows profile. The test data were nowhere in sight... – Tormod Jan 06 '12 at 15:01
  • 1
    Note that this gives you the path to the \bin\Debug or \bin\Release folder inside the Test project, like "C:\Yadda\MyProject\bin\Debug" – Chris Moschini Jun 12 '13 at 01:17
  • 1
    also note, at least for Visual Studio 2019, if you put your file in a subfolder in the solution, the folder structure is kept along on copy. And of course make sure your file has the "Copy always" or "Copy if newer" property, in the solution explorer. – Pac0 May 11 '20 at 20:54
24

(original answer updated to also accept .net core multi-target project output paths)

It assumes your test data files are in a folder that you pass as a parameter "testDataFolder" inside a root "Test_Data" folder:

public static string GetTestDataFolder(string testDataFolder)
{
    string startupPath = ApplicationEnvironment.ApplicationBasePath;
    var pathItems = startupPath.Split(Path.DirectorySeparatorChar);
    var pos = pathItems.Reverse().ToList().FindIndex(x => string.Equals("bin", x));
    string projectPath = String.Join(Path.DirectorySeparatorChar.ToString(), pathItems.Take(pathItems.Length - pos - 1));
    return Path.Combine(projectPath, "Test_Data", testDataFolder);
}
DaniCE
  • 2,412
  • 1
  • 19
  • 27