如何为Java 11编译和运行我的Maven单元测试,同时为旧版Java 8编译我的代码

rjd*_*olb 30 java junit unit-testing maven jenkins

我想在单元测试中使用Java 11语法,但我的'main'代码需要为Java 8编译,因为我的生产环境只安装了JDK 8.

有没有办法用maven-compiler-plugin做到这一点?我的Jenkins服务器安装了Java 11.

我将接受在生产代码中偶然使用Java 11特定功能的风险.

mkr*_*hin 37

在Maven中,compile和testCompile的目标是不同的.Maven甚至还有testCompile的参数:testTarget和testSource.所以:

<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>
Run Code Online (Sandbox Code Playgroud)

  • 在https://gist.github.com/aslakknutsen/9648594下有一个很好的例子,说明如何使用这种方法并保证代码安全(=错误地不使用Java 8 API) (9认同)