Custom task to execute all unit tests in all modules

I would like to write a custom task for an Android application project with multiple Gradle modules which executes the unit tests in the following modules so I can run all of them with one Gradle task invocation:

  • Android application module, e.g. testOrangeDebugUnitTest
  • Android library modules, e.g. testDebug
  • Java/Kotlin library modules, e.g. test

Requirements

  1. It would be convenient to being able to configure one product flavor (e.g. “orange”) to being tested (running all would take too long).
  2. Also, running Android unit tests with the debug product type is sufficient.
  3. Modules names should not be hardcoded so that the project is extensible and tests in new modules are picked up automatically.

What would be a modern way to declare and register the task in a Groovy build script? Something like …

tasks.register("testAllModules") {
    group = "verification"
    description = "Runs all unit tests of all modules."
    // ...
}

Related