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

本文关键字:配置部 自定义 Studio 单元测试 Visual | 更新日期: 2023-09-27 18:18:47

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

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

我知道要在UnitTest中使用App.config,我需要标记我的TestMethod with [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 中的卫星组件的配置和设置):

    类库可以有一个App.config文件吗?

更新

在一些评论中,OP说:

通过使用我的示例,如果我在单元测试中编写以下代码ConfigurationManager.AppSettings("ApplicationName");它只会返回null。是否有任何属性定义了UnitTest的位置应该照看"ApplicationName"吗?

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

在你的例子中,你应该这样访问这个部分:

Configuration config =
              ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
AppSettingsSection appSettings = (AppSettingsSection)config.GetSection("MySettingSection");
string appName = appSettings["ApplicationName"];