簡體   English   中英

在所有項目中運行單元測試,即使有些項目失敗

[英]Run unit tests in all projects, even if some fail

我有一個多模塊Gradle項目。 我希望它能夠正常編譯並執行所有其他任務。 但對於單元測試,我希望它能夠運行所有這些,而不是在早期項目中的一個測試失敗時立即停止。

我試過添加

buildscript {
    gradle.startParameter.continueOnFailure = true
}

它適用於測試,但如果出現故障,也會繼續編譯。 那不行。

我可以配置Gradle繼續,僅用於測試任務嗎?

在main build.gradle嘗試類似這樣的東西並讓我知道,我已經用一個小的pmultiproject測試了它,似乎做了你需要的東西。

ext.testFailures = 0 //set a global variable to hold a number of failures

gradle.taskGraph.whenReady { taskGraph ->

    taskGraph.allTasks.each { task -> //get all tasks
        if (task.name == "test") { //filter it to test tasks only

            task.ignoreFailures = true //keepgoing if it fails
            task.afterSuite { desc, result ->
                if (desc.getParent() == null) {
                    ext.testFailures += result.getFailedTestCount() //count failures
                }
            }
        }
    }
}

gradle.buildFinished { //when it finishes check if there are any failures and blow up

    if (ext.testFailures > 0) {
        ant.fail("The build finished but ${ext.testFailures} tests failed - blowing up the build ! ")
    }

}

測試失敗后,我更改了@LazerBanana的答案以取消下一個任務。

通常所有發布都在所有測試之后開始(作為示例 - Artifactory插件執行此操作)。 因此,最好是在測試和發布(或運行)之間添加全局任務,而不是構建失敗。 所以,你的任務序列應該是這樣的:

  1. 編譯每個項目
  2. 測試每個項目
  3. 在所有項目上收集測試結果並使構建失敗
  4. 發布工件,通知用戶等

附加項目:

  1. 我避免使用Ant Fail。 為此目的有GradleException
  2. testCheck任務按照gradle的建議執行doLast部分中的所有代碼

碼:

ext.testFailures = 0 //set a global variable to hold a number of failures

task testCheck() {
    doLast {
        if (testFailures > 0) {
            message = "The build finished but ${testFailures} tests failed - blowing up the build ! "
            throw new GradleException(message)
        }
    }
}

gradle.taskGraph.whenReady { taskGraph ->

    taskGraph.allTasks.each { task -> //get all tasks
        if (task.name == "test") { //filter it to test tasks only

            task.ignoreFailures = true //keepgoing if it fails
            task.afterSuite { desc, result ->
                if (desc.getParent() == null) {
                    ext.testFailures += result.getFailedTestCount() //count failures
                }
            }

            testCheck.dependsOn(task)
        }
    }
}    

// add below tasks, which are usually executed after tests
// as en example, here are build and publishing, to prevent artifacts upload
// after failed tests
// so, you can execute the following line on your build server:
// gradle artifactoryPublish
// So, after failed tests publishing will cancelled
build.dependsOn(testCheck)
artifactoryPublish.dependsOn(testCheck)
distZip.dependsOn(testCheck)
configureDist.dependsOn(testCheck)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM