gpt4 book ai didi

c# - 模拟 IConfiguration 的 GetChildren() 以返回 List

转载 作者:行者123 更新时间:2023-11-30 21:26:31 26 4
gpt4 key购买 nike

我需要模拟 IConfiguration对于以下 appsettings.json值(value)观。

{
"a": 0.01,
"b": [ "xxx", "yyy" ],
}

但是,以下代码在 b.Setup(x => x.Value).Returns(new List<string> { "xxx", "yyy" }); 上出错.

var configuration = new Mock<IConfiguration>();

var a= new Mock<IConfigurationSection>();
a.Setup(x => x.Value).Returns("0.01");

var b = new Mock<IConfigurationSection>();
b.Setup(x => x.Value).Returns(new List<string> { "xxx", "yyy" }); // Error

configuration.Setup(x => x.GetSection("a")).Returns(a.Object);
configuration.Setup(x => x.GetSection("b")).Returns(b.Object);

错误:

Argument 1: cannot convert from 'System.Collections.Generic.List' to 'string'

更新:

我尝试将错误行更改为:

b.Setup(x => x.GetChildren()).Returns(new List<string> { "xxx", "yyy" } as IEnumerable<string>);

现在错误是

cannot convert from 'System.Collections.Generic.IEnumerable<string>' to
'System.Collections.Generic.IEnumerable<Microsoft.Extensions.Configuration.IConfigurationSection>'

最佳答案

配置模块是独立的,允许创建一个内存配置来测试而不需要模拟。

//Arrange
Dictionary<string, string> inMemorySettings =
new Dictionary<string, string> {
{"a", "0.01"},
{"b:0", "xxx"},
{"b:1", "yyy"}
};

IConfiguration configuration = new ConfigurationBuilder()
.AddInMemoryCollection(inMemorySettings)
.Build();

//Verify expected configuraton
configuration.GetSection("a").Get<double>().Should().Be(0.01d);
configuration.GetSection("b").Get<List<string>>().Should().NotBeEmpty();

//...

引用Memory Configuration Provider

关于c# - 模拟 IConfiguration 的 GetChildren() 以返回 List<string>?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59164304/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com