This page shows a PowerShell script that runs .NET unit tests under JetBrains dotCover, writes DetailedXML coverage files, and uses ReportGenerator to convert them to Cobertura and HTML for the Azure DevOps Publish Code Coverage Results task. Below the script you'll find an explanation of how it works, fixes for several bugs that stop it from running as a file-based pipeline script, a corrected version, and a complete pipeline example.
Script generating a code coverage report with dotCover and later converting it with Report Generator so that Azure DevOps task Publish Code Coverage Results can use it.
How the script works
Azure DevOps cannot read dotCover's native report formats directly. The Publish Code Coverage Results task expects Cobertura (or JaCoCo) XML. The script above therefore runs in two stages. First, dotCover wraps the test runner and records coverage. Then ReportGenerator converts the output into a format the pipeline understands.
| Stage | Tool | Output |
|---|---|---|
| Find test projects | Get-ChildItem with *Tests.csproj | List of test project files |
| Run tests with coverage | dotCover.exe cover wrapping dotnet test or vstest.console.exe | <Project>_coverage.xml in DetailedXML format |
| Convert to Cobertura | ReportGenerator -reporttypes:Cobertura | coverage-report/cobertura/Cobertura.xml |
| Build HTML report | ReportGenerator -reporttypes:HtmlInline_AzurePipelines | coverage-report/html/index.html |
| Publish | PublishCodeCoverageResults task | Code Coverage tab on the pipeline run |
Prerequisites on the build agent
- A Windows agent. The script uses Windows paths and
dotCover.exe. - dotCover command-line tools. You can install them from the JetBrains download page or restore the
JetBrains.dotCover.CommandLineToolsNuGet package, which putsdotCover.exein itstoolsfolder. - .NET SDK if you use
dotnet test. If you usevstest.console.exeinstead, you need Visual Studio or Build Tools with the test platform installed. - ReportGenerator, installed as a .NET tool. Install it under the account the agent runs as, because global tools go into that user's profile. The original path
C:\Windows\ServiceProfiles\NetworkService\.dotnet\toolsonly applies when the agent service runs as Network Service. - Test projects that build successfully in the configuration you pass (for example
Release).
# Install ReportGenerator for the current user (run as the agent account)
dotnet tool install --global dotnet-reportgenerator-globaltool
# Or install it into a folder you control, which is better for build agents
dotnet tool install dotnet-reportgenerator-globaltool --tool-path C:\tools\reportgenerator
# Locate vstest.console.exe instead of hardcoding a Visual Studio 2017 path
& "${env:ProgramFiles(x86)}\Microsoft Visual Studio\Installer\vswhere.exe" -latest -products * -find "**\TestPlatform\vstest.console.exe"Code language: PHP (php)
Problems in the original script
- Azure DevOps macro syntax inside PowerShell.
$(System.DefaultWorkingDirectory)and$(BuildConfiguration)are only replaced when the script is pasted into an *inline* task. In a.ps1file, PowerShell reads$( ... )as a subexpression and tries to run a command calledSystem.DefaultWorkingDirectory, which fails. Use the environment variables$env:SYSTEM_DEFAULTWORKINGDIRECTORYand$env:BUILDCONFIGURATIONinstead. - Both runners execute by default. If you don't comment one region out, every test project runs twice, and the vstest run overwrites the
dotnet testcoverage file. - Failed tests are not detected.
$?only reflects the last command. Without/ReturnTargetExitCode, dotCover also returns its own exit code, not the test runner's. A failing test can therefore leave the pipeline green. - Stray space in
-reports: $reportsFilePaths. In the Cobertura call, the value is passed with a leading space. Write it as-reports:<paths>, as the HTML call already does. - Missing comma after
"/Filters=$dotCoverAssemblyFilter"in the dotnet argument array. It happens to work, because a newline also separates elements inside@( ), but it's inconsistent and easy to break when editing. - Hardcoded Visual Studio 2017 Build Tools path. That path is outdated on most current agents. Locate the runner with
vswhereinstead. - Comment typos. The comments say "apropriate", "scrip" and "haven't passed".
Corrected script
This version keeps the dotnet test path only, since that's the common case for SDK-style projects. It reads pipeline values from environment variables and runs every test project. It still generates the reports when tests fail, then fails the step at the end. Save it in the repository, for example as build/coverage.ps1.
param(
[string]$DotCoverExecutable = 'C:\Program Files\DotCover\dotCover.exe',
[string]$ReportGeneratorExecutable = "$env:USERPROFILE\.dotnet\tools\reportgenerator.exe",
[string]$TestProjectPattern = '*Tests.csproj',
[string]$AssemblyFilter = '+:module=MyApplication*;-:module=*Tests',
[string]$WorkingDirectory = $env:SYSTEM_DEFAULTWORKINGDIRECTORY,
[string]$Configuration = $env:BUILDCONFIGURATION
)
$ErrorActionPreference = 'Stop'
if (-not $WorkingDirectory) { $WorkingDirectory = (Get-Location).Path }
if (-not $Configuration) { $Configuration = 'Release' }
foreach ($exe in $DotCoverExecutable, $ReportGeneratorExecutable) {
if (-not (Test-Path -Path $exe)) { throw "Executable not found: $exe" }
}
$dotnetExecutable = (Get-Command dotnet).Source
# Clean output structure: coverage-report\cobertura and coverage-report\html
$reportDirectory = Join-Path $WorkingDirectory 'coverage-report'
$coberturaDir = Join-Path $reportDirectory 'cobertura'
$htmlDir = Join-Path $reportDirectory 'html'
if (Test-Path $reportDirectory) { Remove-Item $reportDirectory -Recurse -Force }
New-Item -ItemType Directory -Path $coberturaDir, $htmlDir -Force | Out-Null
$testProjects = Get-ChildItem -Path $WorkingDirectory -Filter $TestProjectPattern -Recurse -File
if (-not $testProjects) { throw "No files matched $TestProjectPattern." }
$failedProjects = @()
foreach ($project in $testProjects) {
$output = Join-Path $reportDirectory "$($project.BaseName)_coverage.xml"
$dotCoverArgs = @(
'cover',
"/TargetExecutable=$dotnetExecutable",
"/TargetWorkingDir=$($project.DirectoryName)",
"/TargetArguments=test --configuration $Configuration",
"/Output=$output",
'/ReportType=DetailedXML',
"/Filters=$AssemblyFilter",
'/ReturnTargetExitCode'
)
Write-Output "Running dotCover for $($project.Name)"
& $DotCoverExecutable @dotCoverArgs
if ($LASTEXITCODE -ne 0) { $failedProjects += $project.Name }
}
$reports = (Get-ChildItem -Path $reportDirectory -Filter '*_coverage.xml' -File).FullName
if (-not $reports) { throw 'No coverage reports were generated.' }
$reportList = $reports -join ';'
& $ReportGeneratorExecutable "-reports:$reportList" "-targetdir:$coberturaDir" '-reporttypes:Cobertura'
if ($LASTEXITCODE -ne 0) { throw 'ReportGenerator (Cobertura) failed.' }
& $ReportGeneratorExecutable "-reports:$reportList" "-targetdir:$htmlDir" '-reporttypes:HtmlInline_AzurePipelines'
if ($LASTEXITCODE -ne 0) { throw 'ReportGenerator (HTML) failed.' }
if ($failedProjects) { throw "Tests failed in: $($failedProjects -join ', ')" }Code language: PHP (php)
/TargetWorkingDirrunsdotnet testfrom the project folder. You don't need to pass a quoted project path, which avoids argument-quoting problems with paths that contain spaces./ReturnTargetExitCodemakes dotCover return the exit code ofdotnet test, so$LASTEXITCODEtells you whether the tests failed.- The filter includes your application modules and excludes the test assemblies, so test code doesn't inflate the coverage percentage.
- Every parameter can be overridden, which lets you run the script on a developer machine:
./build/coverage.ps1 -WorkingDirectory C:\src\MyApp -Configuration Debug.
Note: Recent dotCover releases have reworked parts of the console runner's syntax and options. If an option is rejected, run dotCover.exe help cover on the agent and check which options your installed version supports.
Using vstest.console instead of dotnet test
Older .NET Framework test projects sometimes have to run through vstest.console.exe. In that case, build the solution first, find the compiled test DLL, and replace the argument array in the loop with the one below. As in the dotnet version, setting the working directory avoids quoting the DLL path.
$vsTest = & "${env:ProgramFiles(x86)}\Microsoft Visual Studio\Installer\vswhere.exe" -latest -products * -find "**\TestPlatform\vstest.console.exe" | Select-Object -First 1
$testDll = Get-ChildItem -Path (Join-Path $project.DirectoryName "bin\$Configuration") -Filter "$($project.BaseName).dll" -Recurse -File | Select-Object -First 1
if (-not $testDll) { throw "Build $($project.Name) before running coverage." }
$dotCoverArgs = @(
'cover',
"/TargetExecutable=$vsTest",
"/TargetWorkingDir=$($testDll.DirectoryName)",
"/TargetArguments=$($testDll.Name)",
"/Output=$output",
'/ReportType=DetailedXML',
"/Filters=$AssemblyFilter",
'/ReturnTargetExitCode'
)Code language: PHP (php)
Wiring it into Azure Pipelines
Azure Pipelines exposes non-secret pipeline variables as environment variables. The name is uppercased and dots become underscores, so BuildConfiguration arrives as BUILDCONFIGURATION and System.DefaultWorkingDirectory as SYSTEM_DEFAULTWORKINGDIRECTORY. That's why the corrected script needs no macro syntax.
pool:
vmImage: windows-latest # or a self-hosted Windows pool with dotCover installed
variables:
BuildConfiguration: Release
steps:
- task: PowerShell@2
displayName: Run tests with dotCover
inputs:
filePath: build/coverage.ps1
arguments: -DotCoverExecutable "C:\tools\dotcover\dotCover.exe" -ReportGeneratorExecutable "C:\tools\reportgenerator\reportgenerator.exe"
- task: PublishCodeCoverageResults@2
displayName: Publish coverage
condition: succeededOrFailed()
inputs:
summaryFileLocation: $(System.DefaultWorkingDirectory)/coverage-report/cobertura/Cobertura.xml
- task: PublishPipelineArtifact@1
displayName: Keep HTML report
condition: succeededOrFailed()
inputs:
targetPath: $(System.DefaultWorkingDirectory)/coverage-report/html
artifact: coverage-htmlCode language: CSS (css)
Version 2 of the Publish Code Coverage Results task builds its own HTML view from the summary file. That makes the HtmlInline_AzurePipelines output optional. Keep it as an artifact, or drop that ReportGenerator call. Version 1 of the task is deprecated. It used codeCoverageTool: Cobertura and reportDirectory inputs, and the original script's HTML folder was designed for it.
Note: On Microsoft-hosted agents, dotCover is not preinstalled. Restore it in an earlier step, for example from the NuGet package, and pass the resulting path through -DotCoverExecutable.
Common errors and fixes
| Symptom | Cause | Fix |
|---|---|---|
The term 'System.DefaultWorkingDirectory' is not recognized | Macro syntax used in a .ps1 file | Use $env:SYSTEM_DEFAULTWORKINGDIRECTORY |
| Pipeline passes although tests fail | dotCover exit code returned instead of the test runner's | Add /ReturnTargetExitCode and check $LASTEXITCODE |
| Coverage is 0% or the report is empty | Filter matches no modules, or only test assemblies | Check module names against the bin output and adjust +:module= masks |
| ReportGenerator cannot find report files | Space after -reports: or a wrong path | Pass -reports:path1;path2 with no space |
| Tests run twice and coverage looks wrong | Both the dotnet and vstest regions are enabled | Keep only one runner block |
| Profiler errors when the agent runs as a service account | Bitness mismatch between dotCover and the test process | Set the core instruction set option (x64 or x86) to match the test process, as the original comment suggests |
| Publish task reports no coverage data | summaryFileLocation points to the wrong file | Point it at coverage-report/cobertura/Cobertura.xml |
Best practices
- Pass tool paths as parameters or pipeline variables instead of editing the script on each agent.
- Exclude test assemblies, generated code and migrations with filters, so the percentage reflects production code.
- Publish coverage with
condition: succeededOrFailed(), so you still see coverage when a test breaks. - Keep coverage generation separate from quality gates. Feed the Cobertura file into tools such as SonarQube when you want thresholds enforced.
- Pin tool versions on self-hosted agents and update them deliberately, because console options can change between releases.
Frequently asked questions
Can Azure DevOps read dotCover reports directly?
No. The Publish Code Coverage Results task reads Cobertura or JaCoCo files, so dotCover's DetailedXML output has to be converted first, which is what ReportGenerator does in this script.
Why does my script fail with System.DefaultWorkingDirectory is not recognized?
The $(Variable) syntax is only replaced by Azure DevOps in inline scripts. In a script file, PowerShell treats it as a subexpression, so read the value from $env:SYSTEM_DEFAULTWORKINGDIRECTORY instead.
How do I make the build fail when unit tests fail under dotCover?
Add /ReturnTargetExitCode to the dotCover arguments so it returns the test runner's exit code. Then check $LASTEXITCODE after each run and throw if it isn't zero.
Do I still need the HtmlInline_AzurePipelines report?
Not with PublishCodeCoverageResults@2, which builds its own HTML view from the Cobertura summary. You can keep the ReportGenerator HTML as a pipeline artifact if you prefer its layout.
Can I use Coverlet instead of dotCover?
Yes. For SDK-style projects, dotnet test --collect "XPlat Code Coverage" produces Cobertura directly, with no extra conversion. dotCover is mainly useful when your team already relies on JetBrains tooling or its filtering options.
Related tutorials
- More Code Quality & Analysis tutorials
- SonarQube Masterclass: 2-Day Hands-on Training for Developers, DevOps & Administrators
- Top 10 Static Code Analysis Tools in 2026: Features, Pros, Cons & Comparison
I’m Rajesh Kumar, a DevOps, SRE, DevSecOps, Cloud, and Platform Engineering expert passionate about sharing practical knowledge, real-world experiences, and industry best practices. I have worked at Cotocus and regularly write about technology, travel, investing, health, product reviews, and digital marketing through my various platforms.
I publish technical articles at DevOps School, travel stories at Holiday Landmark, stock market insights at Stocks Mantra, health and fitness guidance at My Medic Plus, product reviews at TrueReviewNow, and SEO and digital marketing strategies at Wizbrand.
Find Trusted Cardiac Hospitals
Compare heart hospitals by city and services โ all in one place.
Explore Hospitals