I need to mock IConfiguration for the following appsettings.json values.
{
"a": 0.01,
"b": [ "xxx", "yyy" ],
}
However, the following code gets error on 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);
Error:
Argument 1: cannot convert from 'System.Collections.Generic.List' to 'string'
I tried to change the error line to:
b.Setup(x => x.GetChildren()).Returns(new List<string> { "xxx", "yyy" } as IEnumerable<string>);
Now the error is
cannot convert from 'System.Collections.Generic.IEnumerable<string>' to
'System.Collections.Generic.IEnumerable<Microsoft.Extensions.Configuration.IConfigurationSection>'
The configuration module is independent and allows for the creation an in memory configuration to test against without the need to mock.
//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();
//...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With