Kotlin+Java Maven项目Jacoco无法统计Kotlin测试的Kotlin类覆盖率
Hey there, let's work through why your Kotlin tests aren't contributing to Jacoco coverage stats for Kotlin classes. After looking at your pom.xml, here's the root issue and step-by-step fixes:
问题根源
Your Jacoco setup correctly captures coverage from Java tests, but Kotlin tests aren't being monitored by the Jacoco agent during execution. This is likely because the Maven Surefire plugin isn't configured to run Kotlin test classes or pass along Jacoco's required JVM arguments.
具体修复步骤
1. 添加并配置Maven Surefire插件
Your pom is missing an explicit maven-surefire-plugin configuration. By default, Surefire might only scan for Java test classes and won't use Jacoco's agent parameters. Add this to your <build><plugins> section:
<plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-surefire-plugin</artifactId> <version>3.0.0-M5</version> <configuration> <!-- Pass Jacoco's agent arguments to the test JVM --> <argLine>${argLine}</argLine> <!-- Ensure both Java and Kotlin test classes are executed --> <includes> <include>**/*Test.java</include> <include>**/*Test.kt</include> </includes> </configuration> </plugin>
2. 确认Jacoco Prepare-Agent配置
Your existing Jacoco prepare-agent setup is correct, but double-check that it's setting up the agent properly (it automatically populates the ${argLine} variable used by Surefire):
<execution> <id>pre-unit-test</id> <goals> <goal>prepare-agent</goal> </goals> <configuration> <destFile>${basedir}/target/coverage-reports/jacoco-ut.exec</destFile> </configuration> </execution>
3. 优化编译顺序(可选,提升稳定性)
To avoid any cross-compilation issues between Java and Kotlin, ensure Kotlin code compiles before Java code. Adjust the compile execution phase in your kotlin-maven-plugin:
<execution> <id>compile</id> <phase>process-sources</phase> <goals> <goal>compile</goal> </goals> <configuration> <sourceDirs> <sourceDir>${project.basedir}/src/main/kotlin</sourceDir> <sourceDir>${project.basedir}/src/main/java</sourceDir> </sourceDirs> </configuration> </execution>
验证修复
Run this Maven command to regenerate coverage reports:
mvn clean verify
Check the HTML report in target/jacoco-ut-report—you should now see coverage data from Kotlin tests for your Kotlin classes. If issues persist, verify that the jacoco-ut.exec file is generated in target/coverage-reports and check Surefire logs to confirm Kotlin tests are being executed.
内容的提问来源于stack exchange,提问作者Igor Sidorov

