From Gossip@caterpillar

JUnit Gossip: 自動生成測試報告

接續上一個主題,您可以將JUnit的測試過程在Ant建構的過程訊息中顯示出來,只要加入< formatter>標籤設定即可:
  • build.xml
<project name="autobuildtest" default="test"> 
......
<target name="test" depends="compile">
<junit printsummary="yes">
<formatter type="plain" usefile="false"/>
<test
name="onlyfun.caterpillar.test.MathToolTest"/>
<classpath>
<pathelement location="${classes.dir}"/>
</classpath>
</junit>
</target>
</project>

Ant建構與調用JUnit進行測試的訊息如下:
>ant
Buildfile: build.xml

setProperties:

prepareDir:
   [delete] Deleting directory D:\temp\classes
    [mkdir] Created dir: D:\temp\classes

compile:
    [javac] Compiling 2 source files to D:\temp\classes

test:
    [junit] Running onlyfun.caterpillar.test.MathToolTest
    [junit] Tests run: 1, Failures: 0, Errors: 0,
            Time elapsed: 0 sec
    [junit] Testsuite: onlyfun.caterpillar.test.MathToolTest
    [junit] Tests run: 1, Failures: 0, Errors: 0,
            Time elapsed: 0 sec

    [junit] Testcase: testGcd took 0 sec

BUILD SUCCESSFUL
Total time: 1 second


當usefile屬性設定為true時,會自動幫您將產生的結果儲存在檔案中,預設是TEST-*.txt,其中*是您的測試案例類別名稱,就上例而言,其產生的報告檔案內容如下:
Testsuite: onlyfun.caterpillar.test.MathToolTest
Tests run: 1, Failures: 0, Errors: 0, Time elapsed: 0 sec

Testcase: testGcd took 0 sec


<formatter>標籤還可以設定將測試的結果,以XML文件儲存下來,一個撰寫的例子如下,它將測試的結果儲存至report目錄中,檔案名稱為TEST-*.xml,*是您的測試案例類別名稱:
  • build.xml
<project name="autobuildtest" default="test"> 
......
<target name="test" depends="compile">
<junit printsummary="yes">
<formatter type="xml"/>
<test
name="onlyfun.caterpillar.test.MathToolTest"/>
<classpath>
<pathelement location="${classes.dir}"/>
</classpath>
</junit>
</target>
</project>

您也可以將測試結果所產生的XML文件轉換為HTML文件,使用Ant可以直接幫您完成這個工作,<junitreport>標籤使用 XSLT將XML文件轉換為HTML文件,一個撰寫的例子如下所示:
  • build.xml
<project name="autobuildtest" default="report"> 
<target name="setProperties">
<property name="src.dir" value="src"/>
<property name="classes.dir" value="classes"/>
<property name="report.dir" value="report"/>
</target>

<target name="prepareDir" depends="setProperties">
<delete dir="${report.dir}"/>
<delete dir="${classes.dir}"/>
<mkdir dir="${report.dir}"/>
<mkdir dir="${classes.dir}"/>
</target>

<target name="compile" depends="prepareDir">
<javac srcdir="./src" destdir="${classes.dir}"/>
</target>

<target name="test" depends="compile">
<junit printsummary="yes">
<formatter type="xml"/>
<test
name="onlyfun.caterpillar.test.MathToolTest"
todir="${report.dir}"/>
<classpath>
<pathelement location="${classes.dir}"/>
</classpath>
</junit>
</target>

<target name="report" depends="test">
<junitreport todir="${report.dir}">
<fileset dir="${report.dir}">
<include name="TEST-*.xml"/>
</fileset>
<report
format="frames" todir="${report.dir}/html"/>
</junitreport>
</target>
</project>

<include>設定搜尋TEST-*.xml文件,將之轉換為HTML文件,而最後的結果我們設定儲存至 report/html/目錄下,format屬性中我們設定HTML文件具有框架,如果不設定這個屬性則HTML報告文件就不具有框架,上例所產生的 HTML文件如下:

自動化產生測試報告