如何让 ac# 单元测试使用 App.Config?

Bob*_*egg 2 c# unit-testing

我已将其简化为最简单的。

VS2019 MSTest测试项目(.NET Core)模板

默认单元测试项目。

使用nuget安装System.Configuration.ConfigurationManager(5.0.0)

将 app.config 文件添加到项目中(添加 -> 新项目 -> 选择应用程序配置文件>

将条目添加到配置文件。

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
  <add key="TestKey" value="testvalue"/>
</appSettings>
</configuration>
Run Code Online (Sandbox Code Playgroud)

调试下面的代码,k为空。

   using Microsoft.VisualStudio.TestTools.UnitTesting;
   using System.Configuration;

   namespace UnitTestProject1
   {
    [TestClass]
    public class UnitTest1
    {
    [TestMethod]
    public void TestMethod1()
    {
        var k = System.Configuration.ConfigurationManager.AppSettings["TestKey"];

    }
  }
 
Run Code Online (Sandbox Code Playgroud)

如何让单元测试读取配置文件?

Tam*_*Bui 6

如果您将此行添加到您的 TestMethod 中,它将告诉您它期望使用的配置文件的名称是什么:

public void TestMethod1()
{
    string path = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None).FilePath;
    var k = ConfigurationManager.AppSettings["TestKey"];
}
Run Code Online (Sandbox Code Playgroud)

当我运行它时,它调用文件“(path-to)\testhost.dll.config”,而不是“App.config”。所以我所做的就是将文件重命名为“testhost.dll.config”,将其构建操作更改为“内容”和“始终复制”,运行单元测试,它给了我正确的值var k

我无法解释为什么它会专门查找该文件名,但出于某种原因它确实如此。

  • 只是浪费了一个小时,直到我找到你的答案。谢谢。 (2认同)