![](/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.