Jenkins Pipeline如何跳过无测试类的publishHTML与junit步骤?
解决Jenkins Pipeline跳过无测试类时的publishHTML和junit步骤问题
方法1:先检查文件/目录存在性,再执行对应步骤
这是最稳妥的方案,通过条件判断只在目标资源存在时执行步骤,彻底避免报错。
示例Pipeline代码:
pipeline { agent any stages { // 其他业务阶段... stage('Publish Test Reports') { steps { script { // 检查Jacoco报告目录是否存在 def jacocoDir = '/home/jenkins/agent/....site/jacoco' if (fileExists(jacocoDir)) { publishHTML(target: [ allowMissing: false, alwaysLinkToLastBuild: false, keepAll: true, reportDir: jacocoDir, reportFiles: 'index.html', reportName: 'Jacoco Coverage Report' ]) } else { echo "Jacoco报告目录不存在,跳过publishHTML步骤" } // 检查JUnit报告文件是否存在 def junitReportPaths = findFiles(glob: '.../reports/*.xml') if (junitReportPaths.size() > 0) { junit testResults: '.../reports/*.xml', allowEmptyResults: true } else { echo "未找到JUnit测试报告文件,跳过junit步骤" } } } } } }
方法2:给publishHTML添加allowMissing参数
publishHTML原生支持allowMissing: true参数,开启后即使指定目录不存在,也只会跳过步骤而不报错。
修改后的publishHTML配置:
publishHTML(target: [ allowMissing: true, // 核心参数:目录不存在时不触发报错 alwaysLinkToLastBuild: false, keepAll: true, reportDir: '/home/jenkins/agent/....site/jacoco', reportFiles: 'index.html', reportName: 'Jacoco Coverage Report' ])
方法3:修正junit的allowEmptyResults使用问题
你之前配置后仍报错,大概率是因为testResults指定的路径完全匹配不到任何文件(连空文件都没有)。此时可以结合路径通配符+前置判断,或者调整参数使用方式:
// 先用findFiles确认是否有匹配文件,再执行junit def junitFiles = findFiles(glob: '**/reports/*.xml') if (junitFiles.size() > 0) { junit testResults: '**/reports/*.xml', allowEmptyResults: true } else { echo "无JUnit测试报告,跳过测试结果统计" }
注意:如果testResults的路径完全找不到任何文件,即使设置allowEmptyResults: true,Jenkins仍可能触发报错,因此前置判断是更可靠的方式。
内容的提问来源于stack exchange,提问作者IpU
相关产品推荐
相关产品推荐

