shutdown jvm時(shí)dump出覆蓋率數(shù)據(jù)
1.下載jacoco:http://www.eclemma.org/jacoco/
2.對(duì)于tomcat,在catalina.sh的JAVA_OPTS配置中增加:
-javaagent:/home/work/local/jacoco/lib/jacocoagent.jar=includes=com.xxx.*
其中 includes:表示針對(duì)指定的class進(jìn)行覆蓋率數(shù)據(jù)收集,其他參數(shù): append=true/false:每一次收集的覆蓋率數(shù)據(jù)是追加還是替換,不設(shè)置默認(rèn)為true destfile=jacoco.exec:dump出來(lái)的覆蓋率數(shù)據(jù)文件output=file/tcpserver/tcpclient:覆蓋率數(shù)據(jù)輸出的形式,分別為file,tcpserver和tcpclient,file是比較簡(jiǎn)單的方式,tcp的方式可支持自行開(kāi)發(fā)獲取覆蓋率數(shù)據(jù)的工具。不設(shè)置默認(rèn)是file。
3.注意采用output=file的方式下,是在jvm停掉時(shí)將覆蓋率數(shù)據(jù)dump出來(lái)到文件,在shutdown tomcat后不能kill -9 java,只殺掉tomcat進(jìn)程,否則數(shù)據(jù)收集無(wú)效
4.生成覆蓋率數(shù)據(jù)需要ant執(zhí)行,build.xml實(shí)例如下:指定第3步dump出的exec文件之后,執(zhí)行antjacoco,就會(huì)在指定路徑輸出html格式覆蓋率報(bào)告
<?xml version="1.0" ?>
<project name="testExec" xmlns:jacoco="antlib:org.jacoco.ant" default=" jacoco">
<property name="srcPath" value="src/main/java"/>
<property name="classPath" value="target/classes"/>
<property name="jacocoantPath" value=""/>
<property name="jacocoexecPath" value="./merged.exec"/>
<property name="workspacePath" value="."/>
<property name="reportfolderPath" value="./report"/>
<property name="server_ip" value=""/>
<property name="server_port" value=""/>
<taskdef uri="antlib:org.jacoco.ant" resource="org/jacoco/ant/ antlib.xml">
<classpath path="${jacocoantPath}" />
</taskdef>
<target name="merge">
<jacoco:merge destfile="merged.exec">
<fileset dir="${workspacePath}" includes="**/*.exec"/>
</jacoco:merge>
</target>
<target name="dump">
<jacoco:dump address="${server_ip}" reset="false" destfile=" ${jacocoexecPath}" port="${server_port}" append="true"/>
</target>
<target name="jacoco">
<delete dir="${reportfolderPath}" />
<mkdir dir="${reportfolderPath}" />
<jacoco:report>
<executiondata>
<file file="${jacocoexecPath}" />
</executiondata>
<structure name="JaCoCo Report">
<group name="ad">
<classfiles>
<fileset dir="${classPath}" />
</classfiles>
<sourcefiles encoding="gbk">
<fileset dir="${srcPath}" />
</sourcefiles>
</group>
</structure>
<html destdir="${reportfolderPath}" encoding="utf-8" />
</jacoco:report>
</target>
</project>
不停jvm dump出覆蓋率數(shù)據(jù)
在配置JAVA_OPTS的參數(shù)時(shí),修改如下:
-javaagent:/home/work/local/jacoco/jacocoagent.jar=includes=com.xx.*,output=tcpserver,port=10001,address=100.100.100.100
這樣的方式下啟動(dòng)tomcat之后,jacoco會(huì)在一個(gè)端口上提供client訪問(wèn),并能dump出此時(shí)的覆蓋率數(shù)據(jù)文件,dump的方式仍然是ant執(zhí)行,build.xml中有這樣一段:
<target name="dump">
<jacoco:dumpaddress="${server_ip}" reset="false"destfile="${jacocoexecPath}" port="${server_port}"append="true"/>
</target>
需要配置server的ip和端口,執(zhí)行ant dump,輸出的還是exec文件,再執(zhí)行ant jacoco會(huì)生成html報(bào)告