当前位置:   article > 正文

Object reference not set to an instance of an object_system.nullreferenceexception: object reference no

system.nullreferenceexception: object reference not set to an instance of an

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

  1. <configSections>
  2. <section name="connection" type="System.Configuration.AppSettingsSection, System.Configuration, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"/>
  3. </configSections>
  4. <connection>
  5. <add key="DHP" value="Data Source=WXPFSER12-LAB1;Initial Catalog=PlatformDB;Integrated Security=True" />
  6. </connection>

Reference Code

  1. string strConfigPath = @"D:\Sample\VSTS\Unit Test\Call Class\CallClass\ConsoleApp\App.config";
  2. System.Configuration.ConfigurationFileMap fileMap = new ConfigurationFileMap(strConfigPath); //Path to your config file
  3. System.Configuration.Configuration configuration = System.Configuration.ConfigurationManager.OpenMappedMachineConfiguration(fileMap);
  4. var SettingsSection = configuration.GetSection("connection") as AppSettingsSection;
  5. string connection = SettingsSection.Settings["DHP"].Value;


Reference

ConfigurationProperty is inaccessible due to its protection level

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小小林熬夜学编程/article/detail/563726
推荐阅读