Code coverage reports help development teams understand how much of their application code is exercised by automated tests. They are commonly generated during unit testing and uploaded to services that display coverage trends, identify untested areas, and help teams monitor code quality.
In a GitHub Actions workflow, generating a coverage report is only one part of the process. The report must also be valid, accessible, and compatible with the upload action or coverage service that consumes it.
Problems often appear when a test process fails halfway through execution, a coverage file is empty, a report is written to an unexpected directory, or multiple test projects generate reports with different formats. In these situations, an upload step may fail even though the actual test results are available.
A more reliable workflow validates coverage files before uploading them. This makes failures easier to understand and prevents invalid reports from creating unnecessary noise in the CI pipeline.
In this article, we will explore how coverage files are generated in GitHub Actions, why invalid reports occur, how to validate them, and how to build a workflow that uploads only usable coverage data.
Understanding Code Coverage Files in GitHub Actions
Code coverage measures which parts of an application are executed while automated tests run.
For example, suppose an application contains 100 executable lines and a test suite executes 75 of them. The line coverage is approximately 75 percent.
Coverage tools can measure different aspects of execution:
Line coverage identifies which executable lines were run.
Branch coverage measures whether different decision paths were executed.
Method coverage measures which methods were called.
Class coverage measures which classes were exercised.
The exact metrics depend on the coverage tool and report format.
In a .NET application, developers commonly use Coverlet to collect coverage information during test execution. The results can then be converted into formats such as Cobertura or OpenCover.
For example, a test command might look like this:
dotnet test \
--collect:"XPlat Code Coverage" \
--results-directory ./TestResultsWhen the test process completes, the coverage collector can produce a file named coverage.cobertura.xml inside a generated results directory.
A simplified directory structure might look like this:
Repository/
|
+-- src/
|
+-- tests/
| +-- UnitTests/
|
+-- TestResults/
+-- a1b2c3d4/
+-- coverage.cobertura.xmlThe generated directory name may vary between test runs. This is one reason why upload steps should not assume that the report always exists at a fixed path.
Why Coverage Files Become Invalid
A coverage report can be missing, incomplete, malformed, or incompatible with the upload tool.
These problems often occur because of differences between local development environments and CI runners.
Tests Fail Before Coverage Collection Completes
If a test process crashes, is terminated, or encounters an environment problem, the coverage collector may not finish writing the report.
For example, an unexpected process termination can leave a partially written XML file.
The file may exist, but it may not contain a complete XML document.
The Report File Is Empty
A workflow may create the expected output directory even when no tests were executed or no coverage data was collected.
The upload step finds the file path but receives an empty file.
An empty report is not equivalent to zero percent coverage. It usually indicates that report generation did not produce usable output.
The Upload Path Is Incorrect
Coverage collectors often generate reports inside temporary directories.
A workflow that expects the report at TestResults/coverage.cobertura.xml may fail when the actual location is TestResults/{guid}/coverage.cobertura.xml.
The upload step may report that no files were found even though a valid report exists elsewhere.
Different Tools Generate Different Formats
Coverage tools do not all use the same report format.
Common formats include:
Format | Typical use |
|---|---|
Cobertura XML | Coverage visualization and reporting |
OpenCover XML | .NET coverage analysis |
LCOV | JavaScript, TypeScript, and other ecosystems |
JaCoCo XML | Java coverage reporting |
Clover XML | Coverage reporting for several languages |
A report can be valid XML but still be rejected by a service that expects a different coverage schema.
File extension alone does not guarantee format compatibility.
Multiple Test Projects Generate Multiple Reports
A solution may contain several test projects:
tests/
|
+-- UnitTests/
+-- IntegrationTests/
+-- ServiceTests/Each project may generate its own report.
If the workflow uploads only one report, the resulting coverage information may be incomplete. If the reports are merged incorrectly, the final file may become invalid.
For this reason, report generation and validation should be treated as separate stages.
Generating Coverage Reports With Coverlet
Let's use a .NET solution as an example.
First, install the required coverage collector in each test project:
dotnet add package coverlet.collectorNext, execute the tests with the XPlat Code Coverage collector:
dotnet test \
--collect:"XPlat Code Coverage" \
--results-directory ./TestResultsThe command runs the tests and asks the collector to generate coverage information.
To produce a Cobertura report, configure the collector's supported output format.
For example, a test runsettings file can contain:
<?xml version="1.0" encoding="utf-8"?>
<RunSettings>
<DataCollectionRunSettings>
<DataCollectors>
<DataCollector friendlyName="XPlat Code Coverage">
<Configuration>
<Format>cobertura</Format>
</Configuration>
</DataCollector>
</DataCollectors>
</DataCollectionRunSettings>
</RunSettings>Save this file as coverage.runsettings and execute:
dotnet test \
--settings coverage.runsettings \
--collect:"XPlat Code Coverage" \
--results-directory ./TestResultsThe collector generates coverage data in the configured format.
If the solution contains multiple test projects, decide whether to collect separate reports or merge them into a single report using an appropriate reporting tool.
Do not assume that every test project writes to the same directory. Inspect the generated files before configuring the upload step.
Validating Coverage Files Before Upload
The validation stage should confirm that the report exists, is not empty, contains valid XML, and has the expected coverage structure.
For a Cobertura report, checking the XML structure is more useful than checking only the filename.
A valid Cobertura report typically contains a coverage root element with attributes such as line-rate and branch-rate.
A simplified example looks like this:
<?xml version="1.0" encoding="utf-8"?>
<coverage
line-rate="0.75"
branch-rate="0.60"
version="1.9"
timestamp="1234567890">
<packages>
<package name="ExampleApp">
<classes>
<class
name="ExampleApp.Services.OrderService"
filename="OrderService.cs"
line-rate="0.80"
branch-rate="0.50">
<lines>
<line number="10" hits="1"/>
<line number="11" hits="0"/>
</lines>
</class>
</classes>
</package>
</packages>
</coverage>The following Python script checks whether a report exists, has content, contains valid XML, and uses the expected root element.
import sys
import xml.etree.ElementTree as ET
from pathlib import Path
report_path = Path(sys.argv[1])
if not report_path.exists():
print(f"Coverage report not found: {report_path}")
sys.exit(1)
if report_path.stat().st_size == 0:
print("Coverage report is empty.")
sys.exit(1)
try:
tree = ET.parse(report_path)
root = tree.getroot()
except ET.ParseError as error:
print(f"Invalid XML coverage report: {error}")
sys.exit(1)
if root.tag != "coverage":
print(f"Unexpected root element: {root.tag}")
sys.exit(1)
if "line-rate" not in root.attrib:
print("Coverage report does not contain line-rate.")
sys.exit(1)
print("Coverage report is valid.")This validation is intentionally simple. It verifies basic Cobertura structure, but it does not prove that every coverage value is correct or that the report includes all expected source files.
For production workflows, you may also validate numeric values, expected package information, and whether the report contains meaningful coverage records.
A valid report with no executable lines may still be technically valid, but it may indicate that the wrong assemblies or source files were included.
Finding Reports in Generated Directories
A common GitHub Actions problem is using an incorrect report path.
Instead of assuming a fixed directory, use a file search to locate generated reports.
For example:
find ./TestResults \
-type f \
-name "coverage.cobertura.xml"This command searches all subdirectories and displays matching files.
If you expect exactly one report, verify that only one matching file exists.
If multiple test projects generate reports, collect all of them and decide whether the upload service accepts multiple files or requires a merged report.
For example, a shell script can fail when no report is found:
REPORTS=$(find ./TestResults \
-type f \
-name "coverage.cobertura.xml")
if [ -z "$REPORTS" ]; then
echo "No coverage reports were generated."
exit 1
fi
echo "Found coverage reports:"
echo "$REPORTS"This is safer than passing a wildcard to an upload action without confirming that matching files exist.
Building a GitHub Actions Workflow
Now let's create a workflow that runs tests, generates coverage reports, validates them, and uploads only valid files.
The following example uses a .NET test project and Python for basic Cobertura XML validation.
name: Test and Coverage
on:
push:
branches:
- main
pull_request:
jobs:
test:
runs-on: ubuntu-latest
steps:
- name: Checkout source
uses: actions/checkout@v4
- name: Setup .NET
uses: actions/setup-dotnet@v4
with:
dotnet-version: '10.0.x'
- name: Restore dependencies
run: dotnet restore
- name: Build solution
run: dotnet build --no-restore
- name: Run tests with coverage
run: |
dotnet test \
--no-build \
--settings coverage.runsettings \
--collect:"XPlat Code Coverage" \
--results-directory ./TestResults
- name: Find coverage reports
id: coverage
shell: bash
run: |
mapfile -t reports < <(
find ./TestResults \
-type f \
-name "coverage.cobertura.xml"
)
if [ "${#reports[@]}" -eq 0 ]; then
echo "No coverage reports were generated."
exit 1
fi
printf '%s\n' "${reports[@]}" \
> coverage-files.txt
echo "Found ${#reports[@]} coverage report(s)."
- name: Validate coverage reports
run: |
while IFS= read -r report; do
python3 scripts/validate_coverage.py "$report"
done < coverage-files.txt
- name: Upload coverage artifacts
uses: actions/upload-artifact@v4
with:
name: coverage-reports
path: |
coverage-files.txt
TestResults/**/coverage.cobertura.xml
if-no-files-found: errorThis workflow separates test execution from report validation and artifact upload.
The test step generates the coverage reports. The discovery step finds the actual files instead of assuming a fixed directory. The validation step checks each report before the upload step runs.
The final step uses GitHub's artifact upload action to preserve the reports for later inspection or use by another workflow job.
This example uploads reports as GitHub Actions artifacts. It does not send them to an external coverage service. If you use a coverage service, add its upload action or command after validation and configure the expected report format.
The action versions and .NET SDK version should be aligned with the versions supported by your repository and workflow.
Deciding Whether an Invalid Report Should Fail the Workflow
Not every coverage problem should have the same result.
Consider two different situations.
The first is when unit tests fail. In this case, the workflow should normally fail because the application has not passed its test suite.
The second is when tests pass but the coverage report is missing or invalid. The correct response depends on how important coverage reporting is to the team's quality process.
For a project where coverage is a required quality gate, an invalid report should fail the workflow. Otherwise, the team could unknowingly merge changes without reliable coverage information.
For a project where coverage reporting is optional, the workflow may continue while recording a warning and skipping the upload.
You can implement this distinction with an explicit workflow setting or a separate validation policy.
Avoid automatically treating a missing report as zero coverage. A missing report indicates that coverage data is unavailable, not that every line of the application is untested.
Handling Multiple Coverage Reports
Large solutions often contain multiple test projects. Each project may produce its own coverage report.
For example:
TestResults/
|
+-- UnitTests/
| +-- coverage.cobertura.xml
|
+-- IntegrationTests/
| +-- coverage.cobertura.xml
|
+-- ServiceTests/
+-- coverage.cobertura.xmlUploading all reports may be sufficient if the coverage service supports multiple report files.
If the service expects one combined report, use a coverage report generator that understands the source format.
For .NET projects, ReportGenerator is commonly used to convert and combine coverage reports.
For example:
dotnet tool install --global dotnet-reportgenerator-globaltoolThen generate a combined report:
reportgenerator \
"-reports:TestResults/**/coverage.cobertura.xml" \
"-targetdir:CoverageReport" \
"-reporttypes:Cobertura"The resulting report can be validated using the same XML validation process.
Be careful when merging reports from different test runs. Make sure they belong to the same source revision and use compatible source paths. Combining unrelated reports can produce misleading coverage results.
Troubleshooting Common Coverage Upload Problems
When a coverage upload fails, start by checking the actual generated files rather than immediately changing the upload action.
Problem | Likely cause | Recommended check |
|---|---|---|
No report found | Incorrect output path | Search generated directories |
Empty XML file | Interrupted collection or no usable data | Check test and collector logs |
XML parsing error | Incomplete or malformed report | Validate the original file |
Unsupported format | Wrong coverage output format | Confirm the upload service requirements |
Incomplete coverage | Some test projects were skipped | Inspect test execution and report discovery |
Duplicate coverage entries | Reports merged incorrectly | Check source paths and merge configuration |
Upload permission failure | Incorrect token permissions | Review workflow permissions |
It is also useful to preserve coverage reports as artifacts when a workflow fails. This allows developers to inspect generated files without rerunning the entire pipeline.
However, avoid uploading reports containing sensitive source paths or other information that should not be exposed to users who can access the workflow artifacts.
Best Practices for Reliable Coverage Pipelines
A reliable coverage pipeline should treat report generation, validation, and uploading as separate responsibilities.
Use the following practices:
Generate coverage reports in a predictable output area.
Discover files instead of assuming temporary directory names.
Validate file size and XML structure before uploading.
Confirm that the report format matches the destination service.
Handle multiple test projects explicitly.
Keep test failures separate from coverage-report failures.
Preserve reports as artifacts when useful for troubleshooting.
Use pinned action versions and review action updates.
Avoid treating missing reports as zero coverage.
Monitor coverage trends rather than relying on one build result.
Also remember that code coverage is a measurement of execution, not a direct measurement of test quality. A high coverage percentage does not guarantee that the tests verify the correct behavior.
Use coverage reports to identify areas that need attention, but review assertions, edge cases, and business requirements when evaluating the quality of a test suite.
Summary
Invalid code coverage files can make GitHub Actions workflows unreliable even when the underlying tests execute successfully. Missing reports, empty files, malformed XML, incorrect paths, and unsupported formats are common reasons why coverage uploads fail.
A better workflow validates reports before uploading them. For .NET applications, Coverlet can generate coverage data, while a small validation script can check whether Cobertura XML files are present and structurally valid.
GitHub Actions can then upload only reports that pass validation. For larger solutions, report discovery and merging should be handled carefully so that the final coverage data represents the intended test projects.
Separating test execution, report generation, validation, and uploading makes CI failures easier to diagnose. It also helps teams maintain dependable coverage reporting without confusing an invalid report with a genuine test failure.

Join the conversation! Your thoughts help the community grow.