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

在Kotlin JVM环境下用Selenium-Cucumber重跑失败测试的正确方法

解决Cucumber JUnit重跑任务与主测试任务顺序问题

问题根源

Gradle的test任务默认会扫描所有继承自JUnit Runner的测试类,你的FailedRunner和TestSuite都会被纳入执行范围,而类名按字母排序(F在T前),所以会先跑FailedRunner。另外你添加的maven-surefire-plugin是Maven生态的插件,Gradle环境下完全没用,直接删掉这个依赖。

正确配置步骤

1. 清理无效依赖

从build.gradle.kts(或build.gradle)中移除以下依赖:

testImplementation("org.apache.maven.plugins:maven-surefire-plugin:2.22.2")

2. 调整测试类配置

确保FailedRunner的CucumberOptions正确指向重跑文件(注意@符号):

import org.junit.runner.RunWith
import cucumber.api.CucumberOptions
import cucumber.api.junit.Cucumber

@RunWith(Cucumber::class)
@CucumberOptions(
    features = ["@target/rerun.txt"], // @标记表示读取重跑用例列表
    glue = ["com.your.package.stepdefs"], // 替换成你的步骤定义包路径
    plugin = ["pretty", "html:target/cucumber-rerun-report.html"]
)
class FailedRunner

TestSuite的配置保持不变,确保包含rerun插件生成失败用例列表:

import org.junit.runner.RunWith
import cucumber.api.CucumberOptions
import cucumber.api.junit.Cucumber

@RunWith(Cucumber::class)
@CucumberOptions(
    features = ["src/test/resources/features"],
    glue = ["com.your.package.stepdefs"],
    plugin = ["pretty", "html:target/cucumber-report.html", "rerun:target/rerun.txt"]
)
class TestSuite

3. 配置Gradle任务

修改build.gradle.kts,让默认test任务只执行主测试,同时创建单独的重跑任务:

tasks.test {
    // 排除FailedRunner,不让默认测试任务执行它
    exclude("**/FailedRunner.class")
    // 传递环境变量(保持你的原有配置)
    systemProperty("ENV", System.getenv("ENV"))
}

// 创建专门的重跑失败用例任务
tasks.register<Test>("rerunFailedTests") {
    description = "重跑Cucumber失败用例"
    // 只执行FailedRunner
    include("**/FailedRunner.class")
    systemProperty("ENV", System.getenv("ENV"))
    // 依赖test任务,确保先跑完主测试再执行重跑
    dependsOn(tasks.test)
    // 仅当存在非空的rerun.txt时才执行
    onlyIf {
        val rerunFile = file("target/rerun.txt")
        rerunFile.exists() && rerunFile.readText().isNotBlank()
    }
}

4. 执行方式

  • 只跑主测试:ENV=dev gradle clean test
  • 跑主测试+自动重跑失败用例:ENV=dev gradle clean rerunFailedTests
  • 如果主测试没有失败,rerun任务会自动跳过

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 19:25:19