I am using Apache Ant to compile and run JUnit tests. At the moment, it is working on environments where the ant JUnit library is installed as a part of Ant, but not on other environments. I want to fix this. I have tried including the jars needed(junit-4.12.jar
and hamcrest-core-1.3.jar
, if I understand it correctly) but it is not working. The relevant part of my build.xml
is as follows:
<property name="build.path" location="build/src"/>
<property name="build.test.path" location="build/test"/>
<property name="lib.path.rel" value="lib"/>
<property name="junit.file" value="${lib.path.rel}/junit/junit-4.12.jar"/>
<property name="hamcrest.file" value="${lib.path.rel}/junit/hamcrest-core-1.3.jar"/>
<path id="junit.class.path">
<pathelement location="${junit.file}"/>
<pathelement location="${hamcrest.file}"/>
<pathelement location="${build.path}"/>
</path>
<target name="test-compile" depends="test-clean">
<mkdir dir="${build.test.path}"/>
<javac srcdir="${test.path}"
destdir="${build.test.path}"
includeantruntime="false">
<classpath refid="junit.class.path" />
</javac>
</target>
<target name="test" depends="test-compile">
<junit>
<classpath>
<path refid="junit.class.path"/>
<pathelement location="${build.test.path}"/>
</classpath>
<batchtest>
<fileset dir="${build.test.path}">
<include name="**/*Test*"/>
</fileset>
</batchtest>
<formatter type="brief" usefile="false"/>
</junit>
</target>
The task test-compile
successfully builds the tests.
The task test
, however, results in the following error:
Problem: failed to create task or type junit
Cause: the class org.apache.tools.ant.taskdefs.optional.junit.JUnitTask was not found.
I am using CentOS 7 with Ant 1.9.2, and though I think it is reasonable to request users to update Ant to the latest version available, I have no control over what OS and libraries they have installed. As such, I want to solve the problem not by yum install something
or whatnot, but by finding a way to properly use the JUnit jar files(if that is possible). Then, when they pull the git repository and run the task, it will work on any OS or environment(since they will be using a jar file they just pulled). Obviously, this also means that "just put the jars in the Ant lib dir" will not be a viable solution.
Thank you.
To fix this error you have to pass to ant the jar that is defining the JUnitTask. This jar is called ant-junit.jar
and you can either (from JUnit task documentation) :
<classpath>
element in a <taskdef>
in the build file.For option 4, you just have to add to your ant build a declaration like:
<taskdef name="junit" classname="org.apache.tools.ant.taskdefs.optional.junit.JUnitTask">
<classpath>
<pathelement location="${lib}/ant-junit.jar"/>
<pathelement location="${lib}/ant-junit4.jar"/>
</classpath>
</taskdef>