Search code examples
javajunittest-suite

How to get a collection of tests in a JUnit 4 test suite


In JUnit 3, I could get all of the tests within a test suite with the following code:

TestSuite allTestsSuite = (TestSuite) AllTests.suite()
Enumeration enumeration = allTestsSuite.tests();
ArrayList listOfTests = Collection.list(enumeration);

However, I can't find an equivalent way of doing this in JUnit 4. Classes no longer have a .suite() method; they simply use the @Suite annotation. This wouldn't be a problem except that the Suite class no longer has a tests() method. There is a children() method, but that returns a list of Runners, which seem to be something different than why I'm looking for.

So how can I get the tests within a test suite in JUnit 4, like I could with JUnit 3?


Solution

  • After a bit of experimentation, I discovered the following solution:

    SuiteClasses suiteClassesAnnotation = AllTests.class.getAnnotation(SuiteClasses.class);
    if (suiteClassesAnnotation == null)
        throw new NullPointerException("This class isn't annotated with @SuiteClasses");
    Class<?>[] classesInSuite = suiteClassesAnnotation.value();
    

    Basically, it gets the classes the same way that JUnit itself gets them: by looking into the annotation and determining which values are included within it.

    The category solution provided by dkatzel is also a good option if you're ultimately wanting to filter these classes, but if you need a list of classes in a suite for some other purpose such as code analysis, this is the simplest and most direct way to do it.