如何在 gradle 4.6+ 中将 JUnit 5 测试实例生命周期切换到 "per-class"?

How to switch JUnit 5 test instance lifecycle to "per-class" in gradle 4.6+?

因为 gradle 4.6 通过以下配置支持 JUnit 5。

test {
    useJUnitPlatform()
}

看来更改测试实例生命周期的旧方法不起作用。

junitPlatform {
    // ...
    configurationParameter 'junit.jupiter.conditions.deactivate', '*'
    configurationParameters([
        'junit.jupiter.extensions.autodetection.enabled': 'true',
        'junit.jupiter.testinstance.lifecycle.default': 'per_class'
    ])
    // ...
}

https://junit.org/junit5/docs/current/user-guide/#running-tests-build-gradle-config-params

如何在 gradle 4.6+ 中将 JUnit 5 测试实例生命周期切换到 "per-class"?

您可以使用系统 属性:

test {

    useJUnitPlatform {
        // ...
        systemProperty 'junit.jupiter.testinstance.lifecycle.default', 'per_class'
        // ...
    }

}

除了使用 中描述的系统 属性 外,还可以使用 junit-platform.properties 文件。 junit-platform.properties 文件可以放在 src/test/resources.

junit-platform.properties

junit.jupiter.testinstance.lifecycle.default = per_class

这是 JUnit 团队的回答。 https://twitter.com/junitteam/status/970014414891094018

Either set it as a systemProperty in the task, or set it in the junit-platform.properties file. The latter is the more robust mechanism since it will be applied in the IDE as well.