How to mock IConfiguration.GetValue

Solution 1:

You can use an actual Configuration instance with in-memory data.

//Arrange
var inMemorySettings = new Dictionary<string, string> {
    {"TopLevelKey", "TopLevelValue"},
    {"SectionName:SomeKey", "SectionValue"},
    //...populate as needed for the test
};

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


//...

Now it is a matter of using the configuration as desired to exercise the test

//...

string value = configuration.GetValue<string>("TopLevelKey");

string sectionValue = configuration.GetSection("SectionName").GetValue<string>("SomeKey");

//...

Reference: Memory Configuration Provider

Solution 2:

I do not have idea about NSubstitute, but this is how we can do in Moq. Aproach is same in either cases.

You can Mock GetSection and return your Own IConfigurationSection.

This includes two steps.

1). Create a mock for IConfigurationSection (mockSection) & Setup .Value Property to return your desired config value.

2). Mock .GetSection on Mock<IConfiguration>, and return the above mockSection.Object

Mock<IConfigurationSection> mockSection = new Mock<IConfigurationSection>();
mockSection.Setup(x=>x.Value).Returns("ConfigValue");

Mock<IConfiguration> mockConfig = new Mock<IConfiguration>();
mockConfig.Setup(x=>x.GetSection(It.Is<string>(k=>k=="ConfigKey"))).Returns(mockSection.Object);

.GetValue() internally makes use of GetSection().

Solution 3:

Mock IConfiguration

Mock config = new Mock();

setupGet

        config.SetupGet(x => x[It.Is<string>(s=>s == "DeviceTelemetryContainer")]).Returns("testConatiner");
        config.SetupGet(x => x[It.Is<string>(s => s == "ValidPowerStatus")]).Returns("On");

Solution 4:

IConfiguration.GetSection<T> must be mocked indirectly. I don't fully understand why because NSubstitute, if I understand correctly, creates its own implementation of an interface you're mocking on the fly (in memory assembly). But this seems to be the only way it can be done. Including a top-level section along with a regular section.

var config = Substitute.For<IConfiguration>();
var configSection = Substitute.For<IConfigurationSection>();
var configSubSection = Substitute.For<IConfigurationSection>();
configSubSection.Key.Returns("SubsectionKey");
configSubSection.Value.Returns("SubsectionValue");
configSection.GetSection(Arg.Is("SubsectionKey")).Returns(configSubSection);
config.GetSection(Arg.Is("TopLevelSectionName")).Returns(configSection);

var topLevelSection = Substitute.For<IConfigurationSection>();
topLevelSection.Value.Returns("TopLevelValue");
topLevelSection.Key.Returns("TopLevelKey");
config.GetSection(Arg.Is<string>(key => key != "TopLevelSectionName")).Returns(topLevelSection);

// GetValue mocked indirectly.
config.GetValue<string>("TopLevelKey").Should().Be("TopLevelValue");
config.GetSection("TopLevelSectionName").GetSection("SubsectionKey").Value.Should().Be("SubsectionValue");