πŸ’‘ If you like this website, please share it with your friends and network! πŸš€
Back to All Scenarios
Scenario 90 of 100
BDD / Cucumber
Intermediate

Refactoring Bloated Cucumber Step Definitions

πŸ“Scenario Overview

Refactoring Bloated Cucumber Step Definitions

Key Takeaways & Cheat Sheet

  • βœ“Delegate complex UI actions to reusable Page Object helper classes
  • βœ“Keep step definition classes focused only on parameter mapping
  • βœ“Combine duplicate steps by utilizing Cucumber regular expression parameters
  • βœ“Group related step mappings into separate domain-specific classes

Short Direct Answer

Step definitions should act only as thin glue code that connects Gherkin sentences to execution logic. If step definitions become bloated with low-level details (like clicking or typing), refactor them by moving all UI actions into reusable Page Object models, leaving steps to focus solely on calling PO methods.

⚠️ Senior Warning (Red Flag)

Never write locator queries or complex click flows directly inside your Step Definitions. This leads to bloated classes that are hard to maintain when the UI changes.

πŸ’‘ STAR Deep Dive Explanation & Pro Tip

Refactoring logic into Page Objects makes your step definitions clean, readable, and easy to maintain when the frontend is updated.

SeleniumAutomation.java
Selenium 4 + Java
// ❌ BLOATED: Direct UI actions in Step Definitions
// @When("User submits order credentials")
// public void submitOrder() {
//     driver.findElement(By.id("user")).sendKeys("admin");
//     driver.findElement(By.id("pass")).sendKeys("secret");
//     driver.findElement(By.id("submit")).click();
// }

// βœ… CLEAN & REFACTORED: Delegate to Page Objects
public class LoginSteps {
    private LoginPage loginPage = new LoginPage(DriverManager.getDriver());

    @When("User submits order credentials")
    public void submitOrder() {
        loginPage.loginAs("admin", "secret"); // Reusable PO method
    }
}