Search code examples
javatestingjunitjunit4junit-runner

How can I pass a CategoryFilter to the JUnitcore?


How can I dynamically build a category filter and invoke the JUnit core to run my tests? I'm trying to build a simple class with a main method that can be invoked to run my tests but I'm sure if this is a clean way.

The idea was to allow the inclusions and exclusions to be passed as command-line parameters and use that to build the CategoryFilter. I've spent quite a bit of time on this and haven't yet figured out how to pass the filter to the JunitCore.

public class SingleJUnitTestRunner {

    public static void main(String... args) throws ClassNotFoundException {
        System.out.println("Running tests");
        System.out.println(Arrays.asList(args));

        synchronized (Play.class) {
            if (!Play.started) {
                Play.init(new File("."), "test");
                Play.start();
            }
        }

        CategoryFilter catfil = Categories.CategoryFilter.include(Play.classloader.loadClass("testutils.SlowTests"));
        List<Filter> filters = new ArrayList<Filter>();
        filters.add(catfil);

        TestSuite suite = new TestSuite();

        for (Class tests : Play.classloader.getAnnotatedClasses(Category.class)) {
            if (catfil.shouldRun(Description.createSuiteDescription(tests))) {
                suite.addTest(new JUnit4TestAdapter(tests));
                System.out.println("With " + tests.getName());
            }
        }

        Result result = new JUnitCore().run(suite);
        System.out.println(result.getRunCount());
        System.exit(result.wasSuccessful() ? 0 : 1);
    }
}

Solution

  • As of JUnit 4.12 you can do this:

    java org.junit.runner.JUnitCore \
        --filter=org.junit.experimental.categories.IncludeCategories=testutils.SlowTests \
        com.example.ExampleTestSuite
    

    See the release notes for details.

    If you want to do this programmatically, use Request.filterWith():

    Request request = ...
    Categories.CategoryFilter filter =
        Categories.CategoryFilter.include(
            testutils.SlowTests.class); 
    request = request.filterWith(filter);
    Result result = JUnitCore.run(request);