Question

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?

Était-ce utile?

La solution

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.

Autres conseils

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);

I used the test project post build command line, but remember to build the project if there are changes:

copy /Y "$(SolutionDir)$(SolutionName)\App.Debug.config" "$(TargetDir)$(ProjectName)$(TargetExt).config"
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top