如果单元测试失败,Jenkins 脚本化管道不会获取测试结果



我有基于 gradle 的 Java 项目,其中包含 junit 测试,我正在为其构建 CI 作业。我成功地使用Slack Slack Notification插件将Slack与Jenkins集成。

詹金斯版本 : 2.173
松弛通知版本 : 2.20

Jenkins CI 是一个脚本化管道,具有以下代码:


stage('Test') {
def slackHelper = new com.xyz.jenkins.libraries.SlackNotifier(env)
try {
sh "./gradlew test"
junit 'build/test-results/test/*.xml'
} finally {
AbstractTestResultAction testResultAction =  currentBuild.rawBuild.getAction(AbstractTestResultAction.class)
slackHelper.getTestStatuses(currentBuild)
slackSend(channel: '#ci-cd', attachments: slackHelper.buildUnitTestSlackNotificationMessage())
}
}

SlackNotifier是一个具有以下代码的库:

/**
* Calculates test result as a string
* @param currentBuild : jenkins object, should be passed from jenkins pipeline script
* @return the final test result as a string
*/
@NonCPS
def getTestStatuses(currentBuild) {
final AbstractTestResultAction testResultAction = currentBuild.rawBuild.getAction(AbstractTestResultAction.class)
if (testResultAction != null) {
this.total = testResultAction.totalCount
this.failed = testResultAction.failCount
this.skipped = testResultAction.skipCount
this.passed = total - failed - skipped
}
}

buildUnitTestSlackNotificationMessage 在同一个类中执行此操作:

def buildUnitTestSlackNotificationMessage() {
final JSONObject unitTestResult = new JSONObject()
unitTestResult.put("fallback", this.jenkinsEnvironment.JOB_NAME + "with build#" + this.jenkinsEnvironment.BUILD_NUMBER + "finish with unit test result : Passed: " + this.passed + " | Failed: " + this.failed + " | Skipped: " + this.skipped )
unitTestResult.put("color", this.getUnitTestReportColor())
unitTestResult.put("pretext", "Message from CI job: " + this.jenkinsEnvironment.JOB_NAME + "#" + this.jenkinsEnvironment.BUILD_NUMBER)
unitTestResult.put("title", "BuildLog")
unitTestResult.put("title_link", "<<<JenkinsHost>>>" + this.jenkinsEnvironment.JOB_NAME + "/" + this.jenkinsEnvironment.BUILD_NUMBER  + "/console")
unitTestResult.put("text", "Passed: " + this.passed +  " | Failed: " + this.failed + " | Skipped: " + this.skipped)
unitTestResult.put("image_url", this.getLogoURL())
this.attachments.add(unitTestResult)
return this.attachments.toString()
}

当所有测试都通过时,一切都很好。但是当测试失败时,我会收到以下通知:

Message from CI job: <<<JobName>>>#47
BuildLog
Passed: null | Failed: null | Skipped: null

事实证明,当任何单元测试在此处失败时testResultAction为 null。

我无法深入了解这一点。请帮忙。

我在reddit上得到了答案,功劳归于:/u/Bodumin

这是根本原因,我在这里引用他的话:

Move the junit step into the finally. What's likely happening is that test returns a non 0 (error) status so it fails it of the try.

因此,脚本化管道如下所示:

stage('Test') {
def slackHelper = new com.xyz.jenkins.libraries.SlackNotifier(env)
try {
sh "./gradlew test"
} finally {
junit 'build/test-results/test/*.xml'
AbstractTestResultAction testResultAction =  currentBuild.rawBuild.getAction(AbstractTestResultAction.class)
slackHelper.getTestStatuses(currentBuild)
slackSend(channel: '#ci-cd', attachments: slackHelper.buildUnitTestSlackNotificationMessage())
}
}

最新更新