Abstract Class with Template Method - Testing Different Application Configuration Settings - App.Config - Web.Config

I just responded to an email message from a reader asking for a possible solution for testing different application configuration settings in say an app.config or web.config file.

One possible solution for testing different application configuration settings is to use an abstract class with a template method to access your application settings.

Let's create a very primitive abstract class that will allow you to access application settings based on a key:


public abstract class AppSettings
{
    // Template Method
    public string GetSetting(string key)
    {
        return GetTheSetting(key);
    }

    // Hook
    protected abstract string GetTheSetting(string key);
}


Now you can create several concrete classes that you can use in your applications and unit tests to help you test the application using different scenarios:


public class StraightFromConfigSettings : AppSettings
{
    protected override string GetTheSetting(string key)
    {
        return ConfigurationSettings.AppSettings[key];
    }
}


public class Scenario1Settings : AppSettings
{
    protected override string GetTheSetting(string key)
    {
        string setting = string.Empty;

        switch (key)
        {
            case "ConnectionString" : setting = "..."; break;
            case "AnotherKey" : setting = "..."; break;
            default: setting = ConfigurationSettings.AppSettings[key]; break;
        }

        return setting;
    }
}


Pass the appropriate AppSettings Class into the constructor of your Application Class:

public class MyApplication : ...
{
    private AppSettings appSettings;

    public MyApplication(AppSettings settings)
    {
        appSettings = settings;
    }

    // Could Do It This Way...
    public string ConnectionString
    {
        get { return appSettings.GetSetting("ConnectionString"); }
    }

    // Or This Way...
    public string GetSetting(string key)
    {
        return appSettings.GetSetting(key);
    }
}


Abstract classes with template methods are very useful in day-to-day development.  This shows one possible way of using them.  Certainly these classes need to be made more robust, but this is one possible way of testing your application using different application settings.

posted on Friday, January 14, 2005 3:57 PM

Main

News

Green Tea

.NET Development

Enterprise Library

Patterns & Practices