如何配置 Xunit dotnet 核心项目以从不同配置(Dev、Test、Staging)进行初始化

Vik*_*kas 5 xunit .net-core

我有一个 REST api,我想使用 dotnet core 2.0 进行集成测试(而不是单元测试)。

目的是能够在本地运行这些集成测试,指向本地开发环境,并使用我计划从 Teamcity 参数传递的给定测试环境。

我发现这篇文章描述了如何在 ASP.NET core 中使用配置。我正在为 xunit 项目寻找类似的东西。

在 .NET 框架世界中,我通过为环境提供单独的 json 文件来管理此问题,并添加Settings.settings文件来为测试环境添加变量,并在运行测试之前传递环境值。但是,在 dotnet core xunit 2.0 项目中,我没有看到此 Settings.settings 文件选项。有什么建议如何解决这个问题吗?

Adr*_*eer 4

I'm not sure what mechanism/CI/CD pipeline you use for your tests.

That said, you can use environment variables to pass configuration to your xUnit tests. If you use Azure DevOps, for example, environment variables can be supplied via pipeline variables. I've done this successfully with .NET Core 2.1 project in Azure DevOps, so I know this works. I've had issues though with getting this to work in older versions of .NET Core.

For example - in Azure DevOps you would address this as follow

  • Create a Build pipeline variable - e.g. ASPNETCORE_ENVIRONMENT
  • Create Visual Studio Test Task to run your xUnit test
  • In your xUnit project, simply use System.Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT")

All the .NET core configuration classes are available via the Microsoft.Extensions.Configuration Nuget package

As such, although I haven't tried this, you should be able to use these framework classes directly in your test project to configure parameters for your specific test environments - e.g.

new ConfigurationBuilder()
        .SetBasePath(Directory.GetCurrentDirectory())
        .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
        .AddJsonFile($"appsettings.{Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT")}.json", optional: true)
        .AddEnvironmentVariables()
        .Build();
Run Code Online (Sandbox Code Playgroud)

The .AddEnvironmentVariables() shown above can also be used as an alternative to override default values in appsettings.json