1
votes

This is a question on how to use a static value for VSTest unit tests run on Azure DevOps Pipeline.

When I develop a unit test that depends on my Web API, I put URL of the Web API hosted on my local dev machine in appsettings.json and this works great. However, when the unit test is run on Azure pipeline, of course it cannot access the Web API hosted on my machine and it fails. I can change the appsettings.json file to point to Web API on Azure but I wish there is a way to always point to the WebAPI on Azure when the unit test is run on the pipeline, overriding the setting in appsettings.json. Is there such a way?

For the Azure pipeline Release, I know I can set variables for app services with Azure App Service Settings task (https://docs.microsoft.com/en-us/azure/devops/pipelines/tasks/deploy/azure-app-service-settings?view=azure-devops). Not sure similar functionality is available for VSTests.

2
Hi Did you get a chance to try out below answer? how did it go?Levi Lu-MSFT

2 Answers

0
votes

You need to have two appsettings files. One for dev (you local test) and the other for production (AzureDevops pipeline).

Like this if you need to make some changes to test locally you change only the dev one.

0
votes

You can use File Transform task to substitute the variables in appsettings.json file with pipeline variables. See here for more information

So you can add a File Transform task before the build task. Then define a variable(eg. TestData.Url) in your pipeline variables. enter image description here

See below yaml example.

- task: FileTransform@1
  displayName: 'File Transform: '
  inputs:
    folderPath: '$(system.defaultworkingdirectory)'
    enableXmlTransform: false
    fileType: json
    targetFiles: '**/appsettings.json'

There are other tasks can do the same work. You can check out task Set Json Property, and task Magic Chunks

You can also put the URL of the Web API in the TestRunParameters section of runsettings file or Properties section of testsettings file. And modify your test code to get the URL from testsettings/runsettings files. Then you can use overrideTestrunParameters attribute of Vstest Task to override the URL. See Vstest task document for more information.