skip to Main Content

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


  1. Chosen as BEST ANSWER

    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:

    subfolder
    + some_data.json
    + more_data.json
    

    In the csproj I added this to include all files:

    <EmbeddedResource Include="subfolder/*.*" />
    

    In the TestMethod I used this to read the files:

    var assembly = typeof(UnitTest1).Assembly;
    using Stream stream =  assembly.GetManifestResourceStream("NewAppTest.subfolder.more_data.json");
    

    This way you don't need to edit your csproj when you add new data files for your tests.


  2. 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>):

    <ItemGroup>
      <EmbeddedResource Include="some_data.json" />
    </ItemGroup>
    

    (If some_data.json is in a subfolder within the project, the path would be subfolder/some_data.json).

    To read an embedded resource, use GetManifestResourceStream:

    var assembly = typeof(UnitTest1).Assembly; //Get the assembly in which the resources are embedded
    using Stream stream = assembly.GetManifestResourceStream("NewAppTest.some_data.json");
    
    //Read the data from the stream as a string
    using StreamReader reader = new(stream);
    string data = reader.ReadToEnd();
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search