如何为 Gradle 中的单个测试 class 并行执行 JUnit 测试

How to execute JUnit tests in parallel for a single test class in Gradle

我们有很多使用 Spring 的集成测试。我们不希望为每个测试创建单独的 JVM 进程(maxParallelForks 选项)或在多模块项目中仅创建 运行 并行构建 (--parallel)。

我们希望单个测试 class 像在 Maven 中一样使用 http://maven.apache.org/surefire/maven-surefire-plugin/examples/fork-options-and-parallel-execution.html 和并行选项

并行执行测试

The important thing to remember with the parallel option is: the concurrency happens within the same JVM process.

是否可以在Gradle实现?

Spring 5:新来的孩子

从Spring 5开始,你可以运行 Junit测试(使用Spring TestContext Framework)并行,我认为这是什么您正在寻找:在同一个 JVM 中同时执行。

有关详细信息,请参阅 Baeldung's blog


原回答:

这里是 Gradle doc explaining Java plugin's tasks in Gradle, and here is API doc 解释所述插件的参数。

请仔细查看 forkEvery and maxParallelForks 参数。

设置这些应该会给你足够的控制来实现并行测试执行。

此处 the SO answer 指出 maxParallelForks 应该设置为什么值,以便最大化加速。

@MariuszS 的回答是最好的

Gradle is ant without xml, maybe this can help you ant.apache.org/manual/Tasks/parallel.html :)

这里描述了最接近的实现方式-https://discuss.gradle.org/t/how-to-use-ants-parallel-target/6720/5

task runAllTestsByGroups << {
      ant.parallel(threadsPerProcessor: 1) {
                    ant.junit (...) {
            // run test group 1
            ...
        }
          ant.junit(...) {
            // run test group 2
            ...
       }
         // run group 3, 4, 5 ...
    }
  }