Skip to content

Instantly share code, notes, and snippets.

@umair-me
Last active July 7, 2022 03:00
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save umair-me/bb23e6d9f367cf2f992ff7126380c667 to your computer and use it in GitHub Desktop.
Save umair-me/bb23e6d9f367cf2f992ff7126380c667 to your computer and use it in GitHub Desktop.
Mock Configuration.GetSection
Mock<IConfiguration> configuration = new Mock<IConfiguration>();
configuration.Setup(c => c.GetSection(It.IsAny<String>())).Returns(new Mock<IConfigurationSection>().Object);
@pablotdv
Copy link

Does not work for me when I use on configuration.GetValue<string>("MyKey")

@umair-me
Copy link
Author

umair-me commented Aug 25, 2020

Sorry the title of this is misleading, I should have mentioned it is "Mock Configuration.GetSection"

Because GetValue is an extension method, and as far as I know extension methods can not be mocked (correct me if I am wrong). You will have to use GetSection as its not an extension method. And as per line 2 its mocking c.GetSection.

@pablotdv
Copy link

pablotdv commented Aug 27, 2020

It's okay man.
I solved my problem as follows:

var _configuration = new Mock<IConfiguration>();
var _configurationSection = new Mock<IConfigurationSection>();
_configurationSection.Setup(a => a.Value).Returns("1, 2, 3, 5, 7, 9");
_configuration.Setup(c => c.GetSection(It.IsAny<String>())).Returns(new Mock<IConfigurationSection>().Object);
_configuration.Setup(a => a.GetSection("MyKey")).Returns(_configurationSection.Object);

@guojianwei001
Copy link

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

        _configuration = new ConfigurationBuilder()
            .AddInMemoryCollection(inMemorySettings)
            .Build();

`
[()](https://docs.microsoft.com/en-us/aspnet/core/fundamentals/configuration/?view=aspnetcore-6.0&viewFallbackFrom=aspnetcore-3.0#memory-configuration-provider)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment