Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

moq

xunit

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'

Update:

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>'
like image 558
ca9163d9 Avatar asked Dec 14 '25 04:12

ca9163d9


1 Answers

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();

//...

Reference Memory Configuration Provider

like image 124
Nkosi Avatar answered Dec 15 '25 18:12

Nkosi