Ant是Java平台下非常棒的批处理命令执行程序,能非常方便地自动完成编译,测试,打包,部署等等一系列任务
下面以Eclipse自带的Ant工具和Java Project来测试下Ant的使用方式.
工程项目结构如下:
src存放Java源文件,classes存放编译后的class文件,lib存放编译和运行用到的所有jar文件,web存放JSP等web文件,dist存放打包后的jar文件,doc存放API文档
build.xml-->工程项目的根路径下-->build.xml定义了Ant要执行的批处理命令.可以随意命名但尽量遵循标准
<?xml version="1.0"?>
<project name="Hello world" default="doc">
<!-- properies -->
<property name="src.dir" value="src"/>
<property name="report.dir" value="report"/>
<property name="classes.dir" value="classes"/>
<property name="lib.dir" value="lib"/>
<property name="dist.dir" value="dist"/>
<property name="doc.dir" value="doc"/>
<!-- 定义classpath -->
<path id="master-classpath">
<fileset file="${lib.dir}/*.jar"/>
<pathelement path="${classes.dir}"/>
</path>
<!-- 初始化任务 -->
<target name="init">
</target>
<!-- 编译 -->
<target name="compile" depends="init" description="compile the source files">
<mkdir dir="${classes.dir}"/>
<javac srcdir="${src.dir}" destdir="${classes.dir}" target="1.5" includeAntRuntime="false">
<classpath refid="master-classpath"/>
</javac>
</target>
<!-- 测试 -->
<target name="test" depends="compile" description="run junit test">
<mkdir dir="${report.dir}"/>
<junit printsummary="on"
haltonfailure="false"
failureproperty="tests.failed"
showoutput="true">
<classpath refid="master-classpath"/>
<formatter type="plain"/>
<batchtest todir="${report.dir}">
<fileset dir="${classes.dir}">
<include name="**/*Test.*"/>
</fileset>
</batchtest>
</junit>
<fail if="tests.failed">
***********************************************************
**** One or more tests failed! Check the output ... ****
***********************************************************
</fail>
</target>
<!-- 打包成jar -->
<target name="pack" depends="test" description="make .jar file">
<mkdir dir="${dist.dir}"/>
<jar destfile="${dist.dir}/hello.jar" basedir="${classes.dir}">
<exclude name="**/*Test.*"/>
<exclude name="**/Test*.*"/>
</jar>
</target>
<!-- 输出api文档 -->
<target name="doc" depends="pack" description="create api doc">
<mkdir dir="${doc.dir}"/>
<javadoc destdir="${doc.dir}"
author="true"
version="true"
use="true"
windowtitle="Test API">
<packageset dir="${src.dir}" defaultexcludes="yes">
<include name="example/**"/>
</packageset>
<doctitle>
<![CDATA[<h1>Hello, test</h1>]]>
</doctitle>
<bottom>
<![CDATA[<i>All Rights Reserved.</i>]]>
</bottom>
<tag name="todo" scope="all" description="To do:"/>
</javadoc>
</target>
</project>
以上xml依次定义了init(初始化),compile(编译),test(测试),doc(生成文档),pack(打包)任务,可以作为模板.
添加对Junit的测试类--Junit3.8.2
src下的两个Hello*类:
package example;
public class Hello {
public int add(int x,int y){
return x+y;
}
}
package example;
import junit.framework.Assert;
import junit.framework.TestCase;
public class HelloTest extends TestCase {
Hello hello = new Hello();
public void testAdd() {
int result = hello.add(1, 2);
Assert.assertEquals(3, result);
}
}
运行效果:
最后结果如下: