在执行单元测试ConfigurationManager.GetSection(sectionName)返回null [英] ConfigurationManager.GetSection(sectionName) returns null while performing unit tests

查看:439
本文介绍了在执行单元测试ConfigurationManager.GetSection(sectionName)返回null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个单元测试项目有它自己的的app.config 文件,该文件是由目标项目定义一个真正的配置文件的模拟正在测试中。这个模拟文件被加载,并通过单元测试code(不是目标项目)处理,它工作正常,如果我只运行在仅这一项测试项目的测试。

  ConfigurationManager.GetSection(sectionName)
 

不过,如果我从几个测试项目,和其他测试项目运行测试前,相关项目执行中,上述语句返回。如果讨论的试验项目作为第一个进行的,没有与加载配置文件没有问题。

如何解决在单元测试中加载配置文件才能正常工作?

解决方案

您的问题不是ConfigurationManager.GetSection(sectionName)返回null,这是我可以测试一些含ConfigurationManager.GetSection(sectionName)code <? / P>

答案是:包装它,它注入,那么你的测试模拟它

您有生民所面临的同一个问​​题的几个例子:

  • <一个href="http://chrisondotnet.com/2011/05/configurationmanager-wrapper-for-unit-testing/">http://chrisondotnet.com/2011/05/configurationmanager-wrapper-for-unit-testing/
  • <一个href="http://weblogs.asp.net/rashid/archive/2009/03/03/unit-testable-configuration-manager.aspx">http://weblogs.asp.net/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:

(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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆