Changing AppSettings in tests
ConfigurationManager.AppSettings is a static dependency, so how can you unit test? Actually it's pretty easy - GetSection, Save, RefreshSection.
The only caveat is you must have an app.config in your test project, even if it's empty.
[TestClass]
public class ChangeConfigurationTest
{
private const string Value = "Hello";
private const string KeyValue = "MySetting";
private static void ChangeConfiguration()
{
//the .config must exist (AppSettings doesn't have to be there).
//if your test class doesn't have an App.config, this succeeds but the new appSetting is not loaded.
var config = ConfigurationManager.OpenExeConfiguration(Assembly.GetCallingAssembly().Location);
var appSettings = (AppSettingsSection)config.GetSection("appSettings");
appSettings.Settings.Clear();
appSettings.Settings.Add(KeyValue, Value);
config.Save();
ConfigurationManager.RefreshSection("appSettings");
}
[TestMethod]
public void TestMethod1()
{
var setting = ConfigurationManager.AppSettings[KeyValue];
Assert.AreEqual(true, string.IsNullOrEmpty(setting));
ChangeConfiguration();
setting = ConfigurationManager.AppSettings[KeyValue];
Assert.AreEqual(Value, setting);
}
}
ConnectionStrings
The corresponding code for a connection string.
private static void ChangeConfiguration()
{
var config = ConfigurationManager.OpenExeConfiguration(Assembly.GetCallingAssembly().Location);
var connectionStrings = (ConnectionStringsSection)config.GetSection("connectionStrings");
connectionStrings.ConnectionStrings["MyDatabase"]
.ConnectionString = @"Data Source=C:\Dev\commands.sqlite";
config.Save();
ConfigurationManager.RefreshSection("connectionStrings");
}