Ultimate Selenium WebDriver and Cucumber Syntax Reference (2025)
✅ Ultimate Selenium WebDriver and Cucumber Syntax Reference (2025)
This guide includes the most essential Selenium WebDriver and Cucumber BDD syntax examples in Java. Each section demonstrates real-world commands and reusable automation patterns for interviews and projects.
๐ Browser Setup and Launch
System.setProperty("webdriver.chrome.driver", "./Drivers/chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(30));
driver.get("https://example.com");
๐ฑ️ Mouse and Keyboard Actions
Actions action = new Actions(driver);
WebElement src = driver.findElement(By.id("source"));
WebElement trg = driver.findElement(By.id("target"));
action.dragAndDrop(src, trg).perform();
action.contextClick(src).perform();
action.doubleClick(src).perform();
action.moveToElement(trg).perform();
๐ Dropdown Handling (Select Class)
WebElement country = driver.findElement(By.id("country"));
Select dropdown = new Select(country);
dropdown.selectByIndex(1);
dropdown.selectByValue("IND");
dropdown.selectByVisibleText("India");
๐ธ Capture Screenshot
File screenshot = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(screenshot, new File("./Screenshots/homepage.png"));
⚠️ Handling Alerts
Alert alert = driver.switchTo().alert();
System.out.println(alert.getText());
alert.accept(); // OK
// alert.dismiss(); // Cancel
๐ก JavaScriptExecutor Examples
JavascriptExecutor js = (JavascriptExecutor) driver;
// Scroll
js.executeScript("window.scrollBy(0,500)");
js.executeScript("window.scrollTo(0, document.body.scrollHeight)");
// Click using JS
WebElement element = driver.findElement(By.id("submit"));
js.executeScript("arguments[0].click();", element);
// Set value
js.executeScript("document.getElementById('username').value='Masum';");
๐ช Frame and Iframe Handling
driver.switchTo().frame(0);
driver.switchTo().frame("frameName");
driver.switchTo().frame(driver.findElement(By.xpath("//iframe[@id='demo']")));
driver.switchTo().defaultContent();
๐ Navigation Commands
driver.navigate().to("https://example.com");
driver.navigate().back();
driver.navigate().forward();
driver.navigate().refresh();
๐ Get URL and Title
System.out.println(driver.getCurrentUrl());
System.out.println(driver.getTitle());
⏳ Waits (Implicit, Explicit, Fluent)
// Implicit Wait
driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(20));
// Explicit Wait
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(20));
wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("username")));
// Fluent Wait
Wait<WebDriver> fluentWait = new FluentWait<>(driver)
.withTimeout(Duration.ofSeconds(30))
.pollingEvery(Duration.ofSeconds(5))
.ignoring(NoSuchElementException.class);
๐ Get All Links on Page
List<WebElement> links = driver.findElements(By.tagName("a"));
for (WebElement l : links) {
System.out.println(l.getText() + " --> " + l.getAttribute("href"));
}
⌨️ Element Actions
driver.findElement(By.id("username")).sendKeys("Masum");
driver.findElement(By.id("password")).sendKeys("Raza");
driver.findElement(By.id("loginBtn")).click();
๐ Excel Reader (Apache POI)
FileInputStream fis = new FileInputStream("./TestData/data.xlsx");
XSSFWorkbook wb = new XSSFWorkbook(fis);
XSSFSheet sheet = wb.getSheetAt(0);
String value = sheet.getRow(0).getCell(0).getStringCellValue();
System.out.println(value);
wb.close();
fis.close();
๐ช File Upload
WebElement upload = driver.findElement(By.id("uploadFile"));
upload.sendKeys("C:\\Users\\Masum\\Documents\\resume.pdf");
๐งฉ Multiple Windows Handling
String mainWindow = driver.getWindowHandle();
Set<String> handles = driver.getWindowHandles();
for (String handle : handles) {
if (!handle.equals(mainWindow)) {
driver.switchTo().window(handle);
System.out.println(driver.getTitle());
driver.close();
}
}
driver.switchTo().window(mainWindow);
๐ช Manage Cookies
driver.manage().addCookie(new Cookie("user", "Masum"));
Set<Cookie> cookies = driver.manage().getCookies();
for (Cookie c : cookies) {
System.out.println(c.getName() + " = " + c.getValue());
}
driver.manage().deleteAllCookies();
๐งฑ Page Factory (POM)
public class LoginPage {
WebDriver driver;
@FindBy(id = "username") WebElement username;
@FindBy(id = "password") WebElement password;
@FindBy(id = "loginBtn") WebElement loginBtn;
public LoginPage(WebDriver driver) {
this.driver = driver;
PageFactory.initElements(driver, this);
}
public void login(String user, String pass) {
username.sendKeys(user);
password.sendKeys(pass);
loginBtn.click();
}
}
๐ง Broken Link Checker
List<WebElement> links = driver.findElements(By.tagName("a"));
for (WebElement link : links) {
String url = link.getAttribute("href");
if (url != null && !url.isEmpty()) {
HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
conn.setRequestMethod("HEAD");
conn.connect();
if (conn.getResponseCode() >= 400) {
System.out.println(url + " is broken (" + conn.getResponseCode() + ")");
}
}
}
๐งช TestNG Grouping Example
import org.testng.annotations.Test;
public class GroupingExample {
@Test(groups = {"sanity"})
public void test1() { System.out.println("Sanity Test 1"); }
@Test(groups = {"sanity", "regression"})
public void test2() { System.out.println("Sanity & Regression Test 2"); }
@Test(groups = {"regression"})
public void test3() { System.out.println("Regression Test 3"); }
}
๐งฉ TestNG Suite XML
<suite name="TestSuite">
<test name="GroupedTests">
<groups>
<run>
<include name="sanity"/>
</run>
</groups>
<classes>
<class name="GroupingExample"/>
</classes>
</test>
</suite>
๐ฟ Cucumber BDD Example
Below is a complete Cucumber + Selenium setup example (Feature file + Step Definitions).
๐ Feature File (Login.feature)
Feature: Login Functionality
Scenario: Verify valid login
Given user launches the browser
When user opens "https://example.com/login"
And user enters username "Masum" and password "Raza"
And clicks on Login button
Then user should be redirected to Dashboard
๐งฉ Step Definition (LoginSteps.java)
public class LoginSteps {
WebDriver driver;
@Given("user launches the browser")
public void launchBrowser() {
WebDriverManager.chromedriver().setup();
driver = new ChromeDriver();
driver.manage().window().maximize();
}
@When("user opens {string}")
public void openUrl(String url) {
driver.get(url);
}
@When("user enters username {string} and password {string}")
public void enterCredentials(String user, String pass) {
driver.findElement(By.id("username")).sendKeys(user);
driver.findElement(By.id("password")).sendKeys(pass);
}
@When("clicks on Login button")
public void clickLogin() {
driver.findElement(By.id("loginBtn")).click();
}
@Then("user should be redirected to Dashboard")
public void verifyDashboard() {
Assert.assertTrue(driver.getTitle().contains("Dashboard"));
driver.quit();
}
}
✅ Conclusion:
This one-stop Selenium + Cucumber syntax guide gives you all essential automation code snippets — from browser setup, waits, alerts, and frames to Cucumber step definitions and TestNG grouping. Bookmark it for your automation projects and interview prep!