我有一个单元测试项目有它自己的的app.config 文件,该文件是由目标项目定义一个真正的配置文件的模拟正在测试中。这个模拟文件被加载,并通过单元测试code(不是目标项目)处理,它工作正常,如果我只运行在仅这一项测试项目的测试。
ConfigurationManager.GetSection(sectionName)
不过,如果我从几个测试项目,和其他测试项目运行测试前,相关项目执行中,上述语句返回空。如果讨论的试验项目作为第一个进行的,没有与加载配置文件没有问题。
我如何解决在单元测试中加载配置文件才能正常工作?
解决方案您的问题不是ConfigurationManager.GetSection(sectionName)返回null,这是我可以测试一些含ConfigurationManager.GetSection(sectionName)code
答案是:包装它,它注入,那么你的测试模拟它
您有生民所面临的同一个问题的几个例子:
- chrisondotnet/2011/05/configurationmanager-wrapper-for-unit-testing/
- weblogs.asp/rashid/archive/2009/03/03/unit-testable-configuration-manager.aspx
(第二个是更详细,还是这个想法是一样的)。
无论如何,这是很合乎逻辑的,你不能从的app.config在单元测试中使用的信息,作为一个app.config是内容为整个应用程序,当它需要完全独立编写测试。如果你直接使用一个app.config值,那么你必须非逻辑耦合。
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:
- chrisondotnet/2011/05/configurationmanager-wrapper-for-unit-testing/
- weblogs.asp/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.
更多推荐
在执行单元测试ConfigurationManager.GetSection(sectionName)返回null
发布评论