Compiling a Gradle Java project with Java 8 but running tests with Java 11

1.7k views Asked by At

As the first part of a transition process of my projects, I would like to keep compile with JDK-8 compiler, but execute tests with JDK-11 runtime.

My projects are Gradle projects (6.+ if it matters), using the java plugin or java-library plugins.

I could not find a way to do it with Gradle options.

I tried to compile (gradlew build) in one terminal with JDK-8, and then switch to another terminal with JDK 11 and run the tests (gradlew test), but it re-compiled the code.

What is the correct way to do it?

1

There are 1 answers

0
Bjørn Vester On BEST ANSWER

You can configure all Java-related tasks (compilations, tests, JavaExec, JavaDoc, etc) with a different JDK than what is used to run Gradle. There is a chapter in the user guide that gives an example of how to run Gradle with Java 8 but use Java 7 in all tasks. It works the same with Java 11.

For your project, you can continue running Gradle with Java 8 but add the following for running tests with a different version:

// Gradle <= 6.6 (Groovy DSL)
tasks.withType(Test) {
    executable = new File("/my/path/to/jdk11/bin/java")
}

The user guide has a more configurable solution, but this is the gist of it.

A cool feature that is part of the upcoming version 6.7 of Gradle is support for JVM toolchains. As it is now, you have to download a JDK 11 distribution yourself and configure the path to it. Newer versions will allow you to declare the version and let Gradle download it for you (from AdoptOpenJDK) if missing:

// Gradle >= 6.7 (Groovy DSL)
// Unreleased at the time of this writing and the syntax is therefore subject to change
test {
    javaLauncher = javaToolchains.launcherFor {
        languageVersion = JavaLanguageVersion.of(11)
    }
}

A final option is to run Gradle with Java 11 and make the compiler target Java 8 using the release option:

// Run Gradle with Java 11
compileJava {
    options.release = 8
}