如何为 C# 中的测试用例提供 json 文件的相对路径

问题描述 投票:0回答:1

需要从项目结构访问json文件。所以需要给亲戚。 C# 这是针对将数据列表与 API 调用中的数据列表进行比较的测试用例。 字符串 dataListJSONFilePath = "C:\Repo\Project\Admins\Data 文件夹\dataList.json";

c# json .net file testcase
1个回答
1
投票

如果我理解正确,您可以将 json 文件添加到您的项目中,并将其“构建操作”设置为“无”,并将“复制到输出目录”设置为“始终”在文件属性中:

这是 JSON 示例:

{
  "ExampleProperty": "hello world"
}

这是示例单元测试:

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));
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.