Accomodating building optional components in an ant build script

Date: Fri Apr 25 2014 Java Debugging

I've been puzzling over the question of how to accommodate optionally building JUnit support into a software project I'm working on. JUnit's classes aren't going to always be present and therefore we only want to include the JUnit-dependent classes if JUnit's .jar file is present. Otherwise we'd get a compile error. Unfortunately ant's documentation leaves some things to be desired and this was one of them.

The initial method I came up with was to use XML comments in build.xml to control whether to compile JUnit-dependent code. The instructions to the developers was "if you want JUnit support, uncomment those four lines". It was clumsy but worked.

Surely with ant being a modern build tool there must be a way, especially with the features in ant for testing conditions and whatnot. What would be nice is to test the environment whether a junit.jar is available and if so compile the JUnit-dependent code.

The latest method begins with this


This requires a property, junit.jar, to be set to the path of a junit.jar implementation. If true then the global property junit.present is set. This allows the property to be tested elsewhere. Like:


How I implemented this was to break up the compile targets into pieces. Originally the build.xml contained a target with name="agent" and this became three targets: name="agent-compile-nonjunit", name="agent-compile-junit" and name="agent-jar". The name="agent" target depended on each of those. The first two contain compilations while the third jars up whatever was compiled and landed into the destination directory.

This shows the compile step which compiles the JUnit-dependent code. The path with refid="fx.cp" contained the normal classpath for the target, hence the classpath element here adds junit.jar to the normal classpath.


I think having to break apart the target like this is clumsy and I'd prefer to keep the build for a specific component all in one target. What would be nice is if I could do something like

fork="true" debug="on"