3.18 Generating a Test Report

3.18.1 Problem

You want to produce a nicely formatted HTML report that summarizes results from all of your tests.

3.18.2 Solution

Use batchtest along with junitreport.

3.18.3 Discussion

In earlier examples, we sent test results directly to the console. In order to format our results as HTML, we need to first write the test results to a series of XML files. We do this with the following line:

<formatter type="xml"/>

This causes test results to go to a series of XML files, one per test. The XML files are written to the directory named by the todir attribute of the junit task or the nested batchtest element.

Once the files are created, junitreport uses XSLT stylesheets to convert the XML files into a nice HTML report. The complete Ant target is shown in Example 3-9.

Example 3-9. Generating a test report
<target name="junit" depends="compile">
  <junit printsummary="on" fork="false" haltonfailure="false">

    <classpath refid="classpath.project"/>
    <formatter type="xml"/>

    <batchtest todir="${dir.build}">
      <fileset dir="${dir.src}">
        <include name="**/Test*.java"/>
      </fileset>
    </batchtest>

  </junit>

  <junitreport todir="${dir.build}">
    <fileset dir="${dir.build}">
      <include name="TEST-*.xml"/>
    </fileset>
    <report format="frames" todir="${dir.build}"/>
  </junitreport>

  <!-- convert an Ant path to a fully-qualified platform specific path -->
  <pathconvert dirsep="/" property="reportUrl">
    <path>
      <pathelement location="${dir.build}/index.html"/>
    </path>
  </pathconvert>

  <!-- launch a web browser to view the results -->
  <exec executable="cmd" os="Windows XP">
    <arg value="/C"/>
    <arg value="${reportUrl}"/> <!-- the full path to the report -->
  </exec>
</target>

Our buildfile runs all tests in the src directory tree and then sends XML results to the build directory, which was specified in the todir attribute of junitreport. After junitreport runs, we launch a web browser to view the test results. This last portion of the example only works on Microsoft Windows. If you are on a different platform, simply change the exec task to point to your browser.

3.18.4 See Also

The previous two recipes show other ways to run tests.