I have a unit tests project with it's own app.config
file, which is a mock of a real configuration file defined by target project being tested. This mock file is loaded and processed by unit test code (not by target project), and it works properly if I run only tests within only this one test project.
ConfigurationManager.GetSection(sectionName)
However, if I run tests from several test projects, and other test projects are performed prior to relevant project, the above statement returns null
. If discussed test project is performed as first, there is no problem with loading configuration file.
How can I fix loading of configuration file in unit test to work correctly?
Your problem is not ConfigurationManager.GetSection(sectionName) returns null, it is how can I test some code containing ConfigurationManager.GetSection(sectionName)?
And the answer is: wrap it, inject it, then for your test mock it.
You have several examples of pepole facing the same issue:
(The second one is much more detailed, still the idea is the same).
Anyway, this is quite logical that you cannot use information from app.config in a unit test, as an app.config is contextual for the whole application, when it is required to write test absolutely independant. If you use directly an app.config value, then you have non logical coupling.
Facing the same issue this solved it:
app.config
should be picked up inside a unit test if it's Copy to Output Directory
property set to Copy if newer
or if you add the DeploymentItem attribute [DeploymentItem("your.config")]
.
More detailed description: http://social.msdn.microsoft.com/Forums/en-US/3e520735-8ced-4092-b681-38b69e0db534/unit-test-configuration#32998bf4-5a76-4083-99da-42f0c3a91559
similar question: MSTest and app.config issue
I think problem is either it could not find the file in test working directory or file itself failed to load.
I have solved this problem by explicitly loading configuration file with name. In your case you can try same.
ExeConfigurationFileMap configMap = new ExeConfigurationFileMap();
configMap.ExeConfigFilename = @"d:\test\test.config";
Configuration config = ConfigurationManager.OpenMappedExeConfiguration(configMap, ConfigurationUserLevel.None);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With