build.xml
<?xml version="1.0" encoding="UTF-8"?><!--1.建立屬性2.編譯源檔案3.編譯test檔案4.運行單元測試5.產生單元測試報告--><!-- 如果檔案夾換名,應先執行刪除檔案夾deleteDir任務,在更換build檔案名稱 --><project name="junit_test" default="run_test"><!--1.使用屬性定義相應的路徑時,一定要使用location,會轉換系統的分隔字元--><property name="src.dir" location="src"></property><property name="test.src.dir" location="test"></property><property name="build.dir" location="build"></property><property name="build.classes" location="${build.dir}/classes"></property><property name="build.test.dir" location="${build.dir}/test"></property><property name="build.test.classes" location="${build.test.dir}/classes"></property><property name="build.test.report" location="${build.test.dir}/report"></property><property name="lib.dir" location="lib"></property><property name="run.test.class" value="**/Test*"></property><!-- 路徑不建議放在properties中定義;如果屬性太多可以在外部檔案中定義<property file="build.properties"></property> --><!--把環境變數中的參數匯出到env這個變數中進行使用<property environment="env"></property>--><!--最佳實務:在項目中增加一個lib檔案夾;使用junit本身的jar包,然後添加到編譯環境之中--><path id="complie_path"><fileset dir="${lib.dir}" includes="*.jar"></fileset></path><path id="compile_test_path"><path refid="complie_path"></path><pathelement location="${build.classes}"/></path><path id="run_test_path"><path refid="compile_test_path"></path><pathelement location="${build.test.classes}"/></path> <target name="clean"><echo>進行項目的清理工作</echo><delete dir="${build.dir}"></delete> </target><target name="init" depends="clean"><echo>進行項目的初始化</echo><mkdir dir="${build.dir}"/><mkdir dir="${build.classes}"/><mkdir dir="${build.test.dir}"/><mkdir dir="${build.test.classes}"/><mkdir dir="${build.test.report}"/></target><target name="compile" depends="init"><echo>編譯源檔案</echo><javac failonerror="true" srcdir="${src.dir}" destdir="${build.classes}" classpathref="compile_test_path"></javac></target><target name="compile_test" depends="compile"><echo>編譯測試檔案</echo><javac failonerror="true" includeantruntime="true" srcdir="${test.src.dir}" destdir="${build.test.classes}" classpathref="compile_test_path"></javac></target><target name="run_test" depends="compile_test"><echo>運行單元測試</echo><!--4.設定資訊直接顯示:printsummary="true" 出錯後不再向下執行:haltonfailure="true"--><junit printsummary="false" haltonfailure="false"><!--1.設定run路徑--><classpath refid="run_test_path"></classpath><!--2.設定顯示錯誤資訊的格式--><formatter type="brief" usefile="false"/><formatter type="xml"/><!--3.設定類路徑--><!--3.1單檔案測試<test name="${run.test.class}"></test>--><!--3.2批量測試todir設定報告檔案路徑 --><batchtest todir="${build.test.report}"><fileset dir="${build.test.classes}" includes="${run.test.class}"></fileset></batchtest><!--3.設定顯示錯誤資訊--></junit><!--5.設定junit格式化的的檔案夾並進行轉換--><junitreport todir="${build.test.report}"><fileset dir="${build.test.report}" includes="TEST-*.xml"></fileset><report format="frames" todir="${build.test.report}/html"/></junitreport></target><target name="end" depends="compile_test"><echo>整個過程結束</echo></target></project>