Answer
Step Definition File Example
Basic Login Step Definition
Java
package stepDefinitions;
import io.cucumber.java.After;
import io.cucumber.java.Before;
import io.cucumber.java.en.Given;
import io.cucumber.java.en.When;
import io.cucumber.java.en.Then;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.By;
import static org.testng.Assert.*;
public class LoginStepDefinitions {
WebDriver driver;
@Before
public void setUp() {
driver = new ChromeDriver();
driver.manage().window().maximize();
}
// Maps to: Given the user opens Chrome browser and launches the application
@Given("the user opens Chrome browser and launches the application")
public void openBrowser() {
driver.get("https://www.example.com");
}
// Maps to: When the user enters the username "admin"
@When("the user enters the username {string}")
public void enterUsername(String username) {
driver.findElement(By.id("username")).sendKeys(username);
}
// Maps to: And the user enters the password "Admin@123"
@When("the user enters the password {string}")
public void enterPassword(String password) {
driver.findElement(By.id("password")).sendKeys(password);
}
// Maps to: And the user clicks on the Login button
@When("the user clicks on the Login button")
public void clickLogin() {
driver.findElement(By.id("loginBtn")).click();
}
// Maps to: Then the user should be on the dashboard
@Then("the user should be on the dashboard")
public void verifyDashboard() {
String title = driver.getTitle();
assertTrue(title.contains("Dashboard"), "Dashboard not loaded. Title: " + title);
}
@After
public void tearDown(io.cucumber.java.Scenario scenario) {
if (scenario.isFailed()) {
// Take screenshot on failure
byte[] screenshot = ((org.openqa.selenium.TakesScreenshot) driver)
.getScreenshotAs(org.openqa.selenium.OutputType.BYTES);
scenario.attach(screenshot, "image/png", "Failure Screenshot");
}
if (driver != null) {
driver.quit();
}
}
}
Step Definition with @CucumberOptions Annotation Example
Java
// The step below corresponds to feature file step:
// Given "^Open Chrome browser and launch the application$"
@Given("^Open Chrome browser and launch the application$")
public void openBrowser() {
driver = new ChromeDriver();
driver.manage().window().maximize();
driver.get("www.facebook.com");
}
Important Notes
- ✓Method name doesn't matter — only the annotation text matters for matching
- ✓Use
{string}for quoted parameters,{int}for numbers - ✓
@Beforeand@Afterare hooks — not step definitions - ✓Step text must exactly match the feature file (Cucumber is case-sensitive)
