Tuesday, January 31, 2012

Ant 'n JUnit

Instead of running JUnit manually from Eclipse, it is better to make it part of the Ant build.

This automatically ensures that all the code is tested each time it is built.

Ant comes with a JUnit task - all we have to do is use it.

Update your build.xml, to create a new 'test' target. Like this:
 <project name="HelloWorld" xmlns:ivy="antlib:org.apache.ivy.ant" >  

<target name="resolve" description="--> retrieve dependencies with ivy">
<ivy:retrieve />
</target>

<target name="init" depends="resolve">
<mkdir dir="classes"/>
<mkdir dir="target"/>
</target>

<path id="build.classpath">
<pathelement location="lib/junit-4.10.jar"/>
<pathelement location="lib/json-20090211.jar"/>
<pathelement location="lib/servlet-api-2.5.jar"/>
<pathelement location="lib/jsp-api-2.0.jar"/>
<pathelement location="lib/log4j-1.2.16.jar"/>
</path>

<target name="compile" depends="init">
<javac srcdir="." destdir="classes">
<classpath refid="build.classpath"/>
</javac>
</target>

<path id="test.classpath">
<pathelement location="classes"/>
<pathelement location="lib/junit-4.10.jar"/>
</path>

<target name="test" depends="compile" >
<junit failureproperty="junit.failure">
<test name="org.confucius.TestCalculator"/>
<classpath refid="test.classpath"/>
<formatter type="plain" usefile="false" />
</junit>
<fail if="junit.failure" message="Unit test(s) failed. See reports!"/>
</target>

<target name="dist" depends="test">
<war destfile="target/HelloWorld.war" webxml="web.xml">
<classes dir="classes"/>
<lib dir="lib">
<exclude name="jsp-api*.jar"/>
<exclude name="servlet-api*.jar"/>
</lib>
<fileset dir="web-content"/>
<webinf dir="WEB-INF"/>
</war>
<echo>Build executed at ${TIME_NOW}</echo>
</target>

<tstamp>
<format property="TIME_NOW" pattern="hh:mm:ss aa MM/dd/yyyy"/>
</tstamp>

</project>


We have made our new 'test' target depend on 'compile'.
And we have made the 'dist' target depend on 'test'.

The junit task's 'failureproperty' records if any of the tests failed.
If so the 'fail' task is triggered, which will halt the build process.

If you run the Ant 'dist' task now, you will see the JUnit tests being run.

No comments: