JUnit4 run all tests in a specific package using a testsuite
Asked Answered
D

2

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
     }
  }

...

}
Disbelief answered 7/9, 2011 at 8:59 Comment(3)
Have you tried running it with junit4?Poul
@Poul 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.Disbelief
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.Antipas
S
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...
Somehow answered 27/9, 2011 at 6:32 Comment(0)
M
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.

Manservant answered 16/12, 2013 at 14:27 Comment(3)
Tried this, but doesn't work I keep getting "failed to scan..." error.Doubletongue
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".Reeba
Beware it doesn't work if the test is packaged in a jar. There is a open request to solve this. code.google.com/p/junit-toolbox/issues/detail?id=2Ashtoreth

© 2022 - 2024 — McMap. All rights reserved.