2012-10-23 193 views
4

我知道,從運行命令行junit的,你可以這樣做:如何從命令行使用junit運行多個測試類?

的java org.junit.runner.JUnitCore TestClass1 [...其它測試類...]

不過,我想運行許多測試一起並手動輸入「TestClass1 TestClass2 TestClass3 ...」效率不高。

當前我組織所有測試類在一個目錄(其中有子目錄指示包)。有沒有什麼辦法可以從命令行運行junit,讓它一次執行這些測試類?

謝謝。

+0

您是否嘗試在一個批處理文件中運行多個命令? – Ahmad

回答

1

我發現我可以編寫一個Ant構建文件來實現這一點。下面是示例build.xml:

<target name="test" description="Execute unit tests"> 
    <junit printsummary="true" failureproperty="junit.failure"> 
     <classpath refid="test.classpath"/> 
     <!-- If test.entry is defined, run a single test, otherwise run all valid tests --> 
     <test name="${test.entry}" todir="${test.reports}" if="test.entry"/> 
     <batchtest todir="tmp/rawtestoutput" unless="test.entry"> 
      <fileset dir="${test.home}"> 
       <include name="**/*Test.java"/> 
       <exclude name="**/*AbstractTest.java"/> 
      </fileset> 
      <formatter type="xml"/> 
     </batchtest> 
    <fail if="junit.failure" message="There were test failures."/> 
</target> 

有了這個構建文件,如果要執行一個測試,運行:

ant -Dtest.entry=YourTestName 

如果你想在批量執行多個測試,指定如上例所示,在<batchtest>...</batchtest> 下進行相應的測試。

5

基本上有兩種方法可以做到這一點:使用shell腳本來收集名稱,或使用ClassPathSuite來搜索所有與給定模式匹配的類的java類路徑。

對於Java來說,classpath suite方法更自然。 This SO answer描述瞭如何最好地使用ClassPathSuite。

shell腳本方法有點笨拙和特定於平臺,可能會遇到麻煩,具體取決於測試的數量,但如果您嘗試避免使用ClassPathSuite出於任何原因,它會訣竅。這個簡單的假設是每個測試文件都以「Test.java」結尾。

#!/bin/bash 
cd your_test_directory_here 
find . -name "\*Test.java" \ 
    | sed -e "s/\.java//" -e "s/\//./g" \ 
    | xargs java org.junit.runner.JUnitCore 
相關問題