Testing / Cucumber Interview Questions
Why should step definitions avoid containing assertions tightly coupled to UI selectors?
A step definition that hardcodes specific UI selectors (like a CSS class or XPath) directly alongside its assertion logic becomes fragile in two compounding ways: any change to the UI's markup breaks the step definition, and because the same step definition is often reused across many scenarios, that single fragile coupling point can break a large portion of the suite at once from one unrelated markup change.
// Fragile: selector and assertion tangled together in the step definition @Then("the user should see the dashboard") public void the_user_should_see_the_dashboard() { assertTrue(driver.findElement(By.cssSelector(".dash-header-v2")).isDisplayed()); } // More resilient: selector lives in a page object, step definition stays declarative @Then("the user should see the dashboard") public void the_user_should_see_the_dashboard() { assertTrue(dashboardPage.isDisplayed()); }
Isolating selectors inside a dedicated page object (or equivalent abstraction) layer, with step definitions calling into that layer rather than embedding selectors directly, means a UI redesign only requires updating the page object's internals in one place, leaving every step definition (and, by extension, every scenario relying on it) untouched. This separation is really the same core idea behind declarative Gherkin style, applied one layer down, inside the step definitions themselves rather than just the feature file text.
More Related questions...