Published:

Jenkins: How to set the build-result as UNSTABLE when tests fail in a Declarative Pipeline

bookmark 1 min read

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.

pipeline {

    agent any

    stages {
        stage ('Build & Test') {
            steps {
                sh 'echo Building... Failure here will fail the build'
                script {
                    try {
                        echo 'Running tests...'
                        sh 'exit 1'
                    }
                    catch (exc) {
                        echo 'Testing failed!'
                        currentBuild.result = 'UNSTABLE'
                    }
                }
            }
        }
    }
}