Search code examples
javaxmljunittravis-cibuild.xml

Configure build.xml to run JUnit tests in separate /test directory


I'm trying to create a build.xml file to use with Travis CI.

This is the code I've come up with so far:

<?xml version="1.0" encoding="UTF-8"?>
<project name="Practice" basedir="." default="init">
   <property name="src.dir" location="src" />
   <property name="bin.dir" location="bin" />
   <property name="lib.dir" location="lib" />
   <path id="classpath">
      <pathelement location="${bin.dir}" />
      <pathelement location="${lib.dir}/hamcrest-core-1.3.jar" />
      <pathelement location="${lib.dir}/junit-4.11.jar" />
   </path>
   <target name="clean">
      <delete dir="${build.dir}" />
   </target>
   <target name="init" depends="clean">
      <mkdir dir="${bin.dir}" />
      <copy includeemptydirs="false" todir="${bin.dir}">
         <fileset dir="${src.dir}">
            <exclude name="**/*.launch" />
            <exclude name="**/*.java" />
         </fileset>
      </copy>
   </target>
   <target name="compile" depends="init" description="compile">
      <javac srcdir="${src.dir}" destdir="${bin.dir}" classpathref="classpath" />
   </target>
   <target name="test" depends="compile">
      <mkdir dir="${report.dir}" />
      <junit printsummary="yes">
         <classpath>
            <path refid="classpath" />
         </classpath>
         <formatter type="xml" />
         <test name="folder1.MyClass1Test" todir="${report.dir}" haltonfailure="yes" />
      </junit>
   </target>
</project>

If I place my JUnit test files in the same directory as the class files, like in the file structure shown below, the above build.xml works, and the JUnit test runs properly:

- src
  - folder1
    - MyClass1.java
    - MyClass1Test.java

I, however, have my test files in a separate /test directory and the structure looks something like the following:

- src
  - folder1
    - MyClass1.java
- test
  - folder1
    - MyClass1Test.java

I can't seem to figure out what I need to change to get the test to run from the /test folder. I tried changing the src.dir location in different spots to point to test instead of src, but the I then get errors that different packages don't exist.

Any suggestions?


Solution

  • You can/should/must define another target that compiles your test sources:

    <target name="compileTest" depends="compile" description="compileTest">
      <javac srcdir="${test-src.dir}" destdir="${bin.dir}" classpathref="classpath" />
    </target>
    

    Your test target then becomes

    <target name="test" depends="compileTest">
      ...
    </target>
    

    Make sure to add the additional property test-src.dir.