有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java在所有项目中运行单元测试,即使有些项目失败了

我有一个多模块的Gradle项目。我希望它能够正常编译和执行所有其他任务。但是对于单元测试,我希望它能够运行所有的测试,而不是在早期项目中的一个测试失败时立即停止

我试着加上

buildscript {
    gradle.startParameter.continueOnFailure = true
}

这对测试有效,但如果出现故障,编译也会继续。那不好

我是否可以将Gradle配置为仅针对测试任务继续


共 (2) 个答案

  1. # 1 楼答案

    在mainbuild.gradle中尝试类似的方法,并让我知道,我已经用一个小的pmulti项目测试了它,并且似乎做了您需要的事情

    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 ! ")
        }
    
    }
    
  2. # 2 楼答案

    测试失败后,我将@LazerBanana答案更改为取消下一个任务

    通常所有的发布都是在所有测试之后开始的(例如,Artifactory插件就是这样做的)。因此,与其构建失败,不如添加全局任务,它将位于测试和发布(或运行)之间。 因此,您的任务顺序应该如下所示:

    1. 编译每个项目
    2. 测试每个项目
    3. 收集所有项目的测试结果并使构建失败
    4. 发布工件、通知用户等

    其他项目:

    1. 我避免使用AntFail。为此目的,存在梯度例外
    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)