Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I access a data file from a Unit test method?

Here is how I am trying to access the file-

  1. I added a folder "TestData" in my unit test project

  2. Added a file via Add->Existing Item. Set the Build Action=None, Copy To Output Directory= Copy Always

Accessing the file in the unit test method as below-

string fileName = System.IO.Path.Combine(
            System.IO.Path.GetDirectoryName(
            System.Reflection.Assembly.GetExecutingAssembly().Location), "TestData\\TestExcel2007File1.xlsx");

XmlDocument actual;
actual.Load(fileName);       //Throws exception saying cannot find part of the file path

I also tried using the Method attribute as-

[TestMethod, DeploymentItem(@"Test Data\", @"Test Data\")]

None seems to work.

The file path generated is

"D:\\MyProject\\TestResults\\MACHINE_NAME 2015-01-23 05_21_45\\Out\\TestData\\TestExcel2007File1.xlsx"

And the Out folder does not have the TestData folder, or the Excel file.

EDIT: My referenced assemblies are present in the Out folder. I am using Visual Studio 2010.

I did the same steps in a different project in Visual Studio 2012 and that seem to find the file in place and work as expected.

EDIT 2: I found that the TestData folder is copied in bin\debug folder, not in the path generated. But the referenced assemblies are copied in the generated path!

EDIT 3: Added a testsetting file and checked the Enable Deployment Menu, added the TestData folder in the Additional Files and directory to deploy list, still didn't work.

like image 872
Thunderstruck Avatar asked Jan 23 '15 13:01

Thunderstruck


2 Answers

I work with xUnit and do it this way:

public static string GetImportPath()
{
    string[] importPaths =
    {
            @"TestData", @"..\TestData", @"..\..\TestData",
    };
    string importPath = importPaths.FirstOrDefault(Directory.Exists);
    Guard.NotNull(importPath, "importPath not found");
    return importPath;
}

I have the folder TestData in my Project folder, same level as bin, Properties etc.

In your case you'd use it like this:

string fileName = Path.Combine(GetImportPath(), "TestExcel2007File1.xlsx");
like image 131
DrKoch Avatar answered Nov 13 '22 18:11

DrKoch


Restarting the visual studio made it work. Not even closing and reopening the solution was enough!!!

like image 41
Thunderstruck Avatar answered Nov 13 '22 16:11

Thunderstruck