我知道要从命令行运行 junit,您可以这样做:
java org.junit.runner.JUnitCore TestClass1 [...其他测试类...]
但是,我想一起运行许多测试并手动输入“TestClass1 TestClass2 TestClass3 ...”效率低下。
当前,我将所有测试类组织在一个目录中(该目录具有指示包的子目录)。有什么方法可以让我从命令行运行 junit 并让它一次执行这些测试类?
谢谢。
我知道要从命令行运行 junit,您可以这样做:
java org.junit.runner.JUnitCore TestClass1 [...其他测试类...]
但是,我想一起运行许多测试并手动输入“TestClass1 TestClass2 TestClass3 ...”效率低下。
当前,我将所有测试类组织在一个目录中(该目录具有指示包的子目录)。有什么方法可以让我从命令行运行 junit 并让它一次执行这些测试类?
谢谢。
基本上有两种方法可以做到这一点:要么使用 shell 脚本来收集名称,要么使用ClassPathSuite
在 java 类路径中搜索与给定模式匹配的所有类。
类路径套件方法对于 Java 来说更自然。这个 SO 答案描述了如何最好地使用 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
我发现我可以编写一个 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>
在上面的示例中指定相应的测试。