build.gradle - Fail tests in Gradle JVM Test Suite when no tests are found? - Stack Overflow

admin2025-04-09  1

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.

Share Improve this question asked Mar 25 at 10:42 pixelpixel 26.5k39 gold badges168 silver badges285 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 0

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.")
                            }
                        }
                    }
                }
            }
        }
    }
}
转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1744203228a235899.html

最新回复(0)