I’m using VS Code under Linux (Debian Buster) and currently write some unittests using the MSTest-framework. Some of my tests have to read files that I have stored in my Test-project NewAppTest. UnitTest1.cs needs to read some_data.json, directory structure:
NewAppTest
+ UnitTest1.cs
+ some_data.json
In UnitTest1.cs I use this code to read some_data.json:
[TestMethod]
public void GetEmployee()
{
var data = File.ReadAllText("../../../some_data.json");
Assert.IsNotNull(data);
}
It bugs me that I need to prefix the filename with "../../../". Surely there must be a better way to set the current working dir. I googled some and found this and this, but I don’t understand it.
I would like to create a file like said .runsettings where I specify the current working directory for all my tests in the project.
I would rather not have to touch every testclass.
A sample minimal .runsettings befitting my use case would be nice.
2
Answers
Thank you, this worked well. For all who are reading along: I also created a subfolder named "subfolder" in the Test-Project and put some_data.json and more_data.json in there:
In the csproj I added this to include all files:
In the TestMethod I used this to read the files:
This way you don't need to edit your csproj when you add new data files for your tests.
A good way to include files in your test application is to use embedded resources. Embedded resources are bundled with the test build so they’re independent of its location.
To embed a file, edit your
.csproj
file and add the following item group (as a child of<Project>
):(If
some_data.json
is in a subfolder within the project, the path would besubfolder/some_data.json
).To read an embedded resource, use GetManifestResourceStream: