Cobertura通过junit统计一般Java工程的代码覆盖率,网上都有介绍,这里主要介绍Cobertura怎么统计OSGI的bundle运行的代码覆盖率
OSGI启动有多种方式:
1、在Eclipse通过launch启动
2、通过命令行启动:java -jar org.eclipse.osgi_3.7.2.v20120110-1415.jar
3、通过eclipse.exe启动。
启动方式介绍参考另外一篇文档。这里主要是使用第二种方式启动,统计覆盖率。
第二种方式下,部署方式:
bundles中包含所有的bundle
startup.bat内容:
java -jar org.eclipse.osgi_3.7.2.v20120110-1415.jar -console 8088
其中的-console 8088是为后续通过控制台控制、关闭osgi做准备的。
Cobertura统计覆盖率,是需要将要统计的代码对应的class进行打桩的,同样,bundle代码也不例外。
我们创建了两个bundle,来统计这两个bundle的 覆盖率:
MainFrame
Word2Excel001
所以需要把上面两个工程编译出的class打桩后放入bundle中。
这样,如果不做其他事情,bundle是无法启动的,因为大桩后的bundle是要依赖Cobertura.jar的。
所以需要制作一个bundle,包装Cobertura.jar。然后打桩的bundle要依赖这个bundle。
在MainFrame和Word2Excel001的MANIFEST中添加一行:
Require-Bundle: WithCobertura
这样bundle就可以启动了。
最后,整个ant脚本内容是:
<project name="cuberturaOSGi1" default="main">
<path id="cobertura.classpath">
<pathelement location="lib/cobertura.jar" />
<pathelement location="lib/asm-3.0.jar" />
<pathelement location="lib/asm-tree-3.0.jar" />
<pathelement location="lib/log4j-1.2.9.jar" />
<pathelement location="lib/jakarta-oro-2.0.8.jar" />
</path>
<taskdef classpathref="cobertura.classpath" resource="tasks.properties" />
<target name="main" depends="report">
</target>
<!--输出报告哦啊-->
<target name="report" depends="runOSGI">
<delete dir="../reportdir" />
<mkdir dir="../reportdir" />
<cobertura-report srcdir="E:\Kevin\Workspace\TCM\src" destdir="../reportdir"/>
</target>
<!--启动OSGI程序-->
<target name="runOSGI" depends="instrument">
<mkdir dir="reportdir" />
<java jar="E:\Kevin\Workspace\TCM\Runtime\org.eclipse.osgi_3.7.2.v20120110-1415.jar" fork="true">
<arg value="-console"/>
<arg value="8088"/>
</java>
</target>
<!--打桩class-->
<target name="instrument">
<delete dir="E:\Kevin\Workspace\TCM\Runtime\bundles\MainFrame\com" />
<delete dir="E:\Kevin\Workspace\TCM\Runtime\bundles\Word2Excel001\com" />
<cobertura-instrument todir="E:\Kevin\Workspace\TCM\Runtime\bundles\MainFrame">
<fileset dir="E:\Kevin\Workspace\TCM\Projects\MainFrame\bin">
<include name="**/*.class"/>
</fileset>
</cobertura-instrument>
<cobertura-instrument todir="E:\Kevin\Workspace\TCM\Runtime\bundles\Word2Excel001">
<fileset dir="E:\Kevin\Workspace\TCM\Projects\Word2Excel001\bin">
<include name="**/*.class"/>
</fileset>
</cobertura-instrument>
</target>
</project>
所有工程代码和样例路径:点击打开链接
参考资料:
http://kaczanowscy.pl/tomek/2009-01/osgi-code-coverage-with-cobertura
http://ant.apache.org/manual/Tasks/java.html
http://www.ibm.com/developerworks/cn/java/j-cobertura/
http://team.ops4j.org/wiki/display/ops4j/Guice-OSGi