DEV Community

Graham Cox
Graham Cox

Posted on

4 1

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()
                .whitelistPackages(RunAllTests.class.packageName)
                .scan()
                .allClasses
                .filter { it.name.endsWith("Spec") }
                .loadClasses()


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

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

        def result = runner.run(testRequest)
        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.

Image of Datadog

Create and maintain end-to-end frontend tests

Learn best practices on creating frontend tests, testing on-premise apps, integrating tests into your CI/CD pipeline, and using Datadog’s testing tunnel.

Download The Guide

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more