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.

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay