Tell intellij which java version to use for JUnit testing

we have a project that needs Java 8 to run.

Now we have Java 16 around, so when importing Intellij uses Java 16 by default.

I tried to convince Intellij to use java 8 for test execution with that:

java {
        toolchain {
                languageVersion = JavaLanguageVersion.of(8)

That works fine when using run “via Gradle”:

However when using Run “via Intellij IDEA”, Intellij still uses Java 16:

Is this a bug in intellij or is there some other way to steer the selection of the JDK that should be used for test execution?

You can find a full example project here: GitHub - david0/junit5-java-version

Perhaps you can specify a JAVA_HOME variable in the run configuration for the JDK you want? You may also be able to change your gradle JVM version if that’s an option like below.

Hi Alex an thanks for your reply.

Gradle JDK has to be Java 16, since one half of the project is a Java 16 project.
The other half is legacy and has to use Java 8 :frowning:

I even set the Gradle JDK to Java 8 for one half of my project and to Java 16 for the other half.
Still intellij seems to use what is configured as Project SDK for running unit tests.

Of course it uses the project SDK if you don’t delegate the test execution to Gradle.
The Gradle JVM is only used - well - to execute Gradle.
That’s why “Build/Run with Gradle” and “Test with Gradle” are the defaults, because Gradle usually knows better how to do the things a project needs.
If IJ does not get the JDK right, you should open an issue with JetBrains YouTrack probably.

Sure, running via Gradle is always the more precise solution, unfortunately its way slower too.

I just tested again - Intellij uses does not use the Project SDK, instead it uses the “module” SDK - kind of what I expect:

Just that this setting seems not to be synched from the gradle import. Sounds related to these tickets:

Once the configuration cache gets production ready, the speed difference will hopefully be neglectible. :slight_smile:

1 Like