如何在单元测试失败时发送通知?

How to send a notification when a unit test fails?

我在 Jenkins 管道中使用以下函数来处理单元测试结果并将它们显示在 Jenkins 构建页面中:

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]
        ]
    ])
}

我知道 J/Xunit 结果显示在 Jenkins 构建页面中,但我希望能够发送 Slack 通知(Slack 通知已配置并运行)如果单元测试失败,更重要的是当它失败时,这可能吗?

您可以为此单元测试套件使用 try/catch,但也许不能单独使用。

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
    }
}

并根据您的喜好自定义 Slack 通知。