如何在覆盖率太低时让 Jenkins 阶段失败并变红(使用 C# 和 dotnet 测试)?

How to make Jenkins stage fail and turn red when coverage is too low (using C# and dotnet test)?

我正在使用 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 构建失败。到目前为止,一切都很好。

但是当构建因此而失败时,它是用户敌对的并且很难理解原因。 'Run unit tests' 舞台在 Blue Ocean 中是绿色的。

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

如果 publishCoverage 为真,您可以将 currentBuild.result 设置为 FAILUREcurrentBuild.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%"
            }
        }
    }
}

受到 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.")
                }
            }
        }
    }
}