Introducing dependencies to all test tasks

For a given project I’d like to configure jacoco so that all tasks of type Test need to run before jacocoTestCoverageVerification. Using the following snippet I managed to declare this dependency, and in another place I also configured jacoco to make use of all “execution data” files.

tasks.withType<Test>().configureEach {
    tasks.getByName("jacocoTestCoverageVerification").dependsOn(this)
}

Instead of getByName I tried to use withType:

tasks.withType<Test>().configureEach {
    val testTask = this
    tasks.withType<JacocoCoverageVerification>().configureEach {
        dependsOn(testTask)
    }
}

While syntactically correct, this doesn’t work:

> Could not create task ':application:test'.
   > DefaultTaskCollection#configureEach(Action) on task set cannot be executed in the current context.

I don’t understand why the first approach works, and why the second does not. I guess “withType” may only be used on the outer layer to initialize lazy computation of the task graph?

Bonus question, when I try to reverse the order (“jacocoTestCoverageVerification” at the outer layer), would it be possible to add constraints referencing Test tasks created “later”, i.e. based on convention plugins only included/parsed/run (?) after this jacoco specific code has been considered? [Less confusing: assuming I add a new Test task type somewhere else, would this be picked up by my jacoco config?]

I’m too lazy to think about the failure reason, but just use this:

tasks.withType<JacocoCoverageVerification>().configureEach {
    dependsOn(tasks.withType<Test>())
}

:slight_smile:

1 Like