Run all tests in Junit 4

前端 未结 7 1571
感动是毒
感动是毒 2021-02-01 15:45

I want to be able to run all tests in a project programmatically. I know Eclipse has a \"Run as JUnit test\" configuration which somehow grabs all the tests in a project and run

7条回答
  •  Happy的楠姐
    2021-02-01 16:36

    None of the other answers did it for me. I had 40k tests I needed to run, so manually listing every class was not an option.

    I did it with ClasspathSuite. A test suite that runs all Junit4 and Junit3 test cases in the class path is as follows:

    import org.junit.extensions.cpsuite.ClasspathSuite;
    import org.junit.extensions.cpsuite.ClasspathSuite.*;
    import org.junit.runner.RunWith;
    import org.junit.runner.JUnitCore;
    import static org.junit.extensions.cpsuite.SuiteType.*;
    
    @RunWith(ClasspathSuite.class)
    @SuiteTypes({ JUNIT38_TEST_CLASSES, TEST_CLASSES })
    public class RunAllSuite {
            /* main method not needed, but I use it to run the tests */
            public static void main(String args[]) {
                    JUnitCore.runClasses(RunAllSuite.class);
            }
    }
    

    I needed to run it from command line, so this is what I did:

    1. Downloaded cp-1.2.6.jar
    2. Create the previously mentioned RunAllSuite
    3. Compile the class, javac RunAllSuite.java -cp cpsuite-1.2.6.jar;junit-4.8.1.jar
    4. run it with target tests in the class path, java -cp cpsuite-1.2.6.jar;junit-4.8.1.jar;path/to/runallsuite/folder;target/classes;target/test-classes RunAllSuite

    And that's it. With the RunAllSuite above, anywhere in your code you can just do JUnitCore.runClasses(RunAllSuite.class), which runs all tests in class path. There are other config options as well which are explained in the ClasspathSuite home page.

    Note also that the class given above does not print anything. If that is needed, you can do

    import org.junit.extensions.cpsuite.ClasspathSuite;
    import org.junit.extensions.cpsuite.ClasspathSuite.*;
    import org.junit.runner.RunWith;
    import org.junit.runner.JUnitCore;
    import org.junit.internal.TextListener;
    import static org.junit.extensions.cpsuite.SuiteType.*;
    
    @RunWith(ClasspathSuite.class)
    @SuiteTypes({ JUNIT38_TEST_CLASSES, TEST_CLASSES })
    public class RunAllSuite {
            public static void main(String args[]) {
                    JUnitCore junit = new JUnitCore();
                    junit.addListener(new TextListener(System.out));
                    junit.run(RunAllSuite.class);
            }
    }
    

提交回复
热议问题