Reading AppSettings to be Unit Test friendly.

My application uses a lot of AppSettings to enable/disable different function and I wanted to created unit tests for different combination. I found the simplest way is to create static class data field, that is set to null by default, and loaded from config file if it is null. This allows in unit test methods to explicitely assign values, and when you want return to reading from config file, just reset it to null.

        static private bool? st_bAPIEnabled;

        public static bool IsAPIEnabled()

        {

            st_bAPIDomesticEnabled = AppSettingsHelper.GetIsTrueIfNull(st_bAPIEnabled, “EnableAPI”);

            return (bool)st_bAPIEnabled;

        }

     #region  “set enabled flags- use from Unit tests”

        public static void SetAPIEnabled(bool value)

        {

            st_bAPIEnabled = value;

        }

        public static void ResetAPIEnabledFlag()

        {

            st_bAPIEnabled =null;

        }

        #endregion  //”set API enabled flags- use from Unit tests”

 

      public class AppSettingsHelper

      {

 

        public static bool GetIsTrueIfNull(bool? bEnabled, string AppSettingsKey)

        {

            if (bEnabled == null)

            {

                bEnabled = AppSettingsHelper.ConfigurationIsTrue(AppSettingsKey);

            }

            return (bool)bEnabled;

        }

            public static bool ConfigurationIsTrue(string key)

            {

            string setting = WebConfigurationManager.AppSettings[key];

            bool bRet=false;

            if(!string.IsNullOrEmpty(setting))

                  {

                bRet =(setting.ToLower() == “true”);

            }

            return bRet;

            }

­­­­}

 

Alternative option described in the posts Abstract Class with Template Method – Testing Different Application Configuration Settings – App.Config – Web.Config  and Unit tests – Changing app.config values at runtime.

 

By the way, the post How NUnit Finds Config Files describes, how to make config files available during unit tests. If you are using MS Team System, see Loading appsettings or custom settings from MSTest.exe  

Advertisements