Last active
July 7, 2022 03:00
-
-
Save umair-me/bb23e6d9f367cf2f992ff7126380c667 to your computer and use it in GitHub Desktop.
Mock Configuration.GetSection
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Mock<IConfiguration> configuration = new Mock<IConfiguration>(); | |
configuration.Setup(c => c.GetSection(It.IsAny<String>())).Returns(new Mock<IConfigurationSection>().Object); |
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);
`
// 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
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 useGetSection
as its not an extension method. And as per line 2 its mockingc.GetSection
.