When you guys are unit testing an application that relies on values from an app.config file? How do you test that those values are read in correctly and how your program re
Well, I just had the same problem... I wanted to test a BL project that is referenced from a web site . but i wanted to test the BL only. So in the pre-build event of the test project I copy the app.Config files into the bin\debug folder and reference them from the app.config ...
You can always wrap the reading-in bit in an interface, and have a specific implementation read from the config file. You would then write tests using Mock Objects to see how the program handled bad values. Personally, I wouldn't test this specific implementation, as this is .NET Framework code (and I'm assuming - hopefully - the MS has already tested it).
You can modify your config section at runtime in your test setup. E.g:
// setup
System.Configuration.Configuration config =
ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
config.Sections.Add("sectionname", new ConfigSectionType());
ConfigSectionType section = (ConfigSectionType)config.GetSection("sectionname");
section.SomeProperty = "value_you_want_to_test_with";
config.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection("sectionname");
// carry out test ...
You can of course setup your own helper methods to do this more elegantly.
You can both read and write to the app.config
file with the ConfigurationManager
class
That worked for me:
public static void BasicSetup()
{
ConnectionStringSettings connectionStringSettings =
new ConnectionStringSettings();
connectionStringSettings.Name = "testmasterconnection";
connectionStringSettings.ConnectionString =
"server=localhost;user=some;database=some;port=3306;";
ConfigurationManager.ConnectionStrings.Clear();
ConfigurationManager.ConnectionStrings.Add(connectionStringSettings);
}
System.Configuration.Abstractions is a thing of beauty when it comes to testing this kind of stuff.
Here is the GitHub project site with some good examples: enter link description here
Here is the NuGet site: https://www.nuget.org/packages/System.Configuration.Abstractions/
I use this in almost all of my .NET projects.