The orders-api and catalog-web tests have run on every build since module 1, but Jenkins only knows one thing about them: whether the command ended well or badly. When a test fails, Diego has to dig through the log until he finds the AssertionFailedError; Marta, from the QA team, has no way of knowing how many tests there are, which ones have been failing for days or whether coverage dropped after the latest change. In this lesson you will make Jenkins understand the results: you will add JaCoCo to the orders-api pom.xml, publish the test reports with the junit step and coverage with the Coverage plugin and its thresholds, separate integration tests with Failsafe, do the same with Jest in catalog-web and learn how to deal with flaky tests without hiding problems. You will also settle an important decision: when a build is unstable (yellow) and when it is failed (red).
What Testing Tools Produce and What Jenkins Does with It
Almost every testing tool can write its results to files in standard formats, and Jenkins has plugins that read them:
| Tool | File it produces | Format | Jenkins step |
|---|---|---|---|
| Maven Surefire (unit tests) | target/surefire-reports/TEST-*.xml |
JUnit XML | junit |
| Maven Failsafe (integration tests) | target/failsafe-reports/TEST-*.xml |
JUnit XML | junit |
| Gradle | build/test-results/test/*.xml |
JUnit XML | junit |
Jest with jest-junit |
reports/junit.xml |
JUnit XML | junit |
| JaCoCo | target/site/jacoco/jacoco.xml |
JaCoCo XML | recordCoverage |
| Jest / Istanbul | coverage/cobertura-coverage.xml |
Cobertura XML | recordCoverage |
The JUnit XML format has become the de facto standard for test results, even when JUnit does not produce it: Java, JavaScript, Python, Go and .NET tools all generate it. Thanks to that, a single Jenkins step works for all of them.
Remember the rule from 04-07: reports are not processed with Groovy in the pipeline, because that would run on the controller. The junit and recordCoverage steps are made for the job.
Coverage in orders-api: JaCoCo in the pom.xml
Coverage measures which part of the code runs during the tests. It does not tell you whether the tests are good, but an area without coverage is, for certain, an untested area. JaCoCo is the standard tool in Java: it instruments the code while the tests run and generates a report.
Edit the orders-api pom.xml (on a branch, as always). Add a property and two plugins in <build>:
<properties>
<java.version>21</java.version>
<jacoco.version>0.8.13</jacoco.version>
</properties>
<!-- ... dependencies unchanged ... -->
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.jacoco</groupId>
<artifactId>jacoco-maven-plugin</artifactId>
<version>${jacoco.version}</version>
<executions>
<execution>
<id>prepare-agent</id>
<goals>
<goal>prepare-agent</goal>
</goals>
</execution>
<execution>
<id>report</id>
<phase>test</phase>
<goals>
<goal>report</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-failsafe-plugin</artifactId>
<executions>
<execution>
<goals>
<goal>integration-test</goal>
<goal>verify</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>Line by line:
<jacoco.version>0.8.13</jacoco.version>: the JaCoCo version in a property, so it can be changed in one place. It is indicative: check the latest on Maven Central. Spring Boot does not manage the JaCoCo version, so you have to specify it.- The
prepare-agentexecution (goalprepare-agent): runs by default in theinitializephase, at the start of the build. It does not run anything by itself: it defines theargLineproperty with the options for the JaCoCo Java agent, and Surefire uses it when it launches the test JVM. That way, while the tests run, JaCoCo records which lines are executed intarget/jacoco.exec. - The
reportexecution (goalreport) bound to thetestphase: right after the tests, it turnsjacoco.execinto HTML, CSV and XML reports intarget/site/jacoco/. The one Jenkins will read istarget/site/jacoco/jacoco.xml. It is bound totest(and not toverify, its default phase) because theTestsstage runs./mvnw test. maven-failsafe-plugin: the Maven plugin for integration tests. It has no version because the Spring Boot parent manages it. Itsintegration-test(runs the tests) andverify(fails the build if any of them failed) goals are used in the Failsafe section.
Check it on your machine:
You will see index.html (open it in the browser: it is the browsable report), jacoco.csv and jacoco.xml. Add target/ to .gitignore if it was not there already: reports are never versioned.
The junit Step
The junit step (JUnit plugin, included in the suggested plugins) reads JUnit XML files and records the results in the build:
| Parameter | TecnoShop value | Effect |
|---|---|---|
testResults |
target/surefire-reports/*.xml |
Ant-style pattern for the files, relative to the workspace |
allowEmptyResults |
false |
If it does not find any file, the step fails. See below |
keepLongStdio |
false by default |
If true, it keeps the full standard output of each test (useful for debugging, but it takes up disk space on the controller) |
skipMarkingBuildUnstable |
false by default |
If there are failed tests, junit marks the build as UNSTABLE |
skipPublishingChecks |
false by default |
With the GitHub Checks plugin from 06-01, it publishes a check with the results |
As for allowEmptyResults, TecnoShop chooses false. If one day a change to pom.xml makes Surefire run no tests at all (for example, a mistyped inclusion pattern), the build would come out green without having tested anything; with false, it fails and you find out. The cost is an extra message (No test report files were found) when the build has already failed before running tests, for example because of a compilation error in the tests. It is a small price for not getting false greens.
Where to Publish: The Right Stage and post
The key question is when junit runs. If you put it in steps after mavenTecnoShop 'test', when a test fails Maven exits with an error, the stage stops and junit never runs: precisely when you need the reports most, you do not have them.
The solution is to publish it in the stage's post section with the always condition:
stage('Tests') {
when {
expression { params.RUN_TESTS }
}
options {
timeout(time: 10, unit: 'MINUTES')
}
steps {
mavenTecnoShop 'test'
}
post {
always {
junit testResults: 'target/surefire-reports/*.xml', allowEmptyResults: false
}
failure {
echo 'The tests failed: check the Test Result page of the build.'
}
}
}post { always { junit ... } }: runs whether the tests pass or fail, as you saw in 03-05.- If the stage is skipped because
RUN_TESTSisfalse, itspostdoes not run either, soallowEmptyResults: falsecauses no problems in that case. - The
failuremessage no longer says "look in the log": it says where the results are. - It is published in the stage that generates the reports, not in the pipeline's
post: it is clear where they come from and, in Pipeline Graph View, the result is associated with theTestsstage.
The Test Result Page and Trends
After the first build with junit, new elements appear:
| Where | What it shows |
|---|---|
Job page (orders-api » main) |
Test Result Trend chart: total, failed and skipped tests per build |
| Build page, side menu Tests / Test Result | Number of tests, failures, duration and the difference from the previous build |
| Inside Test Result | Tree by package (com.tecnoshop.orders), class and test |
| Page of a failed test | Error message, stack trace, standard output, Age (how many builds it has been failing) and Failing since (from which build) |
| History link of a test or class | Duration and result in previous builds |
| Pipeline Graph View | The Tests stage shows the number of tests and failures |
| GitHub (with GitHub Checks) | A Tests check with the summary and the failed tests |
Trigger a failure to see it: on a branch, change the listReturnsThreeOrders test so that it expects 4, just as you did in 01-05, and push. On the build's Test Result page you will see:
Test Result (1 failure / +1)
com.tecnoshop.orders.OrderControllerTest.listReturnsThreeOrders
Error Details: expected: <4> but was: <3>
Stack Trace: org.opentest4j.AssertionFailedError: expected: <4> but was: <3>
at com.tecnoshop.orders.OrderControllerTest.listReturnsThreeOrders(OrderControllerTest.java:13)1 failure / +1: one failed test, one more than in the previous build.- Notice that you have not opened the log: the error, the file and the line are on the build page.
Undo the change before continuing.
UNSTABLE vs. FAILURE: TecnoShop's Decision
In 01-05 you saw the states of a build. Now that Jenkins understands the tests, you need to decide what each color means.
In many installations you will see this pattern:
-Dmaven.test.failure.ignore=true: Maven does not fail even if tests fail; it finishes successfully.- Then
junitfinds the failures and marks the build as UNSTABLE (yellow).
It is a practice inherited from freestyle jobs, where it was used to distinguish "does not compile" (red) from "compiles, but tests fail" (yellow). In a pipeline it has a serious problem: UNSTABLE does not stop the pipeline. The following stages run normally, and the orders-api pipeline would package, pass the smoke check and deploy to dev code with failing tests, because the when conditions of Deploy to dev do not look at the build result.
TecnoShop's decision: it does not use -Dmaven.test.failure.ignore=true.
| Color | Meaning at TecnoShop | Examples | The pipeline... |
|---|---|---|---|
| Red (FAILURE) | Broken: it must not move forward | Does not compile, a unit or integration test fails, the smoke check fails | Stops |
| Yellow (UNSTABLE) | Degraded: it works, but a quality indicator is below its threshold | Coverage below the minimum | Continues, and the result warns you |
| Green (SUCCESS) | Everything is fine | Continues |
A failing test means the code does not do what it should: that is red. Also keep in mind that, for GitHub, an UNSTABLE build is not green: the commit status is published as failed and the protect-main rule from 06-01 prevents the merge. Yellow in Jenkins means "it works, but it does not get merged like this".
If one day you need a stage not to continue when the build is already unstable, the when condition has a way to check it:
The Coverage Plugin: recordCoverage and Its Thresholds
The Coverage plugin (coverage) reads coverage reports from several tools and displays them in Jenkins. It replaces older plugins such as the JaCoCo or Cobertura plugins, which you will see in old tutorials. Install it and add it to plugins.txt.
recordCoverage(
tools: [[parser: 'JACOCO', pattern: 'target/site/jacoco/jacoco.xml']],
id: 'jacoco',
name: 'Coverage (JaCoCo)',
sourceCodeRetention: 'LAST_BUILD',
qualityGates: [
[metric: 'LINE', baseline: 'PROJECT', threshold: 70.0, criticality: 'UNSTABLE'],
[metric: 'BRANCH', baseline: 'PROJECT', threshold: 60.0, criticality: 'UNSTABLE']
]
)tools: a list of reports.parser: 'JACOCO'indicates the format;pattern, the file. The plugin also supportsCOBERTURA,OPENCOVER,PIT(mutations) and others.idandname: identify the report in the interface (useful if a build publishes several).sourceCodeRetention: 'LAST_BUILD': keeps the colorized source code only for the last build.EVERY_BUILDkeeps it for all of them (more disk space on the controller);NEVER, for none.qualityGates: the thresholds. Each one specifies:metric: what is measured.LINEis the percentage of lines executed;BRANCH, the percentage of decision branches (everyifhas two branches) covered.baseline: on which code.PROJECTis the whole project. Other options areMODIFIED_LINES(only the lines changed in a PR) or the*_DELTAvariants (the change relative to the reference build).threshold: the minimum value.criticality: 'UNSTABLE': if it is not reached, the build becomes UNSTABLE. Consistent with the previous table: insufficient coverage is "degraded", not "broken".
The names of some parameters have changed between plugin versions (in earlier versions, the threshold was marked as unstable with unstable: true instead of criticality). If the step does not accept the syntax, generate your own with the Snippet Generator (recordCoverage: Record code coverage results).
Where to Put It
TecnoShop puts it in steps, after mavenTecnoShop 'test', not in post { always }. If the tests fail, the build is already red and the coverage of a failed run is not representative; if they pass, it is recorded and the thresholds are evaluated.
What You Will See
- On the build page, Coverage (JaCoCo): percentages per metric, a tree by package and class and, with the code retained, each file with covered lines in green, uncovered lines in red and partially covered branches in yellow.
- On the job page, the coverage trend chart.
- In PR builds, if the plugin finds a reference build from
main, the coverage of the modified code. The Git Forensics plugin, with thediscoverGitReferenceBuild()step beforerecordCoverage, helps locate that reference build. - With GitHub Checks installed, an additional check with the coverage summary.
Why 70% and 60%?
Thresholds are chosen based on the reality of the project, not the other way around. orders-api has high coverage today because it is small; 70% of lines and 60% of branches protect against drops without turning the threshold into an end in itself. 100% coverage with tests that have no assertions is worthless. For teams with poorly tested legacy code, a threshold on MODIFIED_LINES (for example, 80% of new code) is usually more useful than one on the whole project: it requires new code to arrive tested without forcing the old code to be tested all at once. It is the same "new code" idea you will see in SonarQube in the next lesson.
Integration Tests with Failsafe
The tests in OrderControllerTest are unit tests: they create the controller with new and call its methods. They are extremely fast, but they do not check that Spring starts, that the /api/orders route is mapped correctly or that the response is valid JSON. That is what integration tests do.
| Aspect | Unit (Surefire) | Integration (Failsafe) |
|---|---|---|
| What they test | An isolated class | Several pieces together: Spring, HTTP, JSON serialization |
| Speed | Milliseconds | Seconds (starting the Spring context) |
| Class names (by default) | *Test, Test*, *Tests, *TestCase |
*IT, IT*, *ITCase |
| Maven phase | test |
integration-test and verify |
| If they fail... | The build stops at test |
integration-test does not stop the build (to allow environments to be cleaned up); verify does |
| Reports | target/surefire-reports/ |
target/failsafe-reports/ |
Separating them has advantages: the fast ones give feedback sooner, each type can have its own timeout and, when something fails, you know which level the problem is at.
An Integration Test for /api/orders
Create src/test/java/com/tecnoshop/orders/OrderControllerIT.java:
package com.tecnoshop.orders;
import static org.hamcrest.Matchers.hasSize;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;
@SpringBootTest
@AutoConfigureMockMvc
class OrderControllerIT {
@Autowired
private MockMvc mockMvc;
@Test
void listReturnsJsonWithThreeOrders() throws Exception {
mockMvc.perform(get("/api/orders"))
.andExpect(status().isOk())
.andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON))
.andExpect(jsonPath("$", hasSize(3)))
.andExpect(jsonPath("$[0].customer").value("Lucia Romero"));
}
@Test
void listFiltersByStatusFromTheUrl() throws Exception {
mockMvc.perform(get("/api/orders").param("status", "shipped"))
.andExpect(status().isOk())
.andExpect(jsonPath("$", hasSize(1)))
.andExpect(jsonPath("$[0].status").value("SHIPPED"));
}
@Test
void missingOrderReturns404() throws Exception {
mockMvc.perform(get("/api/orders/99"))
.andExpect(status().isNotFound());
}
@Test
void actuatorHealthReportsUp() throws Exception {
mockMvc.perform(get("/actuator/health"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.status").value("UP"));
}
}An explanation for beginners:
OrderControllerIT: theITsuffix makes Surefire ignore it and Failsafe run it. Nothing else needs to be configured.@SpringBootTest: starts the application's full context, as ifOrdersApiApplicationwere running, with all its components.@AutoConfigureMockMvc: sets up MockMvc, a client that sends simulated HTTP requests to the controller without opening a real port. They go through the whole of Spring MVC (routes, parameters, JSON conversion), but not through the network. The advantage in Jenkins: two simultaneous builds on the same agent do not compete for a port, unlike theSmokestage, which needed18090 + EXECUTOR_NUMBER.@Autowired private MockMvc mockMvc: Spring injects the client into the test.mockMvc.perform(get("/api/orders")): performs aGETon the route..andExpect(status().isOk()): expects a 200 code.content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON): the response must be JSON.jsonPath("$", hasSize(3)):$is the root of the JSON (here, a list), which must have 3 elements.hasSizecomes from Hamcrest, included inspring-boot-starter-test.jsonPath("$[0].customer").value("Lucia Romero"): thecustomerfield of the first element..param("status", "shipped"): adds?status=shipped; it checks end to end the filter Diego added in 04-05.actuatorHealthReportsUp: verifies that the health endpoint used bySmokeand, later, by deployments responds with{"status":"UP"}.
If you prefer a test with a real port, Spring Boot offers @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT) with an HTTP client such as RestClient or TestRestTemplate: the random port avoids conflicts between builds. MockMvc is enough for orders-api, and faster.
Run it locally with the full lifecycle:
In the output you will first see the Surefire tests (Tests run: 4) and then, in the integration-test phase, the Failsafe ones (Tests run: 4 from OrderControllerIT). In target/failsafe-reports/ there is a TEST-com.tecnoshop.orders.OrderControllerIT.xml and a failsafe-summary.xml.
The Integration tests Stage
In Jenkins, the Tests stage has already compiled the test classes and run the unit tests. To avoid repeating everything with verify, the new stage invokes the Failsafe goals directly:
stage('Integration tests') {
when {
expression { params.RUN_TESTS }
}
options {
timeout(time: 10, unit: 'MINUTES')
}
steps {
mavenTecnoShop goals: 'failsafe:integration-test failsafe:verify', label: 'Integration tests'
}
post {
always {
junit testResults: 'target/failsafe-reports/TEST-*.xml', allowEmptyResults: false
}
}
}failsafe:integration-test failsafe:verify: runs the two goals without going through the lifecycle, so it does not compile again or rerun the unit tests. It works because the classes are already compiled in the workspace by the earlier stages (the agent is the same for the whole pipeline).- It comes after
Checks: if the unit tests fail, it is not even attempted (fail fast). And beforePackage: code that does not pass integration is not packaged. TEST-*.xmlinstead of*.xml: Failsafe also writesfailsafe-summary.xml, which is not a JUnit report; including it can cause errors when it is read.- The same
whencondition asTests: if someone unchecksRUN_TESTS, both are skipped. - In Jenkins, the results of both stages add up on the same Test Result page, but each test appears associated with its stage.
JaCoCo coverage still measures only the unit tests. JaCoCo can also measure the integration tests (with the prepare-agent-integration and report-integration goals) if you are ever interested.
catalog-web: jest-junit and Jest Coverage
Jest does not write JUnit XML by itself, but it has reporters that do. Install jest-junit in catalog-web:
This adds the dependency to package.json and updates package-lock.json: push both, as you learned in the previous lesson. Then edit package.json:
{
"name": "catalog-web",
"version": "1.0.0",
"private": true,
"description": "TecnoShop web catalog (practice project for the Jenkins course)",
"main": "src/prices.js",
"scripts": {
"test": "jest --ci --coverage",
"build": "node scripts/build.js"
},
"engines": {
"node": ">=18"
},
"devDependencies": {
"jest": "^29.7.0",
"jest-junit": "^16.0.0"
},
"jest": {
"collectCoverageFrom": ["src/**/*.js", "!src/**/*.test.js"],
"coverageReporters": ["text-summary", "lcov", "cobertura"],
"reporters": [
"default",
["jest-junit", { "outputDirectory": "reports", "outputName": "junit.xml" }]
]
}
}"test": "jest --ci --coverage":--coverageenables coverage measurement on every test run.collectCoverageFrom: which files are measured. All files insrc/are included except the tests themselves.coverageReporters: formats of the coverage report, incoverage/:text-summary: a summary in the console, useful in the log.lcov:coverage/lcov.info, the format SonarQube will read in 06-04.cobertura:coverage/cobertura-coverage.xml, the formatrecordCoveragewill read.
reporters:defaultkeeps Jest's normal console output, andjest-junitalso writesreports/junit.xml.- The
jest-junitversion in the example is indicative; the one npm installs will be pinned in the lockfile.
Add reports/ to .gitignore (it already contains coverage/).
The Changes to the Matrix
Each cell runs the tests on one Node version, so each one publishes its results. Coverage, on the other hand, is the same in all three; it is recorded only in the node-22 cell, the production version:
stage('Tests per Node version') {
matrix {
axes {
axis {
name 'NODE_VERSION'
values 'node-18', 'node-20', 'node-22'
}
}
agent {
label 'linux'
}
stages {
stage('Test') {
steps {
nodejs(nodeJSInstallationName: env.NODE_VERSION, configId: 'npmrc-tecnoshop') {
sh 'node --version && npm --version'
sh 'npm ci --prefer-offline'
sh 'npm test'
}
}
post {
always {
junit testResults: 'reports/junit.xml', allowEmptyResults: false
}
}
}
stage('Coverage') {
when {
environment name: 'NODE_VERSION', value: 'node-22'
}
steps {
recordCoverage(
tools: [[parser: 'COBERTURA', pattern: 'coverage/cobertura-coverage.xml']],
id: 'jest',
name: 'Coverage (Jest)',
qualityGates: [
[metric: 'LINE', baseline: 'PROJECT', threshold: 80.0, criticality: 'UNSTABLE']
]
)
}
}
}
post {
cleanup {
cleanWs()
}
}
}
}What changed and why:
junitin thepost { always }ofTest: as inorders-api, it is published even if the tests fail. Because it runs in all three cells, Jenkins records the tests of each one; on the Test Result page they are identified by the cell (the stage and the value ofNODE_VERSION) in which they ran, so a failure only onnode-18can be spotted at a glance.Coveragestage inside the matrix, withwhen { environment name: 'NODE_VERSION', value: 'node-22' }: it only runs in that cell. In the other two it shows up as skipped.parser: 'COBERTURA'with the file Jest generates. An 80% line threshold:src/prices.jsis small and well tested.cleanWs()moves up from thepostofTestto the matrixpost: if it stayed inTest, the workspace would be deleted beforeCoveragecould read the report. Apostdeclared insidematrixapplies to each cell once all its stages have finished.
Flaky Tests
A flaky test is one that sometimes passes and sometimes fails without the code changing: it depends on the execution order, the time of day, a port that is in use, a sleep that is too short or an external service. Flaky tests do a lot of damage: the team gets used to rerunning the build "to see if it passes this time" and stops trusting failures, including the real ones.
How to Detect Them
- On a test's page, History shows a pattern of alternating green and red across builds of the same code.
- Age keeps resetting: the test fails, passes, fails again.
- The nightly
mainbuild (thecronfrom 04-05) is a good detector: the code does not change between nights; if a test fails one night and not the next, it is flaky.
The Temptation: Automatic Reruns
Surefire and Failsafe can rerun failed tests:
- If a test fails, it is rerun up to 2 times; if it passes on any retry, it is considered passed and marked as flaky in the XML report.
It looks like a solution, and it is dangerous:
- It hides real bugs: a concurrency problem that shows up one time in three is a bug in the code, not in the test, and it would reach production.
- It makes builds longer when there are real failures: every broken test runs three times.
- It normalizes flakiness: nobody fixes something that "passes on its own".
TecnoShop's policy: global retries are not used. A flaky test is treated as a failure:
- An issue is opened with a link to its History.
- If it blocks the team, it is put in quarantine: it is marked with the JUnit 5 tag
@Tag("quarantine")and excluded from regular builds. - Quarantined tests are run separately so they are not lost from sight, and they have a deadline (two weeks) to be fixed or deleted.
The exclusion is configured in pom.xml, with a property that Surefire and Failsafe read:
<properties>
<java.version>21</java.version>
<jacoco.version>0.8.13</jacoco.version>
<excludedGroups>quarantine</excludedGroups>
</properties> @Test
@Tag("quarantine") // Issue ORD-123: fails intermittently because of the system time
void calculatesDeliveryDate() { ... }And quarantined tests can be run on purpose, for example in a nightly practice job:
-Dgroups=quarantine: only the tests with that tag.-DexcludedGroups=: empties the exclusion frompom.xml.
There are Jenkins plugins aimed at analyzing test history (for example, Test Results Analyzer, which shows a table of results per test and build). They are useful when the number of tests grows, but they do not replace the policy: detecting is not fixing.
What Marta Gains
For the QA team, the change in this lesson is big. With her qa role from 05-02, Marta now has:
| Before | Now |
|---|---|
| "The build is red" and a log thousands of lines long | The Test Result page with the specific test, the message and the line |
| No idea how many tests there are | Number of tests per build and its trend |
| No way to tell whether a failure is new | Age and Failing since |
| No coverage data | Coverage by package, class and line, and how it evolves |
| Asking Diego whether a test "usually fails" | The History of each test |
| Checking Jenkins for every PR | The Tests check in the GitHub PR itself |
And something subtler: permanent links. Every build, every report and every test has a stable URL (.../orders-api/job/main/57/testReport/com.tecnoshop.orders/OrderControllerIT/), which Marta can paste into an issue so that anyone sees exactly the same result. Remember that build retention (buildDiscarder with 30 builds) limits how long they exist: to keep a specific one, use Keep this build forever, as in 02-04.
End-to-End Tests: A Preview
End-to-end (E2E) or browser tests open the application in a real browser and go through it as a user would: for example, with Playwright or Selenium, checking that the catalog displays prices in the formatPrice format. They need browsers installed and, often, the application deployed, so they fit better in containers prepared for the purpose. You will see them in Jenkins with Docker. The way their results are published will be the same: almost all of these tools write JUnit XML, which the junit step will read.
The Updated orders-api Jenkinsfile
@Library('[email protected]') _
pipeline {
agent {
label 'linux'
}
options {
timestamps()
timeout(time: 20, unit: 'MINUTES')
buildDiscarder(logRotator(numToKeepStr: '30', artifactNumToKeepStr: '5'))
disableConcurrentBuilds()
preserveStashes(buildCount: 5)
}
parameters {
booleanParam(name: 'RUN_TESTS', defaultValue: true,
description: 'Uncheck only to quickly verify that the code compiles. Never for a build that is going to be deployed.')
choice(name: 'ENVIRONMENT', choices: ['dev', 'staging', 'production'],
description: 'Target environment. For now only dev has a deployment (simulated), and only from main.')
}
triggers {
cron(env.BRANCH_NAME == 'main' ? 'TZ=Europe/Madrid\nH 2 * * 1-5' : '')
}
environment {
MAVEN_ARGS = '-B -ntp'
MAVEN_SETTINGS_ID = 'maven-settings-tecnoshop'
IMAGE = 'registry.tecnoshop.local/orders-api'
APP_VERSION = sh(script: './mvnw -q help:evaluate -Dexpression=project.version -DforceStdout',
returnStdout: true, label: 'Read the version from the pom').trim()
IMAGE_TAG = "${APP_VERSION}-${BUILD_NUMBER}"
}
stages {
stage('PR info') {
when {
changeRequest()
}
steps {
echo "PR #${env.CHANGE_ID} by ${env.CHANGE_AUTHOR}: ${env.CHANGE_BRANCH} → ${env.CHANGE_TARGET} (${env.CHANGE_URL})"
}
}
stage('Build') {
steps {
echo "Build ${env.BUILD_NUMBER} of ${env.JOB_NAME} | branch ${env.BRANCH_NAME} | version ${env.APP_VERSION} | ENVIRONMENT=${params.ENVIRONMENT} | RUN_TESTS=${params.RUN_TESTS}"
mavenTecnoShop 'clean compile'
}
}
stage('Checks') {
failFast true
parallel {
stage('Tests') {
when {
expression { params.RUN_TESTS }
}
options {
timeout(time: 10, unit: 'MINUTES')
}
steps {
mavenTecnoShop 'test'
recordCoverage(
tools: [[parser: 'JACOCO', pattern: 'target/site/jacoco/jacoco.xml']],
id: 'jacoco',
name: 'Coverage (JaCoCo)',
sourceCodeRetention: 'LAST_BUILD',
qualityGates: [
[metric: 'LINE', baseline: 'PROJECT', threshold: 70.0, criticality: 'UNSTABLE'],
[metric: 'BRANCH', baseline: 'PROJECT', threshold: 60.0, criticality: 'UNSTABLE']
]
)
}
post {
always {
junit testResults: 'target/surefire-reports/*.xml', allowEmptyResults: false
}
failure {
echo 'The tests failed: check the Test Result page of the build.'
}
}
}
stage('Dependency analysis') {
options {
timeout(time: 5, unit: 'MINUTES')
}
steps {
mavenTecnoShop goals: 'dependency:tree -DoutputFile=dependencies.txt', label: 'Dependency tree'
archiveArtifacts artifacts: 'dependencies.txt'
}
}
}
}
stage('Integration tests') {
when {
expression { params.RUN_TESTS }
}
options {
timeout(time: 10, unit: 'MINUTES')
}
steps {
mavenTecnoShop goals: 'failsafe:integration-test failsafe:verify', label: 'Integration tests'
}
post {
always {
junit testResults: 'target/failsafe-reports/TEST-*.xml', allowEmptyResults: false
}
}
}
stage('Package') {
steps {
mavenTecnoShop '-DskipTests package'
infoBuild application: 'orders-api', version: env.APP_VERSION, image: "${env.IMAGE}:${env.IMAGE_TAG}"
archiveArtifacts artifacts: 'target/*.jar,build-info.txt', fingerprint: true
stash name: 'jar', includes: 'target/*.jar'
}
}
stage('Smoke') {
options {
timeout(time: 3, unit: 'MINUTES')
}
steps {
smokeSpringBoot extraPath: '/api/orders', expectedText: 'SHIPPED'
}
}
stage('Deploy to dev') {
when {
allOf {
branch 'main'
expression { params.ENVIRONMENT == 'dev' }
expression { params.RUN_TESTS }
}
}
steps {
unstash 'jar'
echo "SIMULATION: this is where target/orders-api-${env.APP_VERSION}.jar would be deployed to dev (future image: ${env.IMAGE}:${env.IMAGE_TAG}; real deployment in 06-06 and 07-03)."
}
}
}
post {
success {
echo "OK: orders-api ${env.APP_VERSION} (${env.BRANCH_NAME}) #${env.BUILD_NUMBER} built successfully."
}
unstable {
echo "WARNING: orders-api (${env.BRANCH_NAME}) #${env.BUILD_NUMBER} is unstable: check the coverage."
}
failure {
echo "ERROR: orders-api (${env.BRANCH_NAME}) #${env.BUILD_NUMBER} failed. Check the red stage."
}
fixed {
echo "orders-api (${env.BRANCH_NAME}) is back to green after an earlier failure."
}
cleanup {
cleanWs()
}
}
}Changes compared with the previous lesson:
Tests:recordCoveragewith line and branch thresholds, andjunitinpost { always }.- A new
Integration testsstage, betweenChecksandPackage, with its ownjunit. - The
unstablemessage in the pipeline'spostpoints to the usual cause: coverage. - The
pom.xmlincludes JaCoCo, Failsafe and the quarantine exclusion; the repository, theOrderControllerITclass. - The pipeline still has no
scriptblocks.
Common Mistakes and Tips
junitinstepsafter the tests: it does not run when they fail, which is exactly when you need it most. Put it inpost { always }.No test report files were foundwhen the tests do run: the pattern does not match (paths are relative to the workspace, not absolute) or the reports are in another directory, for example in a subdirectory of a multi-module project (use**/target/surefire-reports/*.xml).- Including
failsafe-summary.xmlwithtarget/failsafe-reports/*.xml: it is not JUnit XML. UseTEST-*.xml. - The JaCoCo report is not generated: the
reportgoal is in its default phase (verify) and the stage only runstest. Binding it totestfixes it. - 0% coverage despite having tests: some other
pom.xmlconfiguration overrides Surefire'sargLineand removes the JaCoCo agent. If you need your ownargLine, include the JaCoCo property with the@{argLine}syntax. - Integration tests that use a fixed port: they collide when two builds coincide on the same agent. Use MockMvc or a random port.
-Dmaven.test.failure.ignore=truecopied from a tutorial: it turns failures yellow and lets the pipeline carry on all the way to deployment.- Raising coverage thresholds "to motivate people" above what the code actually has: every build ends up yellow and the threshold loses its value as a warning.
- Tip: when a test fails in Jenkins but not on your machine, compare the environment shown in the console (Java version, time zone, variables) with yours before concluding that it is flaky. Many "flaky" tests are really tests that depend on the environment.
Exercises
Exercise 1. Add JaCoCo, Failsafe and OrderControllerIT to orders-api and update the Jenkinsfile. Then, on a branch, delete the getMissingOrderReturns404 test from OrderControllerTest and missingOrderReturns404 from OrderControllerIT. What happens to branch coverage? What color is the build and what do you see in the GitHub PR? Undo the change.
Exercise 2. A colleague proposes adding -Dsurefire.rerunFailingTestsCount=3 to MAVEN_ARGS because "the OrderServiceTest.reservesStock test fails every now and then and blocks PRs". Write Laura's reply with a concrete alternative.
Exercise 3. Apply the catalog-web changes (jest-junit, coverage and the new matrix structure). Then introduce a bug in src/prices.js that only affects Node 18 (hint: use a method that does not exist in that version, such as Array.prototype.toSorted, in a new function with its test). How does Marta locate the problem without opening the log?
Solutions
Solution 1. The get method has two paths: the order exists (.map(ResponseEntity::ok)) or it does not (.orElse(...)). Without the 404 tests, JaCoCo records that the orElse path never runs, and branch coverage drops. If it falls below 60%, recordCoverage marks the build as UNSTABLE (yellow); on the Coverage (JaCoCo) page you will see the orElse line highlighted as uncovered. In GitHub, the commit status appears as failed (UNSTABLE is not green for GitHub) and the protect-main rule prevents the PR from being merged. If coverage did not drop below the threshold (it depends on the rest of the code), the build would stay green, but the trend chart would show the drop: a threshold is no substitute for watching the trend.
Solution 2. "I would rather not. With three retries, reservesStock would almost always pass and we would stop seeing it, but if it fails 'every now and then' it may be a real concurrency problem in stock reservation, which in production would affect customer orders. Besides, the retries would apply to every test in the project. Proposal: (1) open an issue with the link to the test's History in Jenkins; (2) while it is being investigated, put it in quarantine with @Tag("quarantine") and the issue reference, so it does not block PRs; (3) whoever investigates it can run it in a loop locally with -Dgroups=quarantine; (4) it has two weeks to be fixed or removed. If we find out the failure is in the code, the test has done its job."
Solution 3. The node-18 matrix cell turns red and the node-20 and node-22 cells stay green (toSorted exists since Node 20). Marta opens the build and, in Pipeline Graph View, sees which cell failed; in Test Result, the failed test appears associated with the NODE_VERSION = node-18 cell, with an error along the lines of TypeError: ... toSorted is not a function. The Coverage stage only runs on node-22, so coverage is recorded normally. With that, Marta can open the issue stating the affected version and linking to the test, without reading a single line of the log. The fix is to use [...list].sort(...) (compatible with every version) or, if the team decides to drop Node 18, remove it from the matrix and update engines in package.json.
Conclusion
Jenkins now understands the results of TecnoShop's tests. orders-api measures its coverage with JaCoCo (prepare-agent and report bound to test, with the report in target/site/jacoco/jacoco.xml), publishes its unit and integration tests with the junit step in the post { always } of each stage and its coverage with recordCoverage, whose line and branch thresholds mark the build as unstable; integration tests with Failsafe and MockMvc have their own stage between Checks and Package. catalog-web does the same with jest-junit and Jest coverage in Cobertura format, recorded only in the node-22 cell. You have settled TecnoShop's color semantics (red is broken, yellow is degraded, which is why -Dmaven.test.failure.ignore is not used), a policy for flaky tests based on quarantine rather than retries, and Marta has reports, trends, history and permanent links. Tests tell you whether the code does what it should; what is still missing is knowing whether it is well made: whether it has likely bugs, vulnerabilities, duplication or technical debt. That is what you will analyze in Code Quality Analysis with SonarQube.
