问题描述
有很多 示例,它们显示了如何在 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.
此问题已关闭:
但仔细阅读后,我没有看到扣篮的答案。
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 $ c中做类似的事情$ c>,但是我没有任何进展。
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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!