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

sgnsajgon picture sgnsajgon · Aug 26, 2013 · Viewed 8.4k times · Source

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?

Answer

Ouarzy picture Ouarzy · Sep 4, 2013

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.