Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ConfigurationManager.GetSection(sectionName) returns null while performing unit tests

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?

like image 498
sgnsajgon Avatar asked Aug 26 '13 08:08

sgnsajgon


3 Answers

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:

  • http://chrisondotnet.com/2011/05/configurationmanager-wrapper-for-unit-testing/
  • http://weblogs.asp.net/rashid/archive/2009/03/03/unit-testable-configuration-manager.aspx

(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.

like image 86
Ouarzy Avatar answered Nov 11 '22 16:11

Ouarzy


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

like image 2
Andreas Avatar answered Nov 11 '22 17:11

Andreas


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);
like image 1
Binu Bhasuran Avatar answered Nov 11 '22 15:11

Binu Bhasuran