How to run custom Gradle task on specific build variant?

I am trying to consolidate or merge unit test report into single HTML file, I was able to do it with TestReport. However it seems the task execute both testDebugUnitTest and testReleaseUnitTest` hence I am getting twice report of test cases.

tasks.register<TestReport>("consolidateReport") {
    description = "Custom Gradle task for consolidating test report"
    group = "Custom Tasks"

    destinationDirectory.set(file("$rootDir/app/build/consolidated/tests/unitTest"))
    // Combine all 'test' task results into a single HTML report
    testResults.from(allprojects.map {
        it.tasks.withType(Test::class)
    })
}

Usage
./gradlew consolidateReport


I tried the below but it does not work. I play around to check more and it seems the variant that is only running is debug.

applicationVariants.all {
        // Extract variant name and capitalize the first letter
        val variantName = name.replaceFirstChar {
            if (it.isLowerCase()) it.titlecase(Locale.getDefault()) else it.toString()
        }
        // Define task names for unit tests and Android tests
        val unitTests = "test${variantName}UnitTest"
        val androidTests = "connected${variantName}AndroidTest"

        tasks.register<TestReport>("consolidate${variantName}Report") {
            // Depend on unit tests and Android tests tasks
            dependsOn(listOf(unitTests, androidTests))
            description = "Custom Gradle task for consolidating test report"
            group = "Custom Tasks"

            destinationDirectory.set(file("$rootDir/app/build/consolidated/tests/unitTest"))
             allprojects.map {
                it.tasks.withType(Test::class)
            }.filter { it.any {
                println(it.debug)
                true
            } }
            // Combine all 'test' task results into a single HTML report
            testResults.from(allprojects.map {
                it.tasks.withType(Test::class)
            }.filter { it.any {
                println(variantName)
                it.name.contains(variantName, true)
            } })
        }
    }
false
false
false
false
false
false
Debug
Debug
Debug
Debug
Debug
Debug

Now I really have no idea what is happening.

All the “allprojects” trickery, reaching into other projects model and getting tasks or anyhting else from there is highly problematic and highly discouraged.

Even while the test report aggregation plugin does not integrate with the android setup of builds, the tactic it uses is exactly the way to safely share the test results with other projects and then aggregate them, so you should do it like the plugin does for normal JVM projects.

I actually initially use subprojects and put this code in the root/project level build.gradle. I just tried to move it in app module in hopes to only execute the task in debug build variant.

Using subprojects is not any better than using allprojects. :wink: