Search code examples
javaunit-testingmavenjunitjenkins

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


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.


Solution

  • 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>