赞
踩
1.Sistuation
当在Unit Testing中使用app.config文件,调用类中的方法可能会出现如下的错误
System.NullReferenceException: Object reference not set to an instance of an object.
这是因为在Unit Testing项目中,虽然引用了要被测试项目类的Dll,但是并没有对app.config文件进行任何引用
Solution:
1. 将被测试项目中的app.config文件copy一份添加到Unit Testing项目中
2. 将被测试项目中的app.config文件的Copy to Output Directory 设置为Copy always
3. 对被测试项目的app.config文件中的节点进行修改并且进行引用,部分代码如下(这种方法同样适用于一个app.config文件被多个项目使用)
App.config
- <configSections>
- <section name="connection" type="System.Configuration.AppSettingsSection, System.Configuration, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"/>
- </configSections>
- <connection>
- <add key="DHP" value="Data Source=WXPFSER12-LAB1;Initial Catalog=PlatformDB;Integrated Security=True" />
- </connection>
Reference Code
- string strConfigPath = @"D:\Sample\VSTS\Unit Test\Call Class\CallClass\ConsoleApp\App.config";
- System.Configuration.ConfigurationFileMap fileMap = new ConfigurationFileMap(strConfigPath); //Path to your config file
- System.Configuration.Configuration configuration = System.Configuration.ConfigurationManager.OpenMappedMachineConfiguration(fileMap);
- var SettingsSection = configuration.GetSection("connection") as AppSettingsSection;
- string connection = SettingsSection.Settings["DHP"].Value;
Reference
ConfigurationProperty is inaccessible due to its protection level
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。