Cook Computing

Unit Testing Custom Config Section

February 15, 2009 Written by Charles Cook

I recently had to write some unit tests to test a custom configuration section. I was using NUnit so I didn't want to use the config file that would be loaded by NUnit, for example nunit-gui.exe.config, but instead wanted to load one or more separate test config files. The solution was to use the ExeConfigurationFileMap class. For example, say I have this config file:

    <section name="MySettings" type="MySettings, TestConfigSection" />
    testSetting="test" />

I can retrieve values from the custom section using code like this:

using System.Configuration;

public class MySettings : ConfigurationSection
  public string TestSetting
    get { return (string)this["testSetting"]; }
    set { this["testSetting"] = value; }


class Program
  static void Main(string[] args)
    MySettings settings
      = (MySettings)ConfigurationManager.GetSection("MySettings");
    string testSetting = settings.TestSetting;

To unit test the MySettings class I can use an instance of ExeConfigurationFileMap to load a test config file (in this case from the current directory where the test is being run):

using System.Configuration;
using NUnit.Framework;

public class ConfigTests
  public void testSetting()
    ExeConfigurationFileMap fileMap = new ExeConfigurationFileMap();
    fileMap.ExeConfigFilename = "ConfigTests.config";
    Configuration config 
      = ConfigurationManager.OpenMappedExeConfiguration(fileMap, 
    MySettings section 
      = config.GetSection("MySettings") as MySettings;
    Assert.AreEqual("test", section.TestSetting);