How to mock ConfigurationManager.AppSettings with moq

I am using AspnetMvc4. A moment ago I wrote

ConfigurationManager.AppSettings["mykey"] = "myvalue";

in my test method and it worked perfectly.

Explanation: the test method runs in a context with app settings taken from, typically a web.config or myapp.config. ConfigurationsManager can reach this application-global object and manipulate it.

Though: If you have a test runner running tests in parallel this is not a good idea.


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 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.