You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过Cucumber Gradle实现并行执行?求文档及示例

Gradle 配置 Cucumber 并行执行(按 Feature 文件拆分)

一、依赖配置

先确保项目引入核心依赖,重点是 Cucumber 的 JUnit Platform 引擎和 JUnit 5 基础组件:

dependencies {
    testImplementation 'io.cucumber:cucumber-java:7.14.0' // 替换为你使用的Cucumber版本
    testImplementation 'io.cucumber:cucumber-junit-platform-engine:7.14.0'
    testImplementation 'org.junit.platform:junit-platform-launcher:1.10.0'
    testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.10.0'
}

二、Gradle Test 任务配置

修改 build.gradle 中的 test 任务,启用并行并指定按 Feature 文件拆分的执行策略:

test {
    // 按CPU核心数设置并行进程数
    maxParallelForks = Runtime.runtime.availableProcessors()
    // 每个Feature启动独立进程,避免状态污染
    forkEvery = 1

    // 传递Cucumber并行执行参数
    systemProperty 'cucumber.execution.parallel.enabled', 'true'
    // 按Feature文件分组执行
    systemProperty 'cucumber.execution.group.by', 'feature'
    // 固定并行线程数,也可改用dynamic策略
    systemProperty 'cucumber.execution.parallel.config.strategy', 'fixed'
    systemProperty 'cucumber.execution.parallel.config.fixed.parallelism', Runtime.runtime.availableProcessors()

    // 指定使用JUnit Platform运行器
    useJUnitPlatform()
}

如果用 Kotlin DSL(build.gradle.kts),配置如下:

tasks.test {
    maxParallelForks = Runtime.getRuntime().availableProcessors()
    forkEvery = 1

    systemProperty("cucumber.execution.parallel.enabled", "true")
    systemProperty("cucumber.execution.group.by", "feature")
    systemProperty("cucumber.execution.parallel.config.strategy", "fixed")
    systemProperty("cucumber.execution.parallel.config.fixed.parallelism", Runtime.getRuntime().availableProcessors())

    useJUnitPlatform()
}

三、可选:用配置文件统一管理参数

也可以在 src/test/resources/junit-platform.properties 中配置参数,替代任务中的 systemProperty:

cucumber.execution.parallel.enabled=true
cucumber.execution.group.by=feature
cucumber.execution.parallel.config.strategy=fixed
cucumber.execution.parallel.config.fixed.parallelism=4

四、验证并行效果

运行 ./gradlew test,查看控制台日志,若出现类似以下输出,说明并行执行生效:

[Test worker 1] Running com.example.features.LoginFeature
[Test worker 2] Running com.example.features.CheckoutFeature

注意事项

  • 测试用例必须无状态,避免并行任务间的资源冲突(比如共享测试数据、未关闭的浏览器实例)。
  • 根据机器性能调整并行数,不要设置过大导致资源耗尽。
  • 保持 Cucumber 各依赖版本一致,避免版本冲突。

内容的提问来源于stack exchange,提问作者syed naveed

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 05:01:02