11plugins  {
22    //  Core Gradle plugins
33    id " java-gradle-plugin" 
4+     id " jacoco" 
45
56    //  Third-party plugins
67    alias(libs. plugins. kotlinJvm)
@@ -23,6 +24,13 @@ java {
2324    targetCompatibility =  JavaVersion . VERSION_1_8 
2425}
2526
27+ jacocoTestReport  {
28+     reports {
29+         xml. required =  true 
30+         csv. required =  false 
31+     }
32+ }
33+ 
2634plugins. withId(" com.vanniktech.maven.publish"  ) {
2735    mavenPublish {
2836        sonatypeHost =  " S01" 
@@ -76,3 +84,47 @@ dependencies {
7684    testImplementation gradleTestKit()
7785    testImplementation libs. mockk
7886}
87+ 
88+ //  Setup Jacoco for Gradle TestKit
89+ pluginManager. withPlugin(" jacoco"  ) {
90+ 
91+     //  Extracts the JaCoCo runtime jar from the configured JaCoCo Agent
92+     def  extractJacocoRuntimeTask =  tasks. register(" extractJacocoTestKitRuntime"  , Copy ) {
93+         from {
94+             zipTree(project. configurations. getByName(JacocoPlugin . AGENT_CONFIGURATION_NAME ). asPath). matching { include ' jacocoagent.jar'   }. singleFile
95+         }
96+         into file(" ${ buildDir}  /testkit"  )
97+     }
98+ 
99+     def  javaTestTask =  tasks. named(JavaPlugin . TEST_TASK_NAME )
100+ 
101+     def  destinationFileProvider =  javaTestTask. map {
102+         (it. extensions. getByType(JacocoTaskExtension . class) as  JacocoTaskExtension ). destinationFile
103+     }
104+ 
105+     //  Generates a gradle.properties file that contains the correct JVM arguments to run with the extracted JaCoCo agent
106+     def  generateGradlePropertiesTask =  tasks. register(" generateJacocoTestKitGradleProperties"  , WriteProperties . class) {
107+         it. group =  " reporting" 
108+         it. description =  " Generates testkit-gradle.properties file which can be read and added to a TestKit build as gradle.properties" 
109+         it. dependsOn(extractJacocoRuntimeTask)
110+         it. outputFile =  new  File (buildDir, " testkit/${ javaTestTask.name}  /gradle.properties"  )
111+         it. property(" org.gradle.jvmargs"  , " \" -javaagent:${ buildDir}  /testkit/jacocoagent.jar=destfile=${ destinationFileProvider.get()} \" "  )
112+     }
113+ 
114+     //  Make the generated gradle.properties file available on the test classpath as resource
115+     dependencies. add(JavaPlugin . TEST_RUNTIME_ONLY_CONFIGURATION_NAME , files(new  File (buildDir, " testkit/${ javaTestTask.name} "  )))
116+ 
117+     //  "Fixes": https://github.com/gradle/gradle/issues/16603
118+     def  jacocoTestReport =  tasks. named(" jacocoTestReport"  )
119+     jacocoTestReport. configure {
120+         it. doFirst {
121+             sleep(1000 )
122+         }
123+     }
124+ 
125+     //  Setup task dependencies
126+     javaTestTask. configure {
127+         it. dependsOn(generateGradlePropertiesTask)
128+         it. finalizedBy(jacocoTestReport)
129+     }
130+ }
0 commit comments