我需要为以下IConfiguration
值模拟appsettings.json
。
{
"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);
错误:
参数1:无法从“ System.Collections.Generic.List”转换为“字符串”
我试图将错误行更改为:
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>'
答案 0 :(得分:3)
配置模块是独立的,并允许创建内存中配置以进行测试,而无需进行模拟。
//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();
//...
答案 1 :(得分:0)
或者,您可能想从转换为流的json字符串中读取配置。 imo看起来有点花哨,并且在测试复杂配置时提供了更大的灵活性:
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();
}
}