How to Rerun Failed Test Cases in Cucumber Using TestNG (Java)


Test automation often faces flaky test failures or environmental issues. Instead of rerunning the entire suite, it’s much more efficient to rerun only the failed test cases.
In this article, I’ll walk you through how to rerun failed scenarios in a Cucumber framework with a TestNG runner.
🧪 Why Rerun Failed Tests?
Saves execution time
Focuses debugging on flaky or failed tests
Reduces load on test environments and CI/CD pipelines
✅ Step-by-Step Guide
🧩 Prerequisites
Java
Maven project
Cucumber + TestNG setup
Basic understanding of feature files and step definitions
1️⃣ Update Cucumber TestNG Runner to Record Failures
Use the rerun
plugin in your Cucumber options to log failed scenarios.
@CucumberOptions(
features = "src/test/resources/features",
glue = "stepDefinitions",
plugin = {
"pretty",
"html:target/cucumber-reports",
"rerun:target/failed_scenarios.txt"
},
monochrome = true
)
public class TestRunner extends AbstractTestNGCucumberTests {
}
🔹 The rerun:target/failed_scenarios.txt
plugin creates a file with all failed scenario paths.
2️⃣ Create a Separate Runner for Failed Scenarios
This runner will pick up and execute only the failed tests from the .txt
file.
@CucumberOptions(
features = "@target/failed_scenarios.txt", // '@' tells Cucumber to read from the file
glue = "stepDefinitions",
plugin = {
"pretty",
"html:target/cucumber-reports-rerun"
},
monochrome = true
)
public class FailedTestRunner extends AbstractTestNGCucumberTests {
}
3️⃣ Execute the Test Flow
Run
TestRunner.java
to execute all testsCucumber logs any failures in
target/failed_scenarios.txt
Run
FailedTestRunner.java
to rerun only the failed scenarios
🛠 Optional: Integrate with testng.xml
<suite name="CucumberSuite">
<test name="Initial Test Run">
<classes>
<class name="runner.TestRunner"/>
</classes>
</test>
<test name="Rerun Failed Tests">
<classes>
<class name="runner.FailedTestRunner"/>
</classes>
</test>
</suite>
This ensures both test passes and reruns are managed in a single TestNG suite.
Subscribe to my newsletter
Read articles from Dinesh Y S directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by

Dinesh Y S
Dinesh Y S
Automation Engineer | Java + Selenium | Appium + Java | RestAssured | Sharing real-world automation tips