【问题标题】:How to use json file located in web api project from separate test project如何从单独的测试项目中使用位于 web api 项目中的 json 文件
【发布时间】:2021-04-30 18:02:43
【问题描述】:

TL;DR

我使用来自第 3 方库的枚举,我想进行一些测试来检查这些枚举的值是否与我在位于主 Web api 项目中的 dictionaries.postmarks.json 文件中的值一致。

有什么方法可以在不将dictionaries.postmarks.json 文件复制到测试项目的情况下实现这一点?

详情:

dictionaries.postmarks.json 包含一些密钥对:

{
  "PostMarks": [
    {
      "Code": 0,
      "Name": "Simple"
    },
    {
      "Code": 1,
      "Name": "Complex"
    },
    {
      "Code": 2,
      "Name": "Any"
    },
    . . .
  ]
}

ConfigureServices我注册选项如下:

var dictionariesConfiguration = new ConfigurationBuilder()
        .SetBasePath(HostEnvironment.ContentRootPath)
        .AddJsonFile("dictionaries.postmarks.json", false, true)
        .Build();

services.Configure<DictionaryOptions>(dictionariesConfiguration);

就是这样。从那以后,我可以非常完美地在我的服务中使用IOptions&lt;DictionaryOptions&gt;

现在我有一个单独的测试项目,我想在其中检查第 3 方 PostMark 枚举的值是否与我在 dictionaries.postmarks.json 文件中的值完全相同。

我不想将 json 文件复制到我的测试项目 (proposed here),因为我想测试完全存在于我的 web api 项目中的值。

这就是我到目前为止所做的:

public class EnumTests
{
    private readonly IConfiguration _configuration;

    public EnumTests()
    {
        _configuration = InitConfiguration();
    }

    private IConfiguration InitConfiguration()
    {          
        //var dir = should I hard code dir here?

        return new ConfigurationBuilder()
            .SetBasePath(dir)
            .AddJsonFile("dictionaries.postmarks.json")
            .Build();
    }

    [Fact]
    public void PostMarkEnum_ShouldBeEqualToPostMarksOptions()
    {
        var fromOptions = _configuration.GetSection("PostMarks").Get<List<DictionaryElement>>();
        var fromLibrary = Enum.GetValues(typeof(PostMark)).Cast<long>().ToList();

        bool equal = true;

        for (var i = 0; i < fromOptions.Count; i++)
        {
            if (fromOptions[i].Code != fromLibrary[i])
            {
                equal = false;
                break;
            }
        }

        Assert.True(equal);
    }
}

public class DictionaryElement
{
    public long Code { get; set; }
    public string Name { get; set; }
}

顺便说一句,我有一些使用WebApplicationFactory 的集成测试,所以我可以从中读取配置,但don't know 是否可能。

【问题讨论】:

    标签: c# asp.net-core integration-testing .net-5


    【解决方案1】:

    您可以将它们作为链接文件添加到您的项目中。但不要忘记将复制到输出文件夹设置为始终

    链接文件只是指向原始文件的指针

    【讨论】:

      猜你喜欢
      • 2022-11-10
      • 1970-01-01
      • 2018-05-17
      • 2011-09-19
      • 1970-01-01
      • 2018-04-05
      • 2015-07-14
      • 2010-11-12
      • 1970-01-01
      相关资源
      最近更新 更多