Itai Ganot Itai Ganot - 28 days ago 18
Groovy Question

How to send a notification when a unit test fails?

I use the following function within a Jenkins pipeline in order to process unit test results and display them in the Jenkins build page:

def check_test_results(String path) {
step([
$class: 'XUnitBuilder',
testTimeMargin: '3000',
thresholdMode: 1,
thresholds: [
[$class: 'FailedThreshold', failureNewThreshold: '0', failureThreshold: '0', unstableNewThreshold: '', unstableThreshold: ''],
[$class: 'SkippedThreshold', failureNewThreshold: '', failureThreshold: '', unstableNewThreshold: '', unstableThreshold: '']
],
tools: [
[$class: 'JUnitType', deleteOutputFiles: true, failIfNotNew: false, pattern: path, skipNoTestFiles: false, stopProcessingIfError: true]
]
])
}


I'm aware to the fact that the J/Xunit results are displayed in the Jenkins build page but I want to have the ability to send a Slack notification (slack notifications are already configured and working) if a unit test fails and more importantly when it fails, is that possible?

Answer

You can use a try/catch for this for the suite of unit tests, but perhaps not individually.

def check_test_results(String path) {
    try {
        step([
            $class: 'XUnitBuilder',
            testTimeMargin: '3000',
            thresholdMode: 1,
            thresholds: [
                [$class: 'FailedThreshold', failureNewThreshold: '0', failureThreshold: '0', unstableNewThreshold: '', unstableThreshold: ''],
                [$class: 'SkippedThreshold', failureNewThreshold: '', failureThreshold: '', unstableNewThreshold: '', unstableThreshold: '']
            ],
            tools: [
                [$class: 'JUnitType', deleteOutputFiles: true, failIfNotNew: false, pattern: path, skipNoTestFiles: false, stopProcessingIfError: true]
            ]
        ])
    }
    catch(error) {
        slackSend message: error
    }
}

and customize the Slack notification to your liking.

Comments