代码之家  ›  专栏  ›  技术社区  ›  jeroenh

单元测试程序集的app.config:如何使appsettings的“file”属性工作?

  •  6
  • jeroenh  · 技术社区  · 15 年前

    我需要在单元测试中从appsettings部分(在app.config中定义)读取设置。我们在这个项目中使用MSTEST。

    假设这是app.config:

    <configuration>
     <appSettings>
       <add key="MyAppSetting" value="MyAppSettingValue"/>
     </appSettings>
    </configuration>
    

    下面是相应的测试,通过此设置:

    [TestClass]
    public class ConfigurationTests
    {
        [TestMethod]
        public void can_read_appsettings()
        {
          string value = ConfigurationManager.AppSettings.Get("MyAppSetting");
          Assert.AreEqual("MyAppSettingValue", value);
        }
    }
    

    现在,当我尝试将appsettings节移动到custom.config文件时,此测试失败。

    这就是我的app.config文件现在的样子:

    <configuration>
     <appSettings file='Custom.config' />
    </configuration>
    

    我将custom.config文件添加到我的项目中(使用生成操作“始终复制”):

     <appSettings>
       <add key="MyAppSetting" value="MyAppSettingValue"/>
     </appSettings>
    

    在控制台应用程序中执行相同操作时,这是有效的。有没有一种方法可以在单元测试组装中实现这一点?

    1 回复  |  直到 15 年前
        1
  •  8
  •   jeroenh    15 年前

    我找到了答案。使用mstest,我需要将“custom.config”文件标记为“localtestrun.testrunconfig”文件中的部署项。