Search code examples
c#unit-testingmoq

How to mock ConfigurationManager.AppSettings with moq


I am stuck at this point of code that I do not know how to mock:

ConfigurationManager.AppSettings["User"];

I have to mock the ConfigurationManager, but I don't have a clue, I am using Moq.

Someone can give me a tip? Thanks!


Solution

  • I believe one standard approach to this is to use a facade pattern to wrap the configuration manager and then you have something loosely coupled that you have control over.

    So you would wrap the ConfigurationManager. Something like:

    public class Configuration: IConfiguration
    {
        public string User
        {
            get
            { 
                return ConfigurationManager.AppSettings["User"];
            }
        }
    }
    

    (You can just extract an interface from your configuration class and then use that interface everywhere in your code) Then you just mock the IConfiguration. You might be able to implement the facade itself in a few different ways. Above I chose just to wrap the individual properties. You also obtain the side benefit of having strongly typed information to work with rather than weakly typed hash arrays.