how to give relative path for json file for test cases in C#

80 Views Asked by At

Need to access a json file from project structure. so need to give relative. C# This is for the test case where the data list is compare with the data List from the API call. string dataListJSONFilePath = "C:\Repo\Project\Admins\Data Folder\dataList.json";

1

There are 1 best solutions below

0
Michał Turczyn On

If i understood you correctly, you could add json file to your project and set its "build action" to none and "copy to output directory" as "always" in file properties: enter image description here

Here's example JSON:

{
  "ExampleProperty": "hello world"
}

And here's example unit test:

using System.Text.Json;

namespace UnitTestsProject;

public record JsonBodyForTest(string ExampleProperty);

public class UnitTest1
{
    [Fact]
    public void ReadPropertyFromJsonFile_ShouldPopulateCorrectly()
    {
        // Arrange
        var jsonBody = File.ReadAllText("testfile.json");

        // Act
        var parsed = JsonSerializer.Deserialize<JsonBodyForTest>(jsonBody);

        // Assert
        Assert.False(string.IsNullOrEmpty(parsed.ExampleProperty));
    }
}