Mocking IConfiguration Extension Method

In this post I wrote about the use of app settings in Asp.Net Core. One thing that I didn’t cover at the time was the fact that, as an extension library, the configuration extensions weren’t very easy to include in unit tests. Of course the intention is that you read the configuration at the start, pass through a model class and no mocking is required.

However, sometimes you’ll find yourself wanting to mock out a particular setting. Before I get into this, this post is heavily based on this article which describes the same process.

The following is a code sample using Moq:

            var configuration = new Mock<IConfiguration>();

            var configurationSection = new Mock<IConfigurationSection>();
            configurationSection.Setup(a => a.Value).Returns("testvalue");

            configuration.Setup(a => a.GetSection("TestValueKey")).Returns(configurationSection.Object);            

This will cause any call to get the app settings key “TestValueKey” to return “testvalue”. As is stated in the linked article, whilst GetValue is an extension method, GetSection is not, but is (internally) called by GetValue.


6 thoughts on “Mocking IConfiguration Extension Method

    1. mike

      I am having trouble returning an int value. In our appsettings.json file we have a setting that is set to an int. I can’t seem to set this up in the mock data to be able to use it for tests. It seems to only allow strings for the return value.

    1. pcmichaels Post author

      It’s quite neat. I’ve started to view passing the config around as a bit of an anti-pattern altogether – partly because of the need for these type of solutions, and partly because it’s dependency injection in name only: your class had to be aware of a, potentially complex, set of configuration. I feel a new post coming on about this, actually 🙂

This site uses Akismet to reduce spam. Learn how your comment data is processed.