【问题标题】:Running an XUnit Integration Test that uses app settings from Visual Studio and from Azure DevOps运行使用来自 Visual Studio 和 Azure DevOps 的应用设置的 XUnit 集成测试
【发布时间】:2021-08-10 15:21:15
【问题描述】:

我有一个集成测试 .NET 5 XUnit 项目。我正在使用 XUnit 2.4 和 XUnit.Runner.VisualStudio 2.4。 本项目中的集成测试需要一个配置值,即 ApiUrl。我想以两种方式运行集成测试:

  1. 从 Visual Studio 使用 All Test Run 或 ReSharper
  2. 从 Azure DevOps 的管道并从管道传递 ApiUrl 将覆盖项目设置中的变量

我的问题:

  • 如何进行配置,让我的测试代码以透明的方式访问 ApiUrl(它不关心它从哪里运行)?
  • 如何将变量 ApiUrl 传递给我的集成测试项目,我使用 DotNetCoreCLI@2 测试任务作为我的管道步骤。

【问题讨论】:

    标签: azure-pipelines xunit .net-5


    【解决方案1】:

    可以通过env: 将环境变量添加到您的任务中,然后您可以在代码中读取:

    - task: DotNetCoreCLI@2
      inputs:
        command: test
        projects: "tests/**/*Tests.csproj"
      env:
        ApiUrl: $(PipelineVariable)
    

    在您的 C# 代码中:

    var apiUrl = Environment.GetEnvironmentVariable("ApiUrl") ?? "http://example.com";
    

    【讨论】:

    • 谢谢,这回答了部分问题。我不想从本地机器上的环境中访问变量,我想通过 appsettings.json 访问它们
    • 在任务的环境变量中设置ApiUrl 将强制该值优先于来自appsettings.json 的值,因为默认情况下配置生成器是通过configBuilder.AddJsonFile('appsettings.json).AddEnvironmentVariables() 设置的
    • 那么,为什么要通过 Environment.GetEnvironmentVariable 而不是 IOption 或 IConfigurationRoot["ApiUrl"] 显式访问变量?
    • 我认为您只需要在 XUnit 中访问该变量,而不是在应用程序本身中。很抱歉!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-07-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多