slashms
slashms

Reputation: 978

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

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?

Upvotes: 2

Views: 2093

Answers (2)

Pod
Pod

Reputation: 4130

In the top-level build.gradle:

subprojects {
    apply plugin: 'java'

    java {
        toolchain {
            languageVersion = JavaLanguageVersion.of(11)
        }
    }

    tasks.withType(JavaCompile).configureEach {
        if (!name.contains("Test")) {
            options.compilerArgs << '--release' << '8'
        }
    }
}

(or do it in each sub-project if you want)

This uses Gradle toolchains, available in Gradle 7.0 onwards.

Upvotes: 0

Bj&#248;rn Vester
Bj&#248;rn Vester

Reputation: 7600

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
}

Upvotes: 2

Related Questions