代码之家  ›  专栏  ›  技术社区  ›  Moojjoo

.NET Core正在获取配置appsettings.json值

  •  0
  • Moojjoo  · 技术社区  · 6 年前

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

    [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;
    }
    
    1 回复  |  直到 6 年前
        1
  •  1
  •   Mike    6 年前

    尝试:

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

    可能是因为您在SendeInvite中嵌套了该属性,所以无法获取该值。