【问题标题】:How do I enable "--enable-preview" for tests?如何为测试启用“--enable-preview”?
【发布时间】:2020-09-18 17:48:00
【问题描述】:

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

我仍然在: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)

脚本是

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")
        }
    }
}

我错过了什么?

【问题讨论】:

    标签: java kotlin gradle preview-feature


    【解决方案1】:

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

    我设法通过像这样配置Test 任务使其工作:

    withType<Test>().all {
        jvmArgs("--enable-preview")
    }
    

    withType<Test>().all {
        allJvmArgs = listOf("--enable-preview")
    }
    

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

    【讨论】:

    • 是的,我在发布问题后发现了同样的问题。感谢您的确认!尽管jvmArgs 不为空,您是否知道为什么.add 不起作用?我很好奇。
    • 说实话我不知道。我对 Kotlin 以及如何在下面实现 Kotlin DSL 了解不多。可能是因为 Kotlin 如何处理不合适的集合,或者是某些 DSL 特定的事情。
    猜你喜欢
    • 2021-07-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-28
    • 2020-01-21
    • 2020-09-03
    • 1970-01-01
    • 2021-01-17
    相关资源
    最近更新 更多