Reputation: 2125
I wonder if anyone could assist me..
I am working in a Visual Studio project, and we have recently begun working on Unit Tests for our project.
The Unit Tests rely on referencing an Excel file in the solution.
We have added code that appears to work well on each of our own environments with regards to referencing the file, and all seems good.
We have now also setup TFS to trigger it to run all the Unit Tests on each commit with a report, which has now shown to have some problems as almost all of them are failing, despite them all running successfully on our own environments.
TFS doesn't seem to provide any logging why the tests are failing, but we assume it's to do with the path referencing.
So our solution structure is like so..
..\head\Solution\Project\project.csproj
..\head\Solution\Tests\TestFiles\spreadsheet.xlsx
We are currently using the following code to reference the spreadsheet..
string filename = Path.Combine(Directory.GetParent(Directory.GetCurrentDirectory()).Parent.Parent.Parent.FullName, "Tests\\TestFiles\\spreadsheet.xlsx");
ExcelImporter importer = new ExcelImporter(filename);
Seems like we are explicitly calling a set number of parent folders, which probably isnt the same on the build server environment.
How can we better reference the spreadsheet file, assuming we'll never know how many parent folders to the solution there will be to it?
Upvotes: 2
Views: 6500
Reputation: 140
In the Unit tests project create a folder, let's call it "Resources", and copy your file there. Make sure the file properties set your file to be always copied to the output.
Then in your unit test just get the file like this:
string filename = Path.Combine(Environment.CurrentDirectory, "Resources\\spreadsheet.xlsx");
Relevant link: Enviroment.CurrentDirectory
Upvotes: 3
Reputation: 44605
I really would not got this way, the physical path where your unit tests will be running from might be very different on the build server compared to your local dev machines.
in general you should simply include (even adding it as a link) a reference to the solution item (excel file) in your unit test project and then you can set its property to copy to output folder so that when unit tests assembly is generated the excel file will also be copied in the same location as the assembly of unit tests, then at the top of your test method you can declare the dependency in this way with the standard attribute:
[DeploymentItem("spreadsheet.xlsx")]
this should work well for MS Tests at least, we use it and works with no issues.
Upvotes: 4