SonarQube Code Coverage, Azure DevOps and .NET Core


How do you get SonarQube/SonarCloud code coverage to work with .NET Core and Azure DevOps?



    These steps assume that you are using .NET Core 3.x and that you have already have a Azure DevOps Build Pipeline integrated with SonarQube/SonarCloud. However, you are unable to get the code coverage statistic to work.

    Step One: Make it work in the IDE

    I'm using Xunit to run my unit tests, so I've added the following Nuget packages to my test project. Make sure your tests run successfully in your IDE.
    • Microsoft.NET.Test.Sdk
    • Xunit
    • Xunit.runner.visualStudio

    Step Two: Add the SonarQube Properties

    Add the following two extra properties to your SonarQubePrepare task in your Azure DevOps build pipeline.
    • sonar.cs.vstest.reportsPaths=$(Agent.TempDirectory)\**\*.trx
    • sonar.cs.vscoveragexml.reportsPaths=$(Agent.TempDirectory)\**\*.coveragexml

    If you are using a YAML build pipeline the SonarQubePrepare task should look like the following. I'm using SonarCloud, so I have the SonarCloudPrepare task, however the inputs are the same.

    - task: SonarCloudPrepare@1
      inputs:
        SonarCloud:'SonarCloud'
        organization: 'seanke'
        scannerMode: 'MSBuild'
        projectKey:'seanke_SonarQubeDotNetCoreCodeCoverageExample'
        extraProperties: |
          sonar.cs.vstest.reportsPaths=$(Agent.TempDirectory)\**\*.trx
          sonar.cs.vscoveragexml.reportsPaths=$(Agent.TempDirectory)\**\*.coveragexml

    Step Three: Output Unit Test Code Coverage

    Add the following argument to the DotNetCoreCLI test task in your build pipeline.

    • --collect "Code Coverage"

    The YAML build pipeline task looks like this. This assumes that your test project is appended with test.csproj.

    - task: DotNetCoreCLI@2  
      inputs:
        command: 'test'
        arguments: '--collect "Code Coverage"'
    

    That's it!

    Check out this project for the full working example:

    Comments

    1. I believe this assumes that you're using Windows build agents with Visual Studio Enterprise. When using Coverlet, it can be configured to generate an OpenCover report which SonarQube can consume.

      ReplyDelete

    Post a Comment

    Popular posts from this blog

    Release pipelines: STOP DOING THIS - Use the Deploy Script Pattern instead