
Gradle 默认的 test 任务仅显示简单类名(如 ExampleSpec),不包含包路径;本文介绍通过配置 afterTest 钩子与 testLogging,实现带包名的清晰测试日志(如 com.company.ExampleSpec > get all examples PASSED),并支持彩色状态标识。
gradle 默认的 `test` 任务仅显示简单类名(如 `examplespec`),不包含包路径;本文介绍通过配置 `aftertest` 钩子与 `testlogging`,实现带包名的清晰测试日志(如 `com.company.examplespec > get all examples passed`),并支持彩色状态标识。
Gradle 原生不提供直接开启“全限定类名”日志的开关,但可通过 Test 任务的 afterTest 生命周期钩子完全接管单个测试用例的输出逻辑,从而精准控制格式。以下为推荐配置(适用于 Gradle 7.0+,基于 JUnit Platform):
test {
useJUnitPlatform() // 推荐显式声明,确保兼容 JUnit 5
// 精简默认日志,仅在失败时输出异常详情
testLogging {
events "failed"
showExceptions true
exceptionFormat "full"
showCauses true
showStackTraces true
}
// 自定义每个测试执行后的输出:强制显示全限定类名 + 彩色状态
afterTest { descriptor, result ->
String className = descriptor.className ?: "unknown"
String testName = descriptor.name ?: "unknown"
String status
if (result.resultType == org.gradle.api.tasks.testing.TestResult.ResultType.FAILURE) {
status = "${ANSI_RED}FAILED${ANSI_RESET}"
} else if (result.resultType == org.gradle.api.tasks.testing.TestResult.ResultType.SKIPPED) {
status = "${ANSI_YELLOW}SKIPPED${ANSI_RESET}"
} else {
status = "${ANSI_GREEN}PASSED${ANSI_RESET}"
}
println "${className} > ${testName} ${status}"
}
}
// ANSI 颜色常量(可选,提升可读性)
def ANSI_RESET = "\u001B[0m"
def ANSI_RED = "\u001B[31m"
def ANSI_GREEN = "\u001B[32m"
def ANSI_YELLOW = "\u001B[33m"
✅ 关键说明:
-
descriptor.className天然返回全限定名(如com.company.ExampleSpec),无需额外解析; -
afterTest在每个测试方法执行后触发,比testLogging.events更底层、更可控; - 保留原生
testLogging配置(如showExceptions true)可确保失败时仍输出完整堆栈,避免信息丢失; - 颜色仅在支持 ANSI 的终端(如 IntelliJ Terminal、iTerm2、WSL)中生效;若需禁用颜色,可移除 ANSI 常量并直接使用纯文本(如
"PASSED")。
⚠️ 注意事项:
- 此方案会覆盖 Gradle 默认的简洁成功日志(如
> Task :test PASSED),但显著提升大型项目中定位测试归属的效率; - 若项目混合使用 JUnit 4 和 JUnit 5,请确保
useJUnitPlatform()已启用(JUnit 4 测试将自动桥接到 Platform); - Gradle 8.0+ 中
TestResult.ResultType枚举值保持兼容,但建议始终使用result.resultType而非已弃用的failedTestCount等计数器判断状态——后者在afterTest中不可靠(因统计尚未汇总)。
通过以上配置,你将获得结构统一、语义明确、开箱即用的测试输出,大幅提升团队协作与 CI 日志可读性。











