</>

Technology

Cucumber

Difficulty

Advanced

Interview Question

How do you rerun only failed Cucumber scenarios?

Answer

Rerunning Failed Cucumber Scenarios

Step 1: Primary Runner — Write Failed to File

Java
@CucumberOptions(
    features = "src/test/resources/features",
    glue = {"stepDefinitions", "hooks"},
    plugin = {
        "pretty",
        "html:target/reports/cucumber.html",
        "json:target/reports/cucumber.json",
        "rerun:target/rerun/failed_scenarios.txt"  // ← key plugin
    }
)
public class TestRunner extends AbstractTestNGCucumberTests {}

After test execution, failed_scenarios.txt contains:

CODE
src/test/resources/features/login.feature:15
src/test/resources/features/checkout.feature:42
src/test/resources/features/payment.feature:8

Step 2: Rerun Runner — Use Failed File as Input

Java
@CucumberOptions(
    features = "@target/rerun/failed_scenarios.txt",  // ← @ prefix = file input
    glue = {"stepDefinitions", "hooks"},
    plugin = {
        "pretty",
        "html:target/reports/rerun-report.html",
        "json:target/reports/rerun.json"
    }
)
public class RerunTestRunner extends AbstractTestNGCucumberTests {}

Maven Profiles for Rerun Flow

XML
<profiles>
    <!-- Profile 1: Full run -->
    <profile>
        <id>regression</id>
        <properties>
            <runner>runners.TestRunner</runner>
        </properties>
    </profile>

    <!-- Profile 2: Rerun failures only -->
    <profile>
        <id>rerun</id>
        <properties>
            <runner>runners.RerunTestRunner</runner>
        </properties>
    </profile>
</profiles>
Bash
# Full run
mvn test -Pregression

# Rerun only failures
mvn test -Prerun

Jenkins Pipeline — Automatic Rerun

GROOVY
stage('Run Tests') {
    steps {
        sh 'mvn clean test -Pregression'
    }
}

stage('Rerun Failed Tests') {
    when {
        expression {
            fileExists('target/rerun/failed_scenarios.txt') &&
            readFile('target/rerun/failed_scenarios.txt').trim() != ''
        }
    }
    steps {
        sh 'mvn test -Prerun'
    }
}

Maven Surefire rerunFailingTestsCount

XML
<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-surefire-plugin</artifactId>
    <configuration>
        <rerunFailingTestsCount>2</rerunFailingTestsCount>  <!-- retry 2x -->
    </configuration>
</plugin>

Comparison of Rerun Methods

MethodGranularitySetup
rerun pluginScenario-level2 runners needed
rerunFailingTestsCountMethod-levelpom.xml change only
Retry with IRetryAnalyzerTestNG methodJava code needed

Follow AutomateQA

Related Topics