运行 使用转换后的应用程序设置在构建管道中进行集成测试

Run integration test in build pipeline with transformed appsettings

我在我的解决方案中添加了一个集成测试项目,使用 .NET Core 3.1 和 xUnit。在这个测试项目中,我还添加了一个 appsettings.json 和一个应该在本地使用的连接字符串。

  "ConnectionStrings": {
    "DefaultConnection": "Data Source=(LocalDb)\MSSQLLocalDb;Initial Catalog=MyApp_IntegrationTests;Integrated Security=True"
  }

我还在 Azure DevOps 的构建管道中添加了以下内容:

- task: DotNetCoreCLI@2
  displayName: 'Run integration tests'
  inputs:
    command: test
    projects: '**/*Tests.csproj'
    arguments: '--configuration $(buildConfiguration)'

这失败了,因为 Azure 不支持 LocalDB。这是有道理的,但我不知道如何转换管道中测试项目使用的 appsettings.json 。如果我在 appsettings.json 中放入 Azure 连接字符串并提交它,它会按预期工作。

关于如何解决这个问题有什么建议吗?

您可以通过以下脚本在 Azure DevOps 上启动 LocalDB

- script: sqllocaldb start mssqllocaldb

如果您想在管道中将 LocalDB connectionString 替换为 Azure connectionstring。您可以使用变量替换任务(例如 Magic Chunks 扩展名)来替换 appsettings.json.

中的 connectionString

First you need set a variable(eg. MyConnectionString) in you pipeline to hold the value of Azure connectionstring.

Then you can add Config Transfromation Task before the Dotnet Test Task, and refer to this variable using the syntax $(MyConnectionString) in the Config Transfromation Task to replace the LocalDB connectionString.

您可以查看 this thread 中的示例。

另一种解决方法是使用 self-host agent 构建管道。由于 Azure 代理无法与您的 localDB 通信,您可以在本地计算机上设置一个自托管代理。自托管代理可以访问您的 localDB。

希望以上内容对您有所帮助!