Ugly Stool Rotating Header Image

Test Configuration Sections in .config Files

The .config files centralize and standardize how per application or per library configuration data are stored.  The format can be a little dense to get through, and I always tend to leak this information from my brain.  I only need to know when I start a new project. 

I have had to relearn configuration data yet again, so I figured I should commit it to the electrons so I do not forget again.

Use the tests with external file dependencies post as a starting point.  The tests have to be written this way because the System.Configuration API does not support accepting input from a stream.

Step 1: Create a minimal configuration.  In this case, I have two configuration values.  The maximum number of tasks, and the period.

namespace My.Library
    public class MyConfiguration : ConfigurationSection
        [ConfigurationProperty("maxTasks", IsRequired = true)]
        public int MaxTasks
            get { return (int)this["maxTasks"];  }
            set { this["maxTasks"] = value; }
        [ConfigurationProperty("period", IsRequired = false, DefaultValue = "00:00:15")]
        public TimeSpan Period
            get { return (TimeSpan)this["period"]; }
            set { this["period"] = value; }

Step 2: Create an example configuration file to use for testing.

    <section name="myConfig" type="My.Library.MyConfiguration, Library" />
    period="00:00:01" />

NOTE: When defining the configuration section (<section />) at a minimum the type attribute must include the full name of the type (My.Library.MyConfiguration).  The value after the comma is the assembly name (minus .exe/.dll) containing the type.  Additional information can be specified such as the version, and public key token, i.e. strong name of the assembly.

Step 3: Write a test to validate the configuration file.

public void MyConfiguration_OverrideAllValues()
    string fileName = Assembly.GetExecutingAssembly().LoadFileAssemblyResource(
        ConfigurationFileMap fileMap = new ConfigurationFileMap(fileName);
        Configuration configuration = ConfigurationManager.OpenMappedMachineConfiguration(
        MyConfiguration mine = (MyConfiguration)configuration.GetSection(
        Assert.Equal(1, mine.MaxTasks);
        Assert.Equal(TimeSpan.FromSeconds(1), mine.Period);

This test validates the configuration data loaded matches the data in the seed file, example1.config.  There are two other tests that should be written.

  1. Validate that period correctly defaults to 15 seconds.
  2. Validate that MaxTasks is a required parameter.

Comments are closed.

Page optimized by WP Minify WordPress Plugin