环境:
我目前在我的解决方案中有三个项目:
我的测试项目中的依赖项都来自NuGet:
问题:
.NET标准库依赖于使用它的任何应用程序中存在的app.config文件。它使用ConfigurationSection和ConfigurationElement属性将值映射到类,非常类似于这个答案:A custom config section with nested collections
.NET Core控制台应用程序中有一个app.config文件,并且该库能够很好地解析它的值并使用它们。好极了。
另一方面,NUnit控制台应用程序中包含相同的app.config文件,但是库似乎无法看到它。一旦它尝试使用ConfigurationManager.GetSection("...")
读取值,它就会返回null
。
有没有人得到一个app.config文件在这样的环境中使用NUnit3?
我试过的:
它看起来像it supports config files,但我不确定文档是指某些特殊的NUnit配置文件还是app.config文件。
我在目前为止编写的一个测试中尝试了一些内容,尝试以某种方式设置配置文件,例如建议使用AppDomain.CurrentDomain.SetData()
(不起作用,可能是因为NUnit3不支持AppDomain):
AppDomain.CurrentDomain.SetData("APP_CONFIG_FILE", @"C:\Path\To\My\Tests\my_test_project_name.dll.config");
虽然NUnit仓库中的测试似乎暗示using a configuration file in NUnit3 is possible,但该特定测试文件仅在.NET 4.5 demo project中引用,而不是.NET Core demo project。
在单元测试中执行以下行并检查其结果时,您可能会注意到NUnit项目正在查找名为testhost.dll.config
的配置文件。
ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None).FilePath;
路径缩短:
ClassLibrary1\NUnitTestProject1\bin\Debug\netcoreapp2.2\testhost.dll.config
因此,我创建了一个如何使用ASP.NET Core 2.2和NUnit Test Project模板配置文件的示例。此外,请确保配置文件的“复制到输出目录”设置设置为Copy always
。
UnitTest.cs
public class UnitTest
{
private readonly string _configValue = ConfigurationManager.AppSettings["test"];
[Test]
public void Test()
{
Assert.AreEqual("testValue", _configValue);
}
}
testhost.dll.config
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="test" value="testValue" />
</appSettings>
</configuration>
当我在App.config
测试项目中使用NUnit
文件时,我遇到了同样的问题,我将App.config
重命名为testhost.dll.config
,然后开始读取配置文件值。