Reference Tasks via configurations

In the gradle documentation, I found the following snippet, to be able to “produce” jacoco-rest-reports for individual subprojects. Furtherfmore I do have an additional test-task (integrationTest), which is now handled in the following code-snippet as well.

 // This will cause the test task to run if the coverage data is requested by the aggregation task
 outgoing.artifact(tasks.test.map { task ->
    task.extensions.getByType<JacocoTaskExtension>().destinationFile!!
})
outgoing.artifact(tasks.named<Test>("integrationTest").map { task ->
    task.extensions.getByType<JacocoTaskExtension>().destinationFile!!
})

This works fine, as long as the corresponding task is “added” to the projects before adding the above configuration. Now I tried to solve this “issue” by using the following:

tasks.withType<Test>().forEach { task ->
    outgoing.artifact(task.extensions.getByType<JacocoTaskExtension>().destinationFile!!)
}

Unfortunately now my test-tasks are not executed anymore, if I do call the aggregateJacocoTestReport-Task.
I am pretty sure, that the “TaskProvider.map()” function is what I am missing in the latter solution. So my question is now, how to “solve” my problem.

Any help is appreciated.