Unit Testing Custom .NET Configuration Classes

I am currently in the process of writing some custom .NET Configuration classes, such as custom ConfigurationHandler implementations, ConfigurationElementCollection, etc. Configuration classes need to be tested just like any other code, especially if they contain any behavior beyond the simple mapping of an XML property to a class property. It turns out the .NET Configuration API makes this pretty easy:

 

    [TestFixture]
    public class ConfigurationTestFixture
    {
        [Test]
        public void TestCustomConfig()
        {
            var cfg = GetTestConfiguration();
            Assert.That(cfg, Is.Not.Null);

            var mySection = cfg.GetSection("mySection") as mySection;
            Assert.That(mySection, Is.Not.Null);
            Assert.That(mySection.CustomProp,Is.EqualTo("configuredValue"));
            ...

        }

        private System.Configuration.Configuration GetTestConfiguration()
        {
            var map = new ExeConfigurationFileMap()
                          {
                              ExeConfigFilename =
                              Path.Combine(AppDomain.CurrentDomain.BaseDirectory,
                              "TestApp.config")
                          };

            return ConfigurationManager.OpenMappedExeConfiguration(
                    map, ConfigurationUserLevel.None);
        }

 

For this to work you’ll need a configuration file with the appropriate XML to test your classes stored at the root of your test project with the Copy To Output Directory property set to Copy If Newer. You could use any path to create your ExeConfigurationFileMap, but for me putting the file at the root seemed the easiest solution.

image

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: