How to abort a Pipeline build if JUnit tests fail?

Article ID:218866667
1 minute readKnowledge base

Issue

I have a Pipeline job that has multiple stages. I would like the build to abort after the "test" stage and not continue if there are test failures. I also want to ensure that the test results are correctly archived.

Environment

  • CloudBees Jenkins Enterprise

  • Pipeline plugin

  • JUnit Plugin

  • Maven

Resolution

You can use a try catch block to achieve this.

The below example will catch the exception thrown if JUnit tests fail, archive the JUnit test results and abort the build.

The

node {

    stage "checkout"

    git url: '...'

    stage "test"

    try {
        // Any maven phase that that triggers the test phase can be used here.
        sh 'mvn test -B'
    } catch(err) {
        step([$class: 'JUnitResultArchiver', testResults: '**/target/surefire-reports/TEST-*.xml'])
        throw err
    }

    stage "deploy"

    echo "Im deploying now!"
}

This stops the "deploy" stage from executing in the event of failed tests.

Note that we purposely don’t use -Dmaven.test.failure.ignore verify in the maven command here (as per the docs[1]). This means that an exception will be thrown when there are failed tests, which we catch, call the JUnitResultArchiver step to archive the test results, then re-throw the exception to abort the build.

Note that by default JUnitResultArchiver will mark the build as UNSTABLE when there are failed tests. If you want to mark the build as FAILURE instead then change the catch block to:

...
catch(err) {
  step([$class: 'JUnitResultArchiver', testResults: '**/target/surefire-reports/TEST-*.xml'])
  if (currentBuild.result == 'UNSTABLE')
    currentBuild.result = 'FAILURE'
  throw err
}