在.NET Core控制台应用程序中使用带有NUnit3的app.config文件

问题描述 投票:7回答:2

环境:

我目前在我的解决方案中有三个项目:

  • 一个.NET Standard 2.0库,包含一些我想测试的代码。
  • 一个.NET Core 2.2控制台应用程序,它引用该库以确保它有效。
  • 使用VS中的“NUnit Test Project”模板创建的.NET Core 2.2控制台应用程序。

我的测试项目中的依赖项都来自NuGet:

  • 我的版本=“h.10.1”
  • nunit“Version =”3.11.0“
  • NUnit.ConsoleRunner“Version =”3.10.0“
  • NUnit3TestAdapter“Version =”3.13.0“
  • Microsoft.NET.Test.Sdk“Version =”16.0.1“

问题:

.NET标准库依赖于使用它的任何应用程序中存在的app.config文件。它使用ConfigurationSectionConfigurationElement属性将值映射到类,非常类似于这个答案: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文件。

  • 我尝试将app.config重命名为my_test_project_name.dll.config
  • 我将配置文件“复制到输出目录”设置为“始终复制”
  • 我尝试了我能想到的每个相似的名字(app.config,App.config,my_test_project_name.config,my_test_project_name.dll.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

c# .net-core nunit app-config nunit-3.0
2个回答
7
投票

在单元测试中执行以下行并检查其结果时,您可能会注意到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>

-1
投票

当我在App.config测试项目中使用NUnit文件时,我遇到了同样的问题,我将App.config重命名为testhost.dll.config,然后开始读取配置文件值。

© www.soinside.com 2019 - 2024. All rights reserved.