Visual Studio单元测试 - 自定义配置部分

时间:2014-08-20 14:32:52

标签: c# unit-testing mstest

我正在编写一些单元测试,这个单元测试确实使用外部库中的代码,这个库期望配置文件包含一些信息。我知道要在我的UnitTest中使用App.config,我需要用[DeploymentItem("App.config")]标记我的TestMethod,但据我所知,默认情况下会在<appSettings>部分查找配置标记。如何指定我的App.config是否定义了自定义配置部分?

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <section name="MySettingSection" type="System.Configuration.AppSettingsSection" />
  </configSections>

  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
  </startup>

  <MySettingSection>
    <add key="ApplicationName" value="My Test Application" />
  </MySettingSection>

</configuration>

1 个答案:

答案 0 :(得分:1)

  

我知道要在我的UnitTest中使用App.config,我需要标记我的   使用[DeploymentItem(“App.config”)]

的TestMethod

此语句错误:默认情况下部署App.config。在Visual Studio 2012及更高版本中也是如此(我无法在早期版本中确认,因为我的计算机中没有安装任何版本)。

  

如何指定我的App.config是否定义了自定义配置部分?

App.config中添加所需的配置部分声明,它将按预期工作:

<configSections>
    <section name="YourSection" type="Assembly Qualified Path to the class representing your section" />
  </configSections>

查看我很久以前做过的其他旧答案(它应该指导您如何使用配置模型来设置App.config 中附属程序集的配置和设置):

更新

在一些评论中,OP说:

  

通过使用我的例子,如果我在单元测试中写下以下内容   ConfigurationManager.AppSettings [ “应用程序名称”];它只会   返回null。是否有任何属性定义UnitTest的位置   应该照看“ApplicationName”吗?

请注意,自定义声明的System.Configuration.AppSettingsSection配置部分不是<appSettings>访问的默认ConfigurationManager.AppSettings["ApplicationName"]

在您的情况下,您应该以这种方式访问​​该部分:

Configuration config =
              ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

AppSettingsSection appSettings = (AppSettingsSection)config.GetSection("MySettingSection");
string appName = appSettings["ApplicationName"];
相关问题