无法在unit testing项目中使用ConfigurationManager
我正在尝试为我的项目编写unit testing,但它不会让我使用配置管理器。 现在我的项目设置像
ASP.Net应用程序(所有aspx页面)
ProjectCore(所有C#文件 – 模型)
ProjectTest(所有测试)
在我的ProjectCore中,我能够从System.Configuration访问ConfigurationManager对象并将信息传递到项目中。 但是,当我运行涉及ConfigurationManager的测试时,我收到错误
System.NullReferenceException: Object reference not set to an instance of an object.
这是测试的一个例子
using System.Configuration; [TestMethod] public void TestDatabaseExists() { //Error when I declare ConfigurationManager Assert.IsNotNull(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString }
在我的其他测试中,ConfigurationManager.ConnectionStrings [“ConnectionString”]。ConnectionString是我将数据适配器的配置字符串设置为,并在测试时返回null错误,但在我实际使用网站时却没有。 有任何想法吗?
这可能是以下几个问题之一:
- 您没有将app.config添加到ProjectTest项目中。
-
您没有在app.config中添加连接字符串。
您正在进行unit testing,在unit testing中,您的注意力应该是尝试测试的特定方法,并且应该删除无关的依赖项。 在这种情况下,尝试mocking / moleing(使用Microsoft Mole和Pex) system.configuration
类; 这肯定会给出一个解决方案。
我在说,一旦在测试项目解决方案中安装了MS moles-and-pex – >,请右键单击系统组件并选择create mole。
这将为您提供一个摩擦版本的配置类,而后者将具有模拟版本的配置类 – 使用它可以绕过您面临的问题。
您还可以使用ExeConfigurationFileMap
特殊配置路径:
// Get the machine.config file. ExeConfigurationFileMap fileMap = new ExeConfigurationFileMap(); // You may want to map to your own exe.config file here. fileMap.ExeConfigFilename = @"C:\test\ConfigurationManager.exe.config"; // You can add here LocalUserConfigFilename, MachineConfigFilename and RoamingUserConfigFilename, too System.Configuration.Configuration config = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None);
它与mstest.exe命令行中的/ noisolation参数有关。 省略/ noisolation参数,它可以工作。