Search code examples
javaantjunitant-junit

Run multiple JUnit tests with Ant


probably this is a very basic question but I am new to java, so please bear with me. I am trying to run java task in ant and I want to know if there is any way to get all the name of the classes inside a folder in ant?

This is the build.xml file

<project default='run-test'  basedir=".">
  <property name="src" value="src"/>
  <property name="test" value="test"/>
  <property name="build" value="build"/>
  <property name="build-classes" value="build/classes"/>
  <property name="build-test-classes" value="build/test/classes"/>
  <property name="junit4" value="/usr/share/java/junit4.jar"/>

  <target name="init">
    <mkdir dir="${build-classes}"/>
    <mkdir dir="${build-test-classes}"/>
  </target>

  <target name="compile" depends="init">
    <javac includeantruntime="false" 
       srcdir="${src}" 
       destdir="${build-classes}"/>
  </target>

  <target name="compile-test" depends="compile">
    <javac includeantruntime="false" 
       classpath="${junit4}:${build-classes}"
       srcdir="${test}" 
       destdir="${build-test-classes}"/>
  </target>

  <target name="run-test" depends="compile-test">
    <java classpath="${junit4}:${build-classes}:${build-test-classes}"
      classname="org.junit.runner.JUnitCore"
      args="myclass.MyClassTest"/> <---This is my problem
  </target>

  <target name="clean">
    <delete dir="${build}"/>
  </target>
</project>

I have to manually mention the name of the class in the arguments. Is there any way where I can only mention the folder and all the class names will be taken up as arguments for the javatask automatically?


Solution

  • Ant ships with a task for running JUnit tests.

    In the run-test target in your example, replace the <java> task with the following:

    <junit>
      <formatter type="plain" usefile="false"/>
      <classpath>
        <pathelement location="${junit4}"/>
        <pathelement location="${build-classes}"/>
        <pathelement location="${build-test-classes}"/>
      </classpath>
      <batchtest>
        <fileset dir="${build-test-classes}">
          <include name="**/*.class"/>
        </fileset>
      </batchtest>
    </junit>