简体   繁体   中英

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

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.

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM