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();
}