如何为测试启用“--enable-preview”?

exp*_*ert 5 java gradle kotlin preview-feature

如何在基于 Kotlin 的 Gradle 脚本中为测试启用“--enable-preview”?我几乎尝试了所有我可以在网上找到的东西,/sf/answers/4329483931/是最接近正确答案的。

我仍然收到以下:test任务错误

org.gradle.api.internal.tasks.testing.TestSuiteExecutionException: Could not execute test class 'com.blabla.playground.AppTest'.
    at org.gradle.api.internal.tasks.testing.SuiteTestClassProcessor.processTestClass(SuiteTestClassProcessor.java:53)
Caused by: java.lang.UnsupportedClassVersionError: Preview features are not enabled for com/blabla/playground/AppTest (class file version 58.65535). Try running with '--enable-preview'
    at java.base/java.lang.ClassLoader.defineClass1(Native Method)

Run Code Online (Sandbox Code Playgroud)

按脚本是

plugins {
    java
    application
}

repositories {
    jcenter()
}

dependencies {
    implementation("com.google.guava:guava:28.2-jre")
    testImplementation("org.junit.jupiter:junit-jupiter-api:5.6.0")
    testRuntimeOnly("org.junit.jupiter:junit-jupiter-engine:5.6.0")
}

application {
    mainClassName = "com.blabla.playground.App"
}

java {
    sourceCompatibility = JavaVersion.VERSION_14
    targetCompatibility = JavaVersion.VERSION_14
}

tasks {
    withType<Test>().all {
        allJvmArgs.add("--enable-preview")
        testLogging.showStandardStreams = true
        testLogging.showExceptions = true
        useJUnitPlatform {
        }
    }

    withType<JavaExec>().all {
        jvmArgs!!.add("--enable-preview")
    }

    withType<Wrapper>().all {
        gradleVersion = "6.4.1"
        distributionType = Wrapper.DistributionType.BIN
    }

    withType(JavaCompile::class.java).all {
        options.compilerArgs.addAll(listOf("--enable-preview", "-Xlint:preview"))
    }

    jar {
        manifest {
            attributes("Main-Class" to "com.blabla.playground.App")
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我错过了什么?

mic*_*alk 3

事实证明,您为Test任务配置标志的方式并没有真正将标志附加到allJvmArgs.

我设法通过配置Test如下任务来使其工作:

withType<Test>().all {
    jvmArgs("--enable-preview")
}
Run Code Online (Sandbox Code Playgroud)

或者

withType<Test>().all {
    allJvmArgs = listOf("--enable-preview")
}
Run Code Online (Sandbox Code Playgroud)

然而,第二个选项可能不是更好,因为它替换了分叉进程的所有 JVM 参数(包括定义系统属性、最小/最大堆大小和引导类路径的参数)。第一个选项应该是首选。