Mock settings in Web.conf with moq

asp.net-mvc-3, c#, moq, unit-testing

Solution

You are better off if you abstract the config file reading, and inject this abstraction into your class, instead of using directly `ConfigurationManager`. Then for your tests you can mock the abstraction.

Create a `IConfigurationReader` interface:

public interface IConfigurationReader
{
   string GetConfigSetting(string settingName);
}

The real implementation will use `ConfigurationManager`, but for tests you can mock `IConfigurationReader`.

It may seem overkill, but it's one time work which can be reused all over your application(s). The added benefit is, that if some day you decide to read configuration settings from somewhere else, you just change the implementation, w/o touching your consumers.

Problem

I am using `VisualStudio.TestTools` for unit-tests in my MVC3-application. The file `/Web.conf` contains a custom configuration which value `"false"` I cant get in my controller by `ConfigurationManager.AppSettings["DisableCheckboxes"];`: That works well on productive, but not in unit-tests. The value is `"null"`: How can I use the framework Moq to Mock the settings in `/Web.conf`?

Original source