How to run multiple test classes with junit from command line?

时光总嘲笑我的痴心妄想 提交于 2020-01-13 12:18:07

问题


I know that to run junit from command line you can do this:

java org.junit.runner.JUnitCore TestClass1 [...other test classes...]

However, I want to run many tests together and manually typing "TestClass1 TestClass2 TestClass3..." is just inefficient.

Current I organize all test classes in a directory (which has sub-directories indicating the packages). Is there any way that I can run junit from command line and let it execute these test classes all at once?

Thanks.


回答1:


Basically there are two ways to do this: Either use a shell script to collect the names, or use ClassPathSuite to search the java classpath for all classes matching a given pattern.

The classpath suite method is more natural for Java. This SO answer describes how best to use ClassPathSuite.

The shell script method is a little clunky and platform-specific, and may run into trouble depending on the number of tests, but it'll do the trick if you're trying to avoid ClassPathSuite for any reason. This simple one assumes that every test file ends in "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



回答2:


I found that I can write an Ant buildfile to achieve this. Here is the sample 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>

With this build file, if you want to execute a single test, run:

ant -Dtest.entry=YourTestName

If you want to execute multiple tests in batch, specify the corresponding tests under the <batchtest>...</batchtest> as shown in the above example.



来源:https://stackoverflow.com/questions/13022990/how-to-run-multiple-test-classes-with-junit-from-command-line

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!