Jenkins: How to set the build-result as UNSTABLE when tests fail in a Declarative Pipeline
I have just spent a few weeks worth of time, creating Jenkinfiles for Declarative Pipelines for x-platform builds for two C++ projects. The concept of Declarative Pipelines is easy to understand, but some things are difficult, or impossible, to do, just using the Declarative Pipeline syntax.
Fortunately, we can execute blocks of code in a script
block.
The example below show how to handle failed tests (where for example ctest returns an error value) gracefully, and just mark the build as UNSTABLE not FAILED. That means that it's very easy to distinguish between build failures in red, and test failures in yellow when you look at the Jenkins dashboard for the project.
1pipeline {
2
3 agent any
4
5 stages {
6 stage ('Build & Test') {
7 steps {
8 sh 'echo Building... Failure here will fail the build'
9 script {
10 try {
11 echo 'Running tests...'
12 sh 'exit 1'
13 }
14 catch (exc) {
15 echo 'Testing failed!'
16 currentBuild.result = 'UNSTABLE'
17 }
18 }
19 }
20 }
21 }
22}