Hopefully, you are using JUnit on your project to unit test your code. If you’re new to JUnit then read this primer. JUnit provides an Ant task that can great generate HTML test reports. These reports are useful to show to your management team. They are also useful if you are running automated builds and you want to review the results of the tests at a later time.
If you’re using Maven then this feature is already available with the “mvn site” command.
Here’s a screen shot of sample report.
The report shows a list of all test cases for each class.
Developing the Ant File
Below is an Ant file for generating the JUnit reports.
As you can see, this is Ant file follows the usual format of Ant files. At the beginning of the file, we set the appropriate directories for our Java source code and JUnit tests. We also have the standard javac task for compiling the code.
Lines 39 – 53, introduces the junit Ant task. This task will run the JUnit tests and produce the test results. The test results are placed in a plain text file and an XML file.
Line 39 is the beginning of the task and we tell the system to stop executing if we encounter an error/exception or a test failure.
Lines 40-41 describe the type of output files to generate. In this case, the task will generate a plain text file. It also generates an XML file that we can use later to generate HTML (via XSL).
Lines 42-47 define the JUnit test cases to include in this report. For our example, we will include all unit tests that end with “Test” (*Test.java) and “All”, (Test*All.java).
The next section handles the generation of the HTML pages for the test results.
Lines 58-63 make use of the junitreport task. This task reads the test output files from the previous junit task. The output files have the format of “TEST-*.xml”. The generated reports are stored in the directory “target.report.dir”. You can open this directory and open the index.html.
Test It Out
- Make sure you have Ant installed, if not then you can download it from here
- Download the source code for this blog article
- Extract the files to a directory on your file system
- Open a MS-DOS window or terminal window
- Move to the directory where you extracted the files
- Type: ant report
- Using a web browser, open the file: build/report/html/index.html
You can now see the results of the unit test. Enjoy.
Good luck!
Book Recommendations