๐Ÿš€ Ultimate Selenium 4 + Cucumber + TestNG Framework Guide (2025 Interview Mastery)

๐Ÿš€ Ultimate Selenium + Cucumber Framework Guide (Interview 2025)

๐Ÿ’ก A complete reference for Selenium 4, Cucumber BDD, TestNG, XPath, and OOP-based Automation Frameworks — ideal for interviews and real project design.


๐Ÿ” What is Selenium?

Selenium is an open-source automation testing framework for web applications. It supports multiple browsers and languages (Java, Python, C#) and enables automation across OS platforms.

⚙️ Selenium 3 vs Selenium 4 Architecture

  • Selenium 3: Communicated via JSON Wire Protocol between client and browser driver.
  • Selenium 4: Fully compliant with W3C WebDriver Protocol, supports Relative Locators, and provides access to Chrome DevTools Protocol (CDP) for capturing console logs, network, and performance data.

๐Ÿง  OOP Concepts in Selenium Framework (Interview Key)

Interview Question: “Where do you use OOPs concepts in your automation framework?”

Answer: OOPs concepts — Encapsulation, Inheritance, Abstraction, and Polymorphism — make Selenium frameworks modular, reusable, and scalable.

๐Ÿงฉ Encapsulation (Used in Page Object Model)

Theory: Encapsulation binds WebElements and related actions in one class, protecting data from outside access. In Selenium, it is implemented via Page Object Model (POM).

// LoginPage.java
public class LoginPage {
  private WebDriver driver;

  // Locators encapsulated
  @FindBy(id="username") private WebElement username;
  @FindBy(id="password") private WebElement password;
  @FindBy(id="loginBtn") private WebElement loginBtn;

  // Constructor to initialize driver
  public LoginPage(WebDriver driver) {
    this.driver = driver;
    PageFactory.initElements(driver, this);
  }

  // Public method to perform login action
  public void login(String user, String pass) {
    username.sendKeys(user);
    password.sendKeys(pass);
    loginBtn.click();
  }
}

๐Ÿ”— Inheritance (Used in Base and Test Classes)

Theory: Inheritance promotes code reuse by allowing child test classes to inherit setup/teardown logic from a base class.

// BaseTest.java
public class BaseTest {
  protected WebDriver driver;

  @BeforeMethod
  public void setUp() {
    // Browser setup reusable by all tests
    WebDriverManager.chromedriver().setup();
    driver = new ChromeDriver();
    driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(10));
  }

  @AfterMethod
  public void tearDown() { driver.quit(); }
}

๐Ÿง  Abstraction (Used in Utility / Helper Classes)

Theory: Abstraction hides complex internal logic. For example, a WaitHelper class abstracts WebDriverWait details.

// IWait.java
public interface IWait {
  WebElement waitVisible(By locator, Duration time);
}

// WaitHelper.java
public class WaitHelper implements IWait {
  private WebDriver driver;
  public WaitHelper(WebDriver driver){ this.driver = driver; }

  public WebElement waitVisible(By locator, Duration time) {
    return new WebDriverWait(driver, time)
      .until(ExpectedConditions.visibilityOfElementLocated(locator));
  }
}

๐Ÿ”„ Polymorphism (Used in Method Overloading/Overriding)

Theory: Polymorphism allows different forms of the same method. In frameworks, we overload helper methods to handle multiple cases.

// ClickHelper.java
public class ClickHelper {
  private WebDriver driver;
  public ClickHelper(WebDriver driver){ this.driver = driver; }

  // Overloaded click methods
  public void click(By locator){ driver.findElement(locator).click(); }
  public void click(WebElement element){ element.click(); }
  public void click(By locator, Duration wait){
    new WebDriverWait(driver, wait)
      .until(ExpectedConditions.elementToBeClickable(locator)).click();
  }
}

๐ŸŒ Selenium 4 WebDriver Syntax

๐Ÿš€ Browser Setup

// Launch Chrome browser
WebDriverManager.chromedriver().setup();
WebDriver driver = new ChromeDriver();
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(10));
driver.get("https://example.com");

๐Ÿงญ Locators & Element Interaction

// Locate and interact with elements
driver.findElement(By.id("username")).sendKeys("Masum");
driver.findElement(By.name("password")).sendKeys("Raza");
driver.findElement(By.cssSelector(".btn")).click();
System.out.println(driver.findElement(By.tagName("h2")).getText());

๐Ÿ–ฑ️ Actions Class (Mouse & Keyboard)

// Perform complex user interactions
Actions act = new Actions(driver);
act.moveToElement(driver.findElement(By.id("menu"))).perform();   // Hover
act.doubleClick(driver.findElement(By.id("edit"))).perform();     // Double click
act.dragAndDrop(src, trg).perform();                              // Drag & drop

๐Ÿ“‹ Dropdown Handling (Select Class)

// Select dropdown options
Select sel = new Select(driver.findElement(By.id("country")));
sel.selectByVisibleText("India");
sel.selectByValue("IND");
sel.selectByIndex(2);

⚠️ Alert Handling

// Handle alert pop-ups
Alert alert = driver.switchTo().alert();
System.out.println(alert.getText());
alert.accept();  // OK
// alert.dismiss(); // Cancel

๐Ÿ’ก JavaScriptExecutor — Full Command Set

// Initialize JS executor
JavascriptExecutor js = (JavascriptExecutor) driver;

// ✅ Scroll operations
js.executeScript("window.scrollBy(0,500)");
js.executeScript("window.scrollTo(0, document.body.scrollHeight)");
js.executeScript("window.scrollTo(0, 0)"); // Scroll to top

// ✅ Scroll to a specific element
WebElement element = driver.findElement(By.id("target"));
js.executeScript("arguments[0].scrollIntoView(true);", element);

// ✅ Click element using JS
js.executeScript("arguments[0].click();", driver.findElement(By.id("submit")));

// ✅ Set and get values
js.executeScript("document.getElementById('username').value='Masum';");
String val = (String) js.executeScript("return document.getElementById('username').value;");
System.out.println(val);

// ✅ Highlight element (debugging)
WebElement box = driver.findElement(By.id("highlight"));
js.executeScript("arguments[0].style.border='3px solid red'", box);

// ✅ Enable / Disable elements
WebElement btn = driver.findElement(By.id("login"));
js.executeScript("arguments[0].removeAttribute('disabled')", btn);

// ✅ Retrieve hidden text
WebElement hidden = driver.findElement(By.id("hiddenText"));
String hiddenText = (String) js.executeScript("return arguments[0].textContent;", hidden);
System.out.println(hiddenText);

// ✅ Refresh or Zoom
js.executeScript("history.go(0)");
js.executeScript("document.body.style.zoom='90%'");

๐Ÿงฉ Frame & iFrame Handling

driver.switchTo().frame(0);
driver.switchTo().frame("frameName");
driver.switchTo().frame(driver.findElement(By.tagName("iframe")));
driver.switchTo().defaultContent();

๐Ÿ”— Navigation Commands

driver.navigate().to("https://site.com");
driver.navigate().back();
driver.navigate().forward();
driver.navigate().refresh();

๐ŸชŸ Multiple Window Handling

// Switch between windows
String main = driver.getWindowHandle();
for (String handle : driver.getWindowHandles()) {
  if (!handle.equals(main)) {
    driver.switchTo().window(handle);
    System.out.println(driver.getTitle());
    driver.close();
  }
}
driver.switchTo().window(main);

๐Ÿช Cookies Management

driver.manage().addCookie(new Cookie("user","Masum"));
for(Cookie c: driver.manage().getCookies())
  System.out.println(c.getName() + "=" + c.getValue());
driver.manage().deleteAllCookies();

⏳ Waits (Implicit / Explicit / Fluent)

// Implicit wait
driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(10));

// Explicit wait
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(20));
wait.until(ExpectedConditions.titleContains("Home"));

// Fluent wait
Wait fluent = new FluentWait<>(driver)
  .withTimeout(Duration.ofSeconds(30))
  .pollingEvery(Duration.ofSeconds(5))
  .ignoring(NoSuchElementException.class);

๐Ÿ“ธ Screenshot Capture

File src = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(src, new File("./Screenshots/image.png"));

๐Ÿ“ Excel Reader (Apache POI)

// Read data from Excel
FileInputStream fis = new FileInputStream("./TestData/data.xlsx");
XSSFWorkbook wb = new XSSFWorkbook(fis);
String val = wb.getSheetAt(0).getRow(0).getCell(0).getStringCellValue();
System.out.println(val);
wb.close(); fis.close();

๐Ÿ” Broken Link Checker

// Check all links on page
List links = driver.findElements(By.tagName("a"));
for (WebElement l : links) {
  String url = l.getAttribute("href");
  if (url != null && !url.isEmpty()) {
    HttpURLConnection c = (HttpURLConnection)new URL(url).openConnection();
    c.setRequestMethod("HEAD");
    c.connect();
    if (c.getResponseCode() >= 400)
      System.out.println(url + " is broken link");
  }
}

๐Ÿงญ XPath Syntax Reference

//tagName[@attribute='value']
//tagName[contains(@attribute,'value')]
//tagName[starts-with(@attribute,'value')]
//tagName[text()='value']
//tagName[contains(text(),'partialvalue')]
//tagName[@attribute='value']/parent::tagname
//tagName[@attribute='value']/following-sibling::tagname
//tagName[@attribute='value']/preceding-sibling::tagname[1]

๐Ÿฅ’ Cucumber BDD Integration

Feature File (Login.feature)

Feature: Login Functionality
  @smoke @login
  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 see the Dashboard

Runner Class (With Glue & Tags)

@RunWith(Cucumber.class)
@CucumberOptions(
  features = "src/test/resources/features",
  glue = {"com.framework.steps","com.framework.hooks"},
  plugin = {"pretty","html:target/cucumber.html"},
  tags = "@smoke"
)
public class RunTest { }

Hooks

public class Hooks {
  public static WebDriver driver;

  @Before
  public void setup(){
    WebDriverManager.chromedriver().setup();
    driver = new ChromeDriver();
  }

  @After
  public void tearDown(Scenario sc){
    if(sc.isFailed())
      System.out.println("Scenario failed: " + sc.getName());
    driver.quit();
  }
}

๐Ÿงช TestNG Grouping & Annotations

public class GroupingExample {
  @Test(groups={"sanity"})
  public void sanityTest(){ System.out.println("Sanity Test"); }

  @Test(groups={"regression"})
  public void regressionTest(){ System.out.println("Regression Test"); }
}

TestNG Annotations Overview

@BeforeSuite  → Runs once before all tests
@BeforeTest   → Runs before any test in  tag
@BeforeClass  → Runs before first method in class
@BeforeMethod → Runs before each test
@Test         → Marks the test case
@AfterMethod  → Runs after each test
@AfterClass   → Runs after all test methods
@AfterTest    → Runs after all tests in 
@AfterSuite   → Runs once after entire suite

๐Ÿ—️ Hybrid Framework Structure

project-root/
├─ src/main/java/com.framework/base/
├─ src/main/java/com.framework/pages/
├─ src/main/java/com.framework/utils/
├─ src/test/java/com.framework/steps/
├─ src/test/java/com.framework/hooks/
├─ src/test/resources/features/
└─ Reports/
  • POM: Encapsulation of page elements and actions
  • TestNG: Execution control and grouping
  • Cucumber: BDD-based step definitions
  • Data Driven: Excel-driven test input
  • Reports: Extent, Allure, or Cucumber HTML

Created by Masum Raza — Automation Test Engineer

Popular posts from this blog

Explore essential Java programs commonly asked in interviews, offering valuable coding insights and practice.

Here is the content refined for clarity and professionalism suitable for someone preparing for a QA Automation interview:

Comprehensive Selenium WebDriver Syntax for Effective Test Automation