![](/img/trans.png)
[英]How do I get my c# console application to run with an app.config?
[英]How do I get a c# Unit Test to use App.Config?
我已将其简化为最简单的。
VS2019 MSTest 测试项目(.NET Core)模板
默认单元测试项目。
使用 nuget 安装 System.Configuration.ConfigurationManager(5.0.0)
将 app.config 文件添加到项目中(添加 -> 新建项目 -> select 应用程序配置文件>
向配置文件添加条目。
<?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"];
}
}
你如何让单元测试读取配置文件?
您必须告诉配置管理器要加载什么文件。 不要依赖与exe名称匹配的文件等。只需将名称保留为app.config即可。
System.Configuration.ConfigurationFileMap configMap = new ConfigurationFileMap("./app.config");
System.Configuration.Configuration configuration = System.Configuration.ConfigurationManager.OpenMappedMachineConfiguration(configMap);
string value = configuration.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
中给了我正确的值。
我无法解释为什么它会专门针对该文件名,但出于某种原因它确实如此。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.