【问题标题】:.NET Core getting Configuration appsettings.json values.NET Core 获取配置 appsettings.json 值
【发布时间】:2019-01-30 14:16:31
【问题描述】:

我正在尝试为以下内容编写单元测试:

[TestMethod]
public void GetInviteEndPoint_ShouldAccessAppSettings()
{
    //Data pulled from the appsettings.test.json
    var config = InitConfiguration();
    var inviteEndPointConfig = config["InviteEndPoint"]; // <-- Pain Point

    //Arrange Test && Mock if needed
    string mockInviteEndPoint = "https://graph.microsoft.com/v1.0/invitations";


    //Actual Code from Application (ACT)
    SendInvite sendInvite = new SendInvite();
    string inviteEndPoint = sendInvite.GetInviteEndPoint(config);

    //Assert 
    // Assert always tests (Expected[Arranged], Actual[From Code Base])
    Assert.AreEqual(mockInviteEndPoint, inviteEndPoint);
}

我的 appsettings.json 和 appsettings.test.json 看起来都一样。我很难从 .json 文件中获取值。我想知道是否有人可以对我坚持的这段代码提供任何见解。

{
    "SendeInvite": {
        "InviteEndPoint": "https://graph.microsoft.com/v1.0/invitations"
        ...Code Omitted... 
    } 
}

我是不是打错了config["InvitedEndPoint"]

请注意,我在测试类的顶部有以下代码

public static IConfiguration InitConfiguration()
{
    var config = new ConfigurationBuilder()
        .AddJsonFile("appsettings.test.json")
        .Build();
    return config;
}

【问题讨论】:

  • 有什么问题?你得到一个例外,是inviteEndPointConfig null?您确定正在加载正确的文件吗? "appsettings.test.json" 是一个 relative 路径,这意味着测试运行程序将在 its 工作目录中查找它。即使那是bin/Debug,您也需要确保将appsettings.test.json 复制到bin/debug
  • 您标记了您的问题 nunit,但根据您对 TestMethodAttribute 的使用,它显然使用了 Microsoft 的测试框架。请重新标记。

标签: c# json .net-core nunit


【解决方案1】:

试试:

var inviteEndPointConfig = config["SendeInvite:InviteEndPoint"];

可能是因为您将属性嵌套在 SendeInvite 中,您没有获得值。

【讨论】:

  • 我根据这篇帖子 - stackoverflow.com/questions/46940710/… 做了一些更改,并将返回结果。
  • 结合您的帖子和我发布的链接,我能够通过测试。开始让我的大脑围绕这个 Depdency Injection DI 敲打。有没有人推荐一些非常好的 DI 和 IC 读数并解释该主题?
猜你喜欢
  • 1970-01-01
  • 2020-06-11
  • 1970-01-01
  • 2021-04-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-06-23
相关资源
最近更新 更多