本文介绍了在单元测试中反序列化 appsettings.json的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

许多示例展示了如何在 Startup.cs 类中反序列化您的应用设置.我明白了.但这不是我要问的.我在单元测试构造函数中工作.

There are many examples out there that show how to deserialize your app settings within the Startup.cs class. I get that. But that's not what I'm asking. I'm working within a unit test constructor.

这个问题很接近:在 .NET Core 测试项目但仔细阅读后,我并没有看到一个灌篮高手的答案.

This question is close: Read appsettings json values in .NET Core Test ProjectBut in reading it carefully, I'm not seeing a slam dunk answer.

appsettings.json:

appsettings.json:

{
  "AppSettings": {
    "myKey1": "myValue1",
    "myKey2": "myValue2",
  }
}

还有:

public class AppSettings
{
    public string myKey1 { get; set; }
    public string myKey2 { get; set; }
}

我能够很好地获得单个值:

I am able to get single values just fine:

var config = new ConfigurationBuilder()
              .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
              .Build();
var myValue1 = config.GetSection("AppSettings:myKey1 ").Value;

但我没有弄清楚如何创建 AppSettings 的实例.我试过了:

But what I'm not figuring out is how to get create an instance of AppSettings. I've tried:

var appSettings = config.GetValue<AppSettings>("AppSettings");

但结果是空的.我已经尝试创建我自己的 IServiceCollection 实例,这样我就可以像在 Startup.cs 中那样做一些事情,但我没有取得任何进展.

But that ends up null. And I've played around with trying to create my own instance of IServiceCollection so I could do something like you might in Startup.cs, but I'm not making any progress.

推荐答案

我最终只是这样做了.

public class AppSettings
{
    AppSettings(IConfigurationRoot config)
    {
            myKey1 = config.GetSection("AppSettings:MyKey1").Value;
            myKey2 = config.GetSection("AppSettings:MyKey2").Value;
    }

    public string myKey1 { get; set; }
    public string myKey2 { get; set; }
}

不理想,但它完成了工作,我可以继续前进.

Not ideal but it gets the job done and I can move on.

这篇关于在单元测试中反序列化 appsettings.json的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-13 18:38