junit test suites

2019-08-14 12:27发布

问题:

I have a script(test.bat) that allows me to launch one java test by command line : -java -cp() org.junit.runner.JUnitCore package.Class

Now I want to do the same for several java tests ? how could I do it? should I have to add the byte code for each java test? could I have an example , please?

回答1:

You can use Ant to run your tests with a single command with the junit ant task. Here's an example on how to use it:

<target name="runtests" depends="clean,compiletests">           
    <junit printsummary="yes" haltonfailure="no">
        <classpath>
            <path refid="test.classpath" />                 
            <pathelement location="${test.classes}"/>
        </classpath>                                
        <formatter type="xml"/>     
        <batchtest fork="yes" todir="${test.reports}">
            <fileset dir="${test.src}">
                <include name="**/*Test*.java"/>
            </fileset>
        </batchtest>
    </junit>        
</target>

That target uses batchtest which is part of the junit ant task. It sets your test classpath so all your tests that contain the Test.java pattern in their class name will be included. Check out the JUnit Task documentation.



回答2:

In JUnit, you can group your tests into a test suite and then run that with a single command.

Here is a tutorial on using test suites in JUnit 3, and here is an SO post about same with JUnit 4. Moreover, here is a tutorial on how to use the new features of JUnit 4.

However, if you are practically trying to write a build script in your batch file, I recommend using an existing build system instead, be it Ant, Maven, Buildr or something else.



回答3:

A convention used in JUnit is to have an AllTests test suite that groups all tests in the project together and have an Ant script or whatever execute the AllTests test suite.



回答4:

You can create a set of suites using the JUnit annotation syntax. I describe it in more detail here.



回答5:

I see 3 possibilities:

  • Use ant (see other answers while I'm typping)
  • update your batch to java -cp ... file1 file2 filen
  • use something like this:

    org.junit.runner.JUnitCore.runClasses(TestClass1.class, ...);
    public class GlobalTest { }