将 IConfiguration 的 GetChildren() 模拟到 return 列表<string>?

Mock IConfiguration's GetChildren() to return List<string>?

我需要为以下 appsettings.json 值模拟 IConfiguration

{
  "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

或者,您可能希望从转换为流的 json 字符串中读取配置。在我看来,这看起来有点花哨,并且在测试复杂配置时提供了更大的灵活性:

public static class ConfigurationHelper
{
    public static IConfigurationRoot GetConfiguration()
    {
        byte[] byteArray = Encoding.ASCII.GetBytes("{\"Root\":{\"Section\": { ... }}");
        using var stream = new MemoryStream(byteArray);
        return new ConfigurationBuilder()
            .AddJsonStream(stream)
            .Build();
    }
}