You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Gradle JVM测试套件未检测到测试时如何配置构建失败?

解决Gradle测试套件无测试时构建失败的问题

你遇到的问题是:当没有找到任何测试时,afterSuite闭包不会执行——因为Gradle在无测试执行的场景下不会触发这个回调。可以通过以下两种方式实现需求:

方式一:监听测试任务的finished事件

testing {
    suites {
        val integrationTest by registering(JvmTestSuite::class) {
            testType = TestSuiteType.INTEGRATION_TEST

            targets {
                all {
                    testTask.configure {
                        finished { result ->
                            if (result.testCount == 0L) {
                                throw IllegalStateException("未找到任何集成测试,构建失败")
                            }
                        }
                    }
                }
            }
        }
    }
}

方式二:使用doLast直接检查测试结果

这种方式更直观,适配Gradle 7.x及以上版本:

testing {
    suites {
        val integrationTest by registering(JvmTestSuite::class) {
            testType = TestSuiteType.INTEGRATION_TEST

            targets {
                all {
                    testTask.configure {
                        doLast {
                            if (testResult.testCount == 0L) {
                                throw IllegalStateException("未找到任何集成测试,构建失败")
                            }
                        }
                    }
                }
            }
        }
    }
}

原理说明

  • afterSuite回调仅在存在至少一个测试套件(含子套件)执行时才会触发,无测试时不会执行。
  • finished事件会在测试任务完成后无条件触发,无论是否有测试执行。
  • doLast块会在测试任务的所有动作完成后执行,此时可直接通过testResult获取任务的测试结果统计。

内容的提问来源于stack exchange,提问作者pixel

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.13 18:22:04