How to compile and run my Maven unit tests for a Java 11, while having my code compiled for an older version of Java 8

14,399

Solution 1

In Maven compile and testCompile goals are different. And Maven even has parameters for testCompile: testTarget and testSource. So:

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-compiler-plugin</artifactId>
    <version>3.0</version>
    <configuration>
        <source>1.7</source>
        <target>1.7</target>
        <testSource>1.8</testSource>
        <testTarget>1.8</testTarget>
    </configuration>
</plugin>

Solution 2

A slightly more terse version of mkrakhin's answer You can set the source, target, testSource and testTarget :

  <properties>
    <maven.compiler.source>1.8</maven.compiler.source>
    <maven.compiler.target>1.8</maven.compiler.target>

    <maven.compiler.testSource>11</maven.compiler.testSource>
    <maven.compiler.testTarget>11</maven.compiler.testTarget>
  </properties>
</project>
Share:
14,399
rjdkolb
Author by

rjdkolb

Interests include Code Software security AWS / Cloud Kubernetes Python Java Love of open source software Coffee and a tendency to watch repeats of Star Trek Richard is a Java nerd with a keen interest in improving the knowledge in the community. He has done over 20 public talks and believes strongly in a KISS principle. Along with specializations in Java, Richard is a member of the Open Web Application Security Project (OWASP) and promotes secure software in the local industry.

Updated on June 28, 2022

Comments

  • rjdkolb
    rjdkolb almost 2 years

    I want to use Java 11 syntax in my unit tests, but my 'main' code needs to be compiled for Java 8 since my production environment only has JDK 8 installed.

    Is there a way of doing this with the maven-compiler-plugin? My Jenkins server has Java 11 installed.

    I will accept the risk that I can accidental use Java 11 specific functionality in my production code.