Search code examples
javajunitantclassnotfoundexception

JUnit with Ant, another java.lang.ClassNotFoundException


New to Ant, don't really know what I'm doing. My guess is that I did not set the JUnit classpath correctly. I see there are a lot of similar questions as this one, Although none of the suggestions have worked for me. Please help!

My project directory structure: (I suspect my dir structure is seriously messed up)

MyProject/
    bin/main/
        project.class
        test1.class
        test2.class
        test3.class
    build/main/project
        Project.class
    build/test/main
        test1.class
        test2.class
        test3.class
    build/test/project
        test1.class
        test2.class
        test3.class
    lib/
        junit-4.11.jar
        hamcrest-all-1.3.jar
    src/main/java/
        project.java
    src/test/java/
        test1.java
        test2.java
        test3.java
    build.xml

My build.xml

<project name="junit-example">
  <property name="main.build.dir" value="build/main"/>
  <property name="main.src.dir" value="src/main/java"/>
  <property name="test.build.dir" value="build/test"/>
  <property name="test.src.dir" value="src/test/java"/>

  <path id="classpath.test">
    <pathelement location="lib/junit-4.11.jar"/>
    <pathelement location="lib/hamcrest-core-1.3.jar"/>
    <pathelement location="${main.build.dir}"/>
  </path>

  <target name="compile">
    <mkdir dir="${main.build.dir}"/>
    <javac srcdir="${main.src.dir}" destdir="${main.build.dir}" includeantruntime="false"/>
  </target>

  <target name="test-compile" depends="compile">
    <mkdir dir="${test.build.dir}"/>
    <javac srcdir="${test.src.dir}" destdir="${test.build.dir}" includeantruntime="false">
        <classpath refid="classpath.test"/>
    </javac>
  </target>

  <target name="testAll" depends="test-compile">
    <junit printsummary="on" haltonfailure="yes" fork="no">
        <classpath>
          <path refid="classpath.test"/>
          <pathelement location="${test.build.dir}"/>
        </classpath>
        <formatter type="brief" usefile="false" />
        <batchtest>
            <fileset dir="${test.src.dir}" includes="**/*Test.java" />
        </batchtest>
    </junit>
  </target>
</project>

Solution

  • You defined batchtest as

    <batchtest>
        <fileset dir="${test.src.dir}" includes="**/*Test.java" />
    </batchtest>
    

    Yet your the files in ${test.src.dir} are

    src/test/java/
        test1.java
        test2.java
        test3.java
    

    Try changing batchtest to

    <batchtest>
        <fileset dir="${test.src.dir}" includes="**/*test?.java" />
    </batchtest>