我已将其简化为最简单的。
VS2019 MSTest 测试项目(.NET Core)模板
默认单元测试项目。
使用nuget安装System.Configuration.ConfigurationManager(5.0.0)
将app.config文件添加到项目中(add -> new Item -> select Application Configuration File>
将条目添加到配置文件。
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="TestKey" value="testvalue"/>
</appSettings>
</configuration>
调试下面的代码,k为null。
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"];
}
}
如何让单元测试读取配置文件?
最佳答案
如果您将此行添加到您的 TestMethod,它会告诉您它期望使用的配置文件的名称是什么:
public void TestMethod1()
{
string path = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None).FilePath;
var k = ConfigurationManager.AppSettings["TestKey"];
}
当我运行它时,它调用文件“(path-to)\testhost.dll.config”,而不是“App.config”。所以我所做的就是将文件重命名为“testhost.dll.config”,将其生成操作更改为“内容”和“始终复制”,运行单元测试,它在 var k< 中为我提供了正确的值
.
我无法解释为什么它会专门查找该文件名,但出于某种原因确实如此。
关于c# - 如何获得使用 App.Config 的 c# 单元测试?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65332017/