Ant - Build file to run JUnit

By xngo on February 28, 2019

Sample Ant build file to run JUnit

<?xml version="1.0" encoding="UTF-8"?>
<!--
  Filename: build.xml
  Note: You have to change the followings according to your environment:
          -<pathelement location="bin"/>
          -<pathelement location="lib/junit/junit-4.8.2.jar"/>
          -<test name="x.x.x.x.x.x" todir="${junit.output.dir}"/>
-->
<project basedir="." default="junit" name="Sample of Ant file for JUnit">
  <property name="junit.output.dir" value="junit"/>
 
  <path id="junit.classpath">
    <pathelement location="bin"/><!-- All compiled class should be under this folder -->
    <pathelement location="lib/junit/junit-4.8.2.jar"/>
  </path>
 
  <!-- Target: Run JUnit test classes. -->
  <target name="junit">
    <mkdir dir="${junit.output.dir}"/>
    <junit fork="yes" printsummary="withOutAndErr">
      <formatter type="xml"/>
      <!-- Add all your test class names here. --> 
      <test name="com.packageName.MyTestClassName.AddTest" todir="${junit.output.dir}"/>
      <test name="com.packageName.MyTestClassName.AddTest2" todir="${junit.output.dir}"/>
      <classpath refid="junit.classpath"/>
    </junit>
  </target>
 
  <!-- Target: Generate JUnit report. -->
  <target name="report">
    <junitreport todir="${junit.output.dir}">
      <fileset dir="${junit.output.dir}">
        <include name="TEST-*.xml"/>
      </fileset>
      <report format="frames" todir="${junit.output.dir}"/>
    </junitreport>    
  </target>
 
</project>

Sample Structure of my files and directories created by Eclipse

C:.
¦   .classpath
¦   .project
¦   build.xml
¦
+---bin
¦   +---com
¦       +---packageName
¦           +---MyClasses
¦           ¦       Add.class
¦           ¦
¦           +---MyTestClassName
¦                   AddTest.class
¦                   AddTest2.class
¦
+---junit
¦   ¦   all-tests.html
¦   ¦   allclasses-frame.html
¦   ¦   alltests-errors.html
¦   ¦   alltests-fails.html
¦   ¦   index.html
¦   ¦   overview-frame.html
¦   ¦   overview-summary.html
¦   ¦   stylesheet.css
¦   ¦   TEST-com.packageName.MyTestClassName.AddTest.xml
¦   ¦   TEST-com.packageName.MyTestClassName.AddTest2.xml
¦   ¦   TESTS-TestSuites.xml
¦   ¦
¦   +---com
¦       +---packageName
¦           +---MyTestClassName
¦                   0_AddTest.html
¦                   1_AddTest2.html
¦                   package-frame.html
¦                   package-summary.html
¦
+---lib
¦   +---junit
¦           junit-4.8.2.jar
¦
+---src
    +---com
        +---packageName
            +---MyClasses
            ¦       Add.java
            ¦
            +---MyTestClassName
                    AddTest.java
                    AddTest2.java

About the author

Xuan Ngo is the founder of OpenWritings.net. He currently lives in Montreal, Canada. He loves to write about programming and open source subjects.