Retrieving Unit Test Metrics from Jenkins via JSON API
This article explains how to define, fetch, and process unit test metrics such as failCount, skipCount, and totalCount from Jenkins build logs using the Jenkins JSON API and a Groovy Jenkinsfile script.
When needing unit test data, the first thought is to extract it from Jenkins build logs, but using the Jenkins JSON API provides a more reliable method. The key metrics are testFailCount , testSkipCount , and testTotalCount , representing failed, skipped, and total test cases respectively.
The API endpoint to retrieve these metrics is ${JOB_URL}${BUILD_ID}/api/json?pretty=true . A typical JSON response contains a hudson.tasks.junit.TestResultAction object with fields failCount , skipCount , and totalCount .
Below is a Jenkinsfile example that requests the JSON API, parses the response with readJSON , iterates over the actions array to locate the TestResultAction class, and extracts the three metrics. The script then prints the values.
node("xxxxx"){
def testsFailCount = "0"
def testSkipCount = "0"
def testTotalCount = "0"
response = httpRequest ignoreSslErrors: true, url: "${JOB_URL}${BUILD_ID}/api/json?pretty=true"
response = response.content
def info = readJSON text: "${response}"
for (cls in info["actions"]) {
if (cls.get("_class")) {
if (cls["_class"] == "hudson.tasks.junit.TestResultAction") {
println(cls)
testsFailCount = cls["failCount"]
testSkipCount = cls["skipCount"]
testTotalCount = cls["totalCount"]
}
}
}
println([testsFailCount, testSkipCount, testTotalCount])
}This approach allows automated collection of unit test metrics for each Jenkins build, enabling further analysis or integration with dashboards such as SonarQube.
DevOps Cloud Academy
Exploring industry DevOps practices and technical expertise.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.