1 JaCoCo介绍
JaCoCo是EclEmma团队基于多年覆盖率库使用经验总结而研发的一个开源的Java代码覆盖率库。
2 JaCoCo覆盖率计数器
3 Gradle单模块接入
在工程的buid.gradle文件中添加如下内容:
//Applying the JaCoCo plugin plugins { id 'jacoco' } // Configuring JaCoCo plugin settings jacoco { toolVersion = "0.8.4" //reportsDir = file("$buildDir/customJacocoReportDir") } //Configuring test task jacocoTestReport { reports { xml.enabled false csv.enabled false html.enabled true //html.destination file("${buildDir}/jacocoHtml") } } check.dependsOn jacocoTestReport
编译完成后会在 ${buildDir}/build/reports/jacoco下生成报告。
如果在Spring Boot的框架下运行,需要在build.gradle中加下面一段,否则执行jacocoTestReport task会被skipped。
tasks.withType(Test) { scanForTestClasses = false include "**/*Test.class" }
4 Gradle多模块接入
在父子工程的buid.gradle文件中添加如下内容,注意父和子都要添加:
//Applying the JaCoCo plugin apply plugin:'jacoco' // Configuring JaCoCo plugin settings jacoco { toolVersion = "0.8.4" //reportsDir = file("$buildDir/customJacocoReportDir") } //Configuring test task jacocoTestReport { reports { xml.enabled false csv.enabled false html.enabled true //html.destination file("${buildDir}/jacocoHtml") } } check.dependsOn jacocoTestReport
编译完成后会在对应的子工程的 ${buildDir}/build/reports/jacoco下生成报告。
5 Maven单模块接入
在工程的pom.xml文件中添加如下内容:
org.jacoco jacoco-maven-plugin 0.8.4 <id>jacoco-initializeid> prepare-agent <id>jacoco-siteid> package report
执行Run As Maven build:
clean install
在项目target/site/jacoco目录下找到index.html文件,即可查看报告。
6 Maven多模块接入
Maven多模块是指存在父子关联的项目,这类项目中存在多个pom.xml文件,父项目pom.xml文件中包括多个
6.1 父pom中增加依赖
在多模块项目中找到父pom.xml文件,添加如下内容:
org.jacoco jacoco-maven-plugin 0.8.4
6.2 新建子覆盖率模块
该模块添加所有要进行单元测试的子工程的依赖,例如,新增一个jacoco-coverage的子模块,在pom.xml文件里添加如下内容:
增加
org.sonatype.mavenbook.multi simple-weather 1.0.0-SNAPSHOT org.sonatype.mavenbook.multi simple-webapp/artifactId> 1.0.0-SNAPSHOT
添加jacoco-maven-plugin
org.jacoco jacoco-maven-plugin 0.8.4 <id>jacoco-initializeid> prepare-agent verify report-aggregate
6.3 父pom中增加该模块
simple-weather simple-webapp jacoco-coverage
执行Run As Maven build:
clean install
在子项目jacoco-coverage生成的target/site/jacoco-aggregate目录下找到index.html文件并打开即可查看报告。
以下给出一个官网提供的报告: