【问题标题】:Visual Studio Unit test - Custom Config SectionVisual Studio 单元测试 - 自定义配置部分
【发布时间】:2014-10-13 23:21:04
【问题描述】:

我正在编写一些单元测试,这个单元测试确实使用外部库中的代码,这个库希望配置文件包含一些信息。我知道要在我的 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>

【问题讨论】:

  • 你使用的是哪个单元测试框架?
  • @Liath 如果 OP 说了一些关于 DeploymentItemAttribute 的话就足以理解 OP 正在谈论 MSTest :D
  • @MatíasFidemraizer 感谢您的澄清 - 只有您使用过 MS 框架才能了解它。
  • @Liath 没问题。无论如何,我已经重新标记了这个问题以避免混淆:)

标签: c# unit-testing mstest


【解决方案1】:

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

这个说法是错误的: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["ApplicationName"];它只会 返回空值。是否有任何属性定义了 UnitTest 应该照顾“ApplicationName”吗?

请注意,您自定义声明的System.Configuration.AppSettingsSection 配置部分不是ConfigurationManager.AppSettings["ApplicationName"] 访问的默认&lt;appSettings&gt;。

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

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

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

【讨论】:

  • 通过使用我的示例,如果我在单元测试ConfigurationManager.AppSettings["ApplicationName"]; 中编写以下内容,它只会返回null。是否有任何Attribute 定义了 UnitTest 应该在哪里处理“ApplicationName”?
  • @TobiasMoeThorstensen 这是预期的行为,不是吗? ConfigurationManager.AppSettings 代表 &lt;appSettings&gt; 配置部分,而不是您的自定义部分。现在我不明白你为什么要声明System.Configuration.AppSettingsSection。只需使用&lt;appSettings&gt;!
  • 我使用自定义 appSection 是有原因的,否则我会使用 appSettings。外部库定义我必须在本节中进行一些设置。我无法将这种东西定义为Attribute 到我的TestMethod ?
  • @TobiasMoeThorstensen 等等,但是您是否尝试在常规 &lt;appSettings&gt; 部分中指定该设置?!?!有很多应用程序需要应用程序设置,但在常规应用程序中!!!
  • @TobiasMoeThorstensen 这似乎是一个非常糟糕的库设计......顺便说一句,你检查我的更新了吗?我觉得你没有尝试过......
猜你喜欢
  • 2014-10-03
  • 2012-11-29
  • 1970-01-01
  • 2010-09-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-10-30
相关资源
最近更新 更多