24

Is this possible in JUnit4?

In JUnit3, I would do the following:

public class MyTestSuite {

  public static Test suite() throws Exception {
     doBeforeActions();

     try {
        TestSuite testSuite = new TestSuite();
        for(Class clazz : getAllClassesInPackage("com.mypackage")){
            testSuite.addTestSuite(clazz);
        }
        return testSuite;
     } finally {
        doAfterActions
     }
  }

...

}
oers
  • 18,436
  • 13
  • 66
  • 75
Fortega
  • 19,463
  • 14
  • 75
  • 113
  • Have you tried running it with junit4? – bbaja42 Sep 26 '11 at 17:37
  • @bbaja42 I don't want to run this with junit4, I want to use the junit4 annotations for my tests and run all of them using a testsuite. – Fortega Sep 27 '11 at 07:36
  • 2
    An "actual" answer to this question would be nice. Somehow, Eclipse is able to accomplish this by clicking one little checkbox in the JUnit run configuration panel. – djangofan Dec 14 '12 at 23:43

2 Answers2

18

The takari-cpsuite (originally developed by Johannes Link) offers a classpath-suite which should fit your needs. It allows filtering of classes in the Classpath by regular expressions like:

import org.junit.extensions.cpsuite.ClasspathSuite.*;
...
@ClassnameFilters({"mytests.*", ".*Test"})
public class MySuite...
oers
  • 18,436
  • 13
  • 66
  • 75
14

You can use JUnitToolBox:

@RunWith(WildcardPatternSuite.class)
@SuiteClasses("**/*Test.class")
public class MySuite {
}

Maven config:

<dependency>
<groupId>com.googlecode.junit-toolbox</groupId>
<artifactId>junit-toolbox</artifactId>
<version>1.5</version>
</dependency>

see https://code.google.com/p/junit-toolbox/ for more details.

rcomblen
  • 4,579
  • 1
  • 27
  • 32
  • Tried this, but doesn't work I keep getting "failed to scan..." error. – SobiborTreblinka Jan 15 '14 at 19:07
  • It can only scan packages in his folder and subfolder. So you need to create an AllTestSuite in com.[yourCompany]. By the way. This configuration ("**/*Test.class") assumes that all your test classes end in "Test". – borjab Jul 25 '14 at 14:40
  • 1
    Beware it doesn't work if the test is packaged in a jar. There is a open request to solve this. https://code.google.com/p/junit-toolbox/issues/detail?id=2 – Esteban May 29 '15 at 13:08