使用目的
JCoverage正如其名,主要用于代碼的覆蓋測試。通過在被測試類的二進(jìn)制文件中添加相應(yīng)的指令,再配合junit,jcoverage可以給出被測試類的代碼覆蓋率,并給出測試過程中哪些語句被執(zhí)行,哪些沒有。通過這些信息,我們可以了解測試代碼的測試質(zhì)量,以及被測試類中哪些語句需要特別的關(guān)注(即那些未被覆蓋的語句)。
當(dāng)前的版本是1.0.5,可以從www.jcoverage.com/downloads.html下載。在實際使用時,需要將jcoverage用到的類放到對應(yīng)的classpath中。在這個版本中它所依賴的外部類以及版本:
- bcel 5.1 http://jakarta.apache.org/bcel/
- log4j 1.2.8 http://jakarta.apache.org/log4j/
- getopt 1.0.9 http://gnu.org/
- oro 2.0.7 http://jakarta.apache.org/oro/
用法
1. jcoverage可以和ant配合使用,使這一過程自動化;居梅ǎ
- 編譯被測試類和相應(yīng)的被測試類的junit代碼。
- 使用<instrument>,將jcoverage的指令加入到被測試類的二進(jìn)制文件中。為了保證這一過程能夠有效,請在編譯被測試類時,設(shè)置<javac>的debug屬性設(shè)為yes。
- 執(zhí)行junit代碼進(jìn)行代碼覆蓋測試。這一步需要注意的是,需要將被注入指令的測試類要早于單元測試所需的測試類裝入。為了確保這一點,需要使用<classpath>,使注入指令的測試類位于測試類之前。
- 使用<report>產(chǎn)生覆蓋測試的報告。
2. 使用例子:
<!-- 采用debug模式編譯被測試類 -->
<javac destdir="${dist.coverage.classes}" deprecation="on" debug="yes">
<src path="${src.code}"/>
<classpath refid="classpath"/>
</javac>
<!-- 編譯被測試類的junit代碼 -->
<javac destdir="${dist.coverage.junit}" deprecation="on">
<src path="${src.junit}"/>
<classpath refid="classpath"/>
</javac>
<!-- 定義jcoverage任務(wù) -->
<path id="jcoverage">
<fileset dir="junit_lib">
<include name="jcoverage.jar"/>
</fileset>
</path>
<taskdef classpathref="jcoverage" resource="tasks.properties"/>
<!-- 給被測試類二進(jìn)制代碼中注入jcoverage的指令 -->
<instrument todir="${dist.coverage.instrument}">
<classpath refid="classpath"/>
<!-- 忽略org.apache.common的應(yīng)用 -->
<ignore regex="org.apache.common.*"/>
<fileset dir="${dist.coverage.classes} ">
<include name="**/*.class"/>
</fileset>
</instrument>
<!-- 啟動junit,進(jìn)行代碼覆蓋測試 -->
<junit printsummary="yes" haltonfailure="no" fork="yes">
<classpath>
<!-- 注意:被注入指令的類,位置在測試類之前。
這樣確保它們早于測試類備加載,使指令起作用。 -->