DEV Community

Graham Cox
Graham Cox

Posted on

Running all JUnit Tests on the Classpath

I've been tinkering with this for a while, and have finally found a reliable way to run all of the JUnit tests that exist on the classpath. In my case this is so that I can package up my end-to-end tests as an executable JAR and run them in a Docker container, but there are various other use cases as well.

This code is in Groovy, because I'm doing this with Spock and Geb, but it'll work just as well in any JVM language.

Note as well that this uses the fantastic ClassGraph API for finding the tests.

So - here's the code:

import io.github.classgraph.ClassGraph
import org.junit.internal.TextListener
import org.junit.runner.JUnitCore
import org.junit.runner.Request

class RunAllTests {
    static void main(String... args) {

        def testClasses = new ClassGraph()
                .filter {"Spec") }

        def runner = new JUnitCore()
        runner.addListener(new TextListener(System.err))

        def testRequest = Request.classes(*testClasses.toArray())

        def result =
        System.exit(result.wasSuccessful() ? 0 : 1)
Enter fullscreen mode Exit fullscreen mode

It's as simple as that. That finds everything that is in the same package as the RunAllTests class or below, and that has a class name ending in Spec, and then runs them all.

Top comments (0)