首页 > 解决方案 > 詹金斯:捕捉junit测试失败

问题描述

我试图让我的 Jenkins 在 junit 测试失败时发送一条 Slack 消息,但是当测试失败时它不会执行任何其他操作。我在Multibranch Pipeline工作中的 Jenkinsfile 中使用脚本化管道。

这是管道中的测试阶段:

node {
    // setup and build Docker image
    stage("Test") {
        slackSend message: "Running tests!" 
        sh("docker run --rm -i \
            -v '${env.WORKSPACE}/tests/results/':/tmp/tests/results \
            ${image} python3 manage.py test")
        try {
            slackSend message: "Checking tests!" 
            junit 'tests/results/*.xml'
        } catch(err) {
            slackSend message: "Error in tests!" 
        } finally {
            slackSend message: "Finally in tests!" 
        }
    }
}

我故意添加了一个会失败的测试用例。我希望看到的是所有四个 Slack 消息:Running tests!Checking tests!Error in tests!Finally in tests!,但我看到的只是Running tests!即使Checking消息出现junit在行之前。

如果测试没有任何失败,那么我会看到Running和Slack 消息CheckingFinally正如我所期望的那样。

try/catch当junit测试失败时,为什么不执行?

标签: jenkinsjunit

解决方案


junit 管道命令不会生成异常,它只会准备/显示单元测试报告。在您的情况下,“真正的单元测试失败”是在 docker 命令执行期间,因此您只需检查 docker run 返回代码。另外检查一下,当测试失败时,python3 命令也会返回错误代码。

检查此答案以了解如何获取 docker run 返回代码 如何获取已退出 docker 容器的数字退出状态?


推荐阅读