I want to configure my Gradle test suite to fail if no tests are found.
I tried to define such behavior in afterSuite
block:
testing {
suites {
val integrationTest by registering(JvmTestSuite::class) {
testType = TestSuiteType.INTEGRATION_TEST
targets {
all {
testTask.configure {
afterSuite(KotlinClosure2({ _: TestDescriptor, result: TestResult ->
if (result.testCount == 0L) {
throw IllegalStateException("No tests were found. Failing the build")
}
}))
}
}
}
}
}
}
but logic in the afterSuite
is not executed.
I want to configure my Gradle test suite to fail if no tests are found.
I tried to define such behavior in afterSuite
block:
testing {
suites {
val integrationTest by registering(JvmTestSuite::class) {
testType = TestSuiteType.INTEGRATION_TEST
targets {
all {
testTask.configure {
afterSuite(KotlinClosure2({ _: TestDescriptor, result: TestResult ->
if (result.testCount == 0L) {
throw IllegalStateException("No tests were found. Failing the build")
}
}))
}
}
}
}
}
}
but logic in the afterSuite
is not executed.
You need to know that the afterSuite
and beforeSuite
callbacks in Gradle's Test task are only invoked after at least one test suite is discovered. If no tests are found at all, these callbacks are never getting executed, which is exactly what you are experiencing.
Fix: Use doLast
on the test task:
To explicitly fail the build when no tests are found, even when zero tests are discovered, you can use doLast {}
to check the test results after the test task has run like this:
testing {
suites {
val integrationTest by registering(JvmTestSuite::class) {
testType = TestSuiteType.INTEGRATION_TEST
targets {
all {
testTask.configure {
doLast {
if (testResult.result.testCount == 0L) {
throw GradleException("No tests were found. Failing the build.")
}
}
}
}
}
}
}
}