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-agent execution (goal prepare-agent): runs by default in the initialize phase, at the start of the build. It does not run anything by itself: it defines the argLine property 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 in target/jacoco.exec.
  • The report execution (goal report) bound to the test phase: right after the tests, it turns jacoco.exec into HTML, CSV and XML reports in target/site/jacoco/. The one Jenkins will read is target/site/jacoco/jacoco.xml. It is bound to test (and not to verify, its default phase) because the Tests stage runs ./mvnw test.
  • maven-failsafe-plugin: the Maven plugin for integration tests. It has no version because the Spring Boot parent manages it. Its integration-test (runs the tests) and verify (fails the build if any of them failed) goals are used in the Failsafe section.

Check it on your machine:

./mvnw -B clean test
ls target/site/jacoco/

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:

junit testResults: 'target/surefire-reports/*.xml', allowEmptyResults: false
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_TESTS is false, its post does not run either, so allowEmptyResults: false causes no problems in that case.
  • The failure message 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 the Tests stage.

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:

sh './mvnw -B -Dmaven.test.failure.ignore=true test'
junit 'target/surefire-reports/*.xml'
  • -Dmaven.test.failure.ignore=true: Maven does not fail even if tests fail; it finishes successfully.
  • Then junit finds 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:

when {
    expression { currentBuild.currentResult == 'SUCCESS' }
}

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 supports COBERTURA, OPENCOVER, PIT (mutations) and others.
  • id and name: 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_BUILD keeps it for all of them (more disk space on the controller); NEVER, for none.
  • qualityGates: the thresholds. Each one specifies:
    • metric: what is measured. LINE is the percentage of lines executed; BRANCH, the percentage of decision branches (every if has two branches) covered.
    • baseline: on which code. PROJECT is the whole project. Other options are MODIFIED_LINES (only the lines changed in a PR) or the *_DELTA variants (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 the discoverGitReferenceBuild() step before recordCoverage, 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: the IT suffix makes Surefire ignore it and Failsafe run it. Nothing else needs to be configured.
  • @SpringBootTest: starts the application's full context, as if OrdersApiApplication were 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 the Smoke stage, which needed 18090 + EXECUTOR_NUMBER.
  • @Autowired private MockMvc mockMvc: Spring injects the client into the test.
  • mockMvc.perform(get("/api/orders")): performs a GET on 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. hasSize comes from Hamcrest, included in spring-boot-starter-test.
  • jsonPath("$[0].customer").value("Lucia Romero"): the customer field 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 by Smoke and, 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:

./mvnw -B clean verify
ls target/failsafe-reports/

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 before Package: code that does not pass integration is not packaged.
  • TEST-*.xml instead of *.xml: Failsafe also writes failsafe-summary.xml, which is not a JUnit report; including it can cause errors when it is read.
  • The same when condition as Tests: if someone unchecks RUN_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:

npm install --save-dev jest-junit

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": --coverage enables coverage measurement on every test run.
  • collectCoverageFrom: which files are measured. All files in src/ are included except the tests themselves.
  • coverageReporters: formats of the coverage report, in coverage/:
    • 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 format recordCoverage will read.
  • reporters: default keeps Jest's normal console output, and jest-junit also writes reports/junit.xml.
  • The jest-junit version 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:

  • junit in the post { always } of Test: as in orders-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 of NODE_VERSION) in which they ran, so a failure only on node-18 can be spotted at a glance.
  • Coverage stage inside the matrix, with when { 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.js is small and well tested.
  • cleanWs() moves up from the post of Test to the matrix post: if it stayed in Test, the workspace would be deleted before Coverage could read the report. A post declared inside matrix applies 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 main build (the cron from 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:

./mvnw -B test -Dsurefire.rerunFailingTestsCount=2
  • 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:

  1. An issue is opened with a link to its History.
  2. 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.
  3. 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:

./mvnw -B test -Dgroups=quarantine -DexcludedGroups=
  • -Dgroups=quarantine: only the tests with that tag.
  • -DexcludedGroups=: empties the exclusion from pom.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: recordCoverage with line and branch thresholds, and junit in post { always }.
  • A new Integration tests stage, between Checks and Package, with its own junit.
  • The unstable message in the pipeline's post points to the usual cause: coverage.
  • The pom.xml includes JaCoCo, Failsafe and the quarantine exclusion; the repository, the OrderControllerIT class.
  • The pipeline still has no script blocks.

Common Mistakes and Tips

  • junit in steps after the tests: it does not run when they fail, which is exactly when you need it most. Put it in post { always }.
  • No test report files were found when 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.xml with target/failsafe-reports/*.xml: it is not JUnit XML. Use TEST-*.xml.
  • The JaCoCo report is not generated: the report goal is in its default phase (verify) and the stage only runs test. Binding it to test fixes it.
  • 0% coverage despite having tests: some other pom.xml configuration overrides Surefire's argLine and removes the JaCoCo agent. If you need your own argLine, 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=true copied 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.

© Copyright 2026. All rights reserved