在执行单元测试ConfigurationManager.GetSection(sectionName)返回null

编程入门 行业动态 更新时间:2024-10-25 18:26:43
本文介绍了在执行单元测试ConfigurationManager.GetSection(sectionName)返回null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个单元测试项目有它自己的的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

本文发布于:2023-11-08 11:39:21,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1569265.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:单元测试   ConfigurationManager   GetSection   sectionName   null

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!