Problem:
I want to read the connection strings from my app.config of my Web Test Project but it never loads.
Solution:
Use the Configuration Manager OpenMappedExeConfiguration call to load the app.config file.
Code:
// Map the new configuration file.
ExeConfigurationFileMap configFileMap = new ExeConfigurationFileMap();
configFileMap.ExeConfigFilename =
System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name + ".config";
// Get the mapped configuration file
var config = ConfigurationManager.OpenMappedExeConfiguration(
configFileMap, ConfigurationUserLevel.None);
Explanation:
The app.config of the test project is not loaded for web or load tests, because they are run in the same application domain as the test process (either vstesthost.exe or qtagent.exe), so they will load their config files instead. Therefore, we simply load the configuration file ourselves.
Loading a configuration file is a two phased process. First we build a ExcConfigurationFileMap object and set the name of our configuration file to be loaded. Then we open that file with a call to OpenMappedExeConfiguration method of the ConfigurationManager class.
I am not a fan of hard coded values so we are going to get the name of the assembly using reflection and simply concatenate ".config" to the end of it. Calling System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name will return the name of the assembly.
After calling OpenMappedExeConfiguration you can use the returned object to access the connection strings or any other data from the app.config.