Welcome to blogs.conchango.com Sign in | Join | Help

Welcome to blogs.conchango.com

Gordon Duthie's Blog

Modifying web.config at runtime for unit test

Lately I've had the need to use the test framework from within Visual Studio. However, one problem which i came across was trying to change the web.config appSettings and connectionString to reference a local database.

Below is the solution I have came up with:

[ClassInitialize()]

        public static void ChangeWebConfigValuesForTest(TestContext testContext)
       {

            // Get the configuration file.
            ExeConfigurationFileMap map = new ExeConfigurationFileMap();
            map.ExeConfigFilename = "c:\\localpath\\web.config";
            Configuration webConfig = ConfigurationManager.OpenMappedExeConfiguration(map, ConfigurationUserLevel.None);

            // Change the app setting value
            AppSettingsSection appSettingsSection = (AppSettingsSection)webConfig.GetSection("appSettings");
           appSettingsSection.Settings["valueToChange"].Value = "TestValue"

           // Change connection string setting
           ConnectionStringSettings connectionStringSettings = webConfig.ConnectionStrings.ConnectionStrings["DBConnectionString"];
            connectionStringSettings.ConnectionString = "Data Source=.;Initial Catalog=TestDB;Persist Security Info=True;User ID=testuser;Password=password";

            //Save the config file
            webConfig.Save();

        }

Published 19 November 2008 08:47 by Gordon.Duthie
Filed under: ,

Comments

 

steven.evans said:

I don’t know your exact scenario here so if this is not applicable then apologies.

What we do on the project that I’m working on is have a copy of the web.config file in the test project that we need to use it named something like: testprojectname.dll.config and set the properties of the file to 'build action' =  none and 'copy to output' = always. That way your tests can get access to the config and you can have different settings for test and app.

Would this help?

November 19, 2008 10:33
Anonymous comments are disabled
Powered by Community Server (Personal Edition), by Telligent Systems