我有一个C#单元测试项目,app.config
文件中有应用程序设置。我正在测试存在于其他项目中的类。该类取决于ConfigurationManager.AppSettings
和ConfigurationManager.ConnectionStrings
。
被测试的类所在的项目没有app.config文件。我以为是因为该类是在单元测试项目的上下文中实例化的,所以它将使用单元测试项目的app.config文件。确实,连接字符串似乎确实是这种情况。
该类检索连接字符串,没有任何问题。但是,当类尝试检索任何应用程序设置时,配置管理器始终返回null
。这里发生了什么?
编辑1
我认为尝试在测试项目中加载一些设置以查看会发生什么是一个好主意。在调用在外部项目中实例化该类的代码之前,我试图立即在单元测试中加载设置。结果相同,一无所有。我想暂时可以将其他项目排除在等式之外。
这是我的配置文件的摘录:
<configSections>
<sectionGroup name="applicationSettings"
type="System.Configuration.ApplicationSettingsGroup, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" >
<section name="MyNamespace.Properties.Settings"
type="System.Configuration.ClientSettingsSection, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
requirePermission="false" />
</sectionGroup>
</configSections>
...
<applicationSettings>
<MyNamespace.Properties.Settings>
<setting name="Bing_Key"
serializeAs="String">
<value>...</value>
</setting>
</MyNamespace.Properties.Settings>
</applicationSettings>
这是我尝试加载设置的方式:
string test = System.Configuration.ConfigurationManager.AppSettings["Bing_Key"];
您提到了项目属性中的设置。查看您是否可以通过这种方式访问设置:
string test = Properties.Settings.Default.Bing_Key;
您可能需要获取定义项目设置文件所在位置的执行程序集,但请首先尝试。
编辑
使用Visual Studio的项目设置文件时,它会将内容添加到app.config中并创建app.config(如果不存在)。ConfigurationManager无法触摸这些设置!您只能使用上述静态方法访问这些特定的生成的project.settings文件。如果要使用ConfigurationManager,则需要手写app.config。像这样添加您的设置:
<appSettings>
<add key="bing_api" value="whatever"/>
</appSettings>
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句