1

我正在使用 C#、coverlet.msbuild 和 Jenkins Cobertura 适配器。我的 Jenkinsfile 中大致有这个:

stage ('Run unit tests') {
    steps {
        powershell "dotnet test -c:Release /p:CollectCoverage=true /p:CoverletOutputFormat=cobertura --no-build --no-restore --logger trx"
    }
    post {
        always {
            step([$class: 'MSTestPublisher'])
            publishCoverage failUnhealthy: true, 
                globalThresholds: [[thresholdTarget: 'Package', unhealthyThreshold: 50.0]],
                adapters: [coberturaAdapter(
                    mergeToOneReport: true, 
                    path: '**/*.cobertura.xml')]
        }
    }
}

如果包级别的覆盖率低于 50%,这会使我的 Jenkins 构建失败。到现在为止还挺好。

但是,当构建因此而失败时,它是对用户不利的并且很难理解为什么。Blue Ocean 中的“运行单元测试”阶段为绿色。

当构建失败时,我可以让这个阶段变成红色,以便更容易看到错误是什么?

4

2 回答 2

1

受到 Sers 的答案和我阅读的其他一些 Jenkinsfile 代码的启发,我得到了这个解决方案,它可以满足我的需求:

stage ('Run unit tests') {
    steps {
        powershell "dotnet test -c:Release /p:CollectCoverage=true /p:CoverletOutputFormat=cobertura --no-build --no-restore --logger trx"
    }
    post {
        always {
            step([$class: 'MSTestPublisher'])
            publishCoverage failUnhealthy: true, 
                globalThresholds: [[thresholdTarget: 'Package', unhealthyThreshold: 50.0]],
                adapters: [coberturaAdapter(
                    mergeToOneReport: true, 
                    path: '**/*.cobertura.xml')]
            script {
                if (currentBuild.result == 'FAILURE') {
                    error("Test coverage is too low.")
                }
            }
        }
    }
}
于 2020-01-21T08:16:42.750 回答
0

您可以设置currentBuild.resultFAILURE如果publishCoverage为真。currentBuild.displayNamecurrentBuild.description可选的:

post {
    always {
        script {
            def failed = publishCoverage (failUnhealthy: true, 
                        globalThresholds: [[thresholdTarget: 'Package', unhealthyThreshold: 50.0]],
                        adapters: [coberturaAdapter(
                            mergeToOneReport: true, 
                            path: '**/*.cobertura.xml')])
            if (failed) {
                currentBuild.result = 'FAILURE'
                currentBuild.displayName = "${currentBuild.displayName} Coverage"
                currentBuild.description = "Coverage lower than 50%"
            }
        }
    }
}
于 2020-01-16T12:19:52.570 回答