一.下载jacoco, ant工具
jacoco: http://www.eclemma.org/jacoco/;
ant: http://ant.apache.org 并添加到环境变量;
二.不停jvm, dump出覆盖率数据
在部署的tomcat服务中,/bin/catalina.sh中JAVA_OPTS参数值添加:
-javaagent:/data1/jacoco/lib/jacocoagent.jar=includes=*,output=tcpser
ver,port=2014,address=10.210.230.26
其中:/data1/jacoco/lib/jacocoagent.jar为安装jacoco的jacocoagent.jar包绝对路径;output覆盖率数据输出的形式,有file, tcpserver, tcpclient, 默认是file,file是在jvm停掉时才将覆盖率数据dump出来;address和port可以提供client访问,并dump出覆盖率数据文件, 在build.xml会使用。
启动tomcat服务,sh /bin/startup.sh; 假设tomcat服务为10.210.230.26:8074
三.使用自动化测试跑该tomcat服务
四.ant的build.xml
- <?xml version="1.0" encoding="UTF-8" ?>
- <project name="testCodeCoveage" xmlns:jacoco="antlib:org.jacoco.ant" default="report">
- <property name="result.dir" location="/data1/hugang/tomcat/apache-tomcat-8.0.36/webapps/ROOT/WEB-INF" />
- <property name="result.classes.dir" location="${result.dir}/classes" />
- <property name="result.report.dir" location="/data1/hugang/jacocoresult/" />
- <property name="result.exec.file" location="./remote.exec" />
- <property name="resource.code" location="/data1/hugang/jacoco/sourcecode/apiservice-java-strategyapi/src/main/java/" />
- <!-- Import JaCoCo Ant tasks, taskdef第三方target -->
- <taskdef uri="antlib:org.jacoco.ant" resource="org/jacoco/ant/antlib.xml">
- <classpath path="/data1/hugang/jacoco/lib/jacocoant.jar" />
- </taskdef>
- <!--tomcat下bin/catalina.sh在JAVA_OPTS参数新加的
- -javaagent:/data1/jacoco/lib/jacocoagent.jar=includes=*,output=tcpser
- ver,port=2014,address=10.210.230.26会在这个端口上提供client访问,并能dump出此时的覆盖率数据文件:destfile-->
- <target name="dump">
- <jacoco:dump address="10.210.230.26" reset="false" destfile="${result.exec.file}" port="2014" append="false"/>
- </target>
- <target name="report" depends="dump">
- <!-- Create coverage report -->
- <jacoco:report>
- <!-- This task needs the collected execution data and ... -->
- <executiondata>
- <file file="${result.exec.file}" />
- </executiondata>
- <!-- the class files and optional source files ... -->
- <structure name="apiservice-java-strategyapi">
- <group name="strategy">
- <classfiles>
- <fileset dir="${result.classes.dir}"/>
- <!-- 可以指定jar包 -->
- <!-- include name="*.jar" -->
- </classfiles>
- <sourcefiles encoding="UTF-8">
- <fileset dir="${resource.code}"/>
- </sourcefiles>
- </group>
- </structure>
- <!-- to produce reports in different formats. -->
- <html destdir="${result.report.dir}" />
- </jacoco:report>
- </target>
- </project>
执行: ant -v
最后在 destdir路径下 /data1/hugang/jacocoresult/
生成html报告
五.展示报告
将报告文件,放到apache服务器下,直接访问html,如下:
参考:http://www.eclemma.org/jacoco/trunk/doc/ant.html