The appsettings.json
configuration can be mocked in several ways, the examples below use Moq.
Consider these settings:
1 | { |
This would be read in the consumer class as:
1 | var url = config.GetValue<string>("Services:SomeService:Url"); |
Option 1: Mock configurationSection and configuration
In the testing class you need to mock configurationSection
and configuration
as follows
1 | var configurationSectionMock = new Mock<IConfigurationSection>(); |
Then inject configurationMock.Object
and it will be happy as when config.GetValue
is called.
Option 2: Read appsettings file based on Environment
Build up configuration
and read appsettings file.
1 | var environment = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT"); |
You can now read the configuration from configuration
1 | var url = configuration.GetValue<string>("Services:SomeService:Url"); |
Option 3: In Memory Collection
If the settings are nested and you need to mock several you can use a dictionary and add to the builder with .AddInMemoryCollection(appSettingsStub)
Consider these settings, the mock concearned with the RetryCount
and RetrySleepDuration
1 | { |
Create the dictionary
1 | var appSettingsStub = new Dictionary<string, string> { |
Create the config
1 | var configuration = new ConfigurationBuilder() |
Using a simple options class
1 | public class SomeServiceOptions |
You can then access this config and bind it to the options class.
1 | var someServiceConfig = configuration |