0% found this document useful (0 votes)
2 views37 pages

WebAutomation Testing Guide

Uploaded by

neevangood
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views37 pages

WebAutomation Testing Guide

Uploaded by

neevangood
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Web Automation Testing

Comprehensive Study Guide

✓ Selenium WebDriver
✓ TestNG Framework
✓ Apache POI
✓ Page Object Model (POM)
✓ Hybrid Driven Development
✓ Cucumber BDD Framework
✓ DevOps for Testers
✓ Mini Project
✓ 100 Interview Questions
✓ 50 Real-Time Scenario Questions

For professionals with basic knowledge of web automation


Table of Contents
1. Selenium WebDriver ..................................... 3
2. TestNG Framework ....................................... 5
3. Apache POI ............................................. 7
4. Page Object Model (POM) ................................ 9
5. Hybrid Driven Development .............................. 11
6. Cucumber BDD Framework ................................. 13
7. DevOps for Testers ..................................... 15
8. Mini Project – End-to-End Framework .................... 17
9. 100 Interview Questions & Answers ...................... 19
10. 50 Real-Time Scenario Questions ........................ 35
1. Selenium WebDriver

1.1 Overview
Selenium is an open-source suite of tools for automating web browsers. It is the industry-standard for web
automation testing and supports multiple programming languages (Java, Python, C#, Ruby, JavaScript)
and all major browsers.

1.2 Selenium Suite Components


Selenium IDE: A browser extension (Chrome/Firefox) for record-and-playback. Great for quick
prototyping but not suitable for large-scale test suites.
Selenium WebDriver: The core API that communicates directly with browser drivers. Supports parallel
execution and integrates with frameworks like TestNG/JUnit.
Selenium Grid: Allows running tests in parallel across multiple machines, browsers, and OS
combinations simultaneously.
Selenium RC (deprecated): Older version replaced by WebDriver. Requires a Selenium server to run.

1.3 WebDriver Architecture


WebDriver follows a client-server architecture. The test script (client) sends JSON Wire Protocol / W3C
WebDriver Protocol commands to the browser driver (e.g., ChromeDriver), which then controls the actual
browser.

Flow: Test Script → WebDriver API → Browser Driver → Browser

1.4 Setting Up Selenium (Java + Maven)


<dependency>
<groupId>[Link]</groupId>
<artifactId>selenium-java</artifactId>
<version>4.18.1</version>
</dependency>

1.5 Core WebDriver Commands


Command Description

[Link](url) Opens a URL in the browser

[Link]([Link]("id")) Locates a single element by ID

[Link]([Link]("c")) Returns a list of elements

[Link]() Clicks on a web element

[Link]("text") Types text into an input field

[Link]() Retrieves visible text of element

[Link]().back() Navigates to the previous page


[Link]().frame("name") Switches context to an iframe

[Link]() Closes all windows and ends session

1.6 Locator Strategies


• ID – Fastest and most reliable when available
• Name – Uses the 'name' attribute of an element
• ClassName – Locates by CSS class name
• TagName – Locates by HTML tag (e.g., 'input', 'button')
• LinkText – Full visible text of an anchor tag
• PartialLinkText – Partial visible text of an anchor tag
• CssSelector – Uses CSS selectors; fast and flexible
• XPath – Most powerful; can traverse parent-child relationships

1.7 Waits in Selenium


• Implicit Wait: Instructs WebDriver to wait a set time before throwing NoSuchElementException.
Applied globally.
[Link]().timeouts().implicitlyWait([Link](10));

• Explicit Wait: Waits for a specific condition to be true before proceeding.


WebDriverWait wait = new WebDriverWait(driver, [Link](15));
WebElement el = [Link]([Link]([Link]("my
Id")));

• Fluent Wait: Like explicit wait but allows polling intervals and ignoring specific exceptions.

1.8 Handling Special Scenarios


• Alerts: [Link]().alert().accept() / dismiss() / getText()
• Multiple Windows: Use [Link]() to iterate and switch
• iFrames: [Link]().frame() then [Link]().defaultContent()
• Actions Class: For mouse hover, drag-and-drop, right-click, keyboard combos
• JavascriptExecutor: Execute JS directly – scrolling, clicking hidden elements
• ScreenShot: TakesScreenshot interface for capturing failure evidence
2. TestNG Framework

2.1 Overview
TestNG (Test Next Generation) is a powerful testing framework inspired by JUnit and NUnit. It overcomes
the limitations of JUnit by introducing features like grouping, sequencing, parameterization, and parallel
execution. It is the most widely used framework with Selenium for Java-based automation.

2.2 Key Annotations


Annotation Description

@BeforeSuite Runs once before all tests in the suite

@AfterSuite Runs once after all tests in the suite

@BeforeTest Runs before any test method in a <test> tag

@AfterTest Runs after all test methods in a <test> tag

@BeforeClass Runs once before the first method of the current class

@AfterClass Runs once after all methods of the current class

@BeforeMethod Runs before each @Test method

@AfterMethod Runs after each @Test method

@Test Marks a method as a test case

@DataProvider Supplies data to a test method for data-driven testing

@Parameters Passes parameters from [Link] to a test method

@Listeners Registers listener classes for custom reporting/logging

2.3 [Link] Configuration


<suite name="RegressionSuite" parallel="classes" thread-count="3">
<test name="LoginTests">
<parameter name="browser" value="chrome"/>
<classes>
<class name="[Link]"/>
<class name="[Link]"/>
</classes>
</test>
</suite>

2.4 Data-Driven Testing with @DataProvider


@DataProvider(name = "loginData")
public Object[][] getLoginData() {
return new Object[][] {
{"user1@[Link]", "Pass@123"},
{"user2@[Link]", "Pass@456"}
};
}
@Test(dataProvider = "loginData")
public void testLogin(String email, String password) {
[Link](email, password);
[Link]([Link]());
}

2.5 Grouping & Prioritization


• Groups: @Test(groups = {"smoke", "regression"}) – run specific groups via [Link]
• Priority: @Test(priority = 1) – lower number runs first (default: 0)
• dependsOnMethods: @Test(dependsOnMethods = {"testLogin"}) – ensures execution order
• Parallel Execution: Set parallel="methods"/"classes"/"tests" in [Link]

2.6 Assertions
• [Link](actual, expected) – Hard assertion; fails immediately
• [Link](condition) – Verifies condition is true
• [Link](condition) – Verifies condition is false
• [Link](object) – Verifies object is not null
• [Link]() – Collects all failures before reporting

2.7 Listeners (ITestListener)


Listeners allow custom behavior on test events like pass, fail, skip. Implement ITestListener interface and
override onTestFailure() to take screenshots automatically.
public class TestListeners implements ITestListener {
@Override
public void onTestFailure(ITestResult result) {
// Capture screenshot on failure
TakesScreenshot ts = (TakesScreenshot) driver;
File src = [Link]([Link]);
}
}
3. Apache POI

3.1 Overview
Apache POI is a Java library for reading and writing Microsoft Office documents. In test automation, it is
primarily used to read test data from Excel (.xlsx) files, enabling data-driven testing without hardcoding
values in test scripts.

3.2 Key Classes


XSSFWorkbook – Represents an Excel 2007+ (.xlsx) workbook
XSSFSheet – Represents a single sheet within the workbook
XSSFRow – Represents a row in the sheet
XSSFCell – Represents a cell in a row
HSSFWorkbook – Represents older Excel 97-2003 (.xls) format
CellType – Enum for cell types: STRING, NUMERIC, BOOLEAN, FORMULA, BLANK

3.3 Maven Dependency


<dependency>
<groupId>[Link]</groupId>
<artifactId>poi-ooxml</artifactId>
<version>5.2.5</version>
</dependency>

3.4 Reading Excel Data – Utility Class


public class ExcelUtils {
private XSSFWorkbook workbook;
private XSSFSheet sheet;

public ExcelUtils(String filePath, String sheetName) throws Exception {


FileInputStream fis = new FileInputStream(filePath);
workbook = new XSSFWorkbook(fis);
sheet = [Link](sheetName);
}

public String getCellData(int rowNum, int colNum) {


XSSFRow row = [Link](rowNum);
XSSFCell cell = [Link](colNum);
if ([Link]() == [Link])
return [Link]((int) [Link]());
return [Link]();
}

public int getRowCount() { return [Link](); }


public int getColCount(int rowNum) { return [Link](rowNum).getLastCellNum(
); }
}
3.5 Writing Data to Excel
public void setCellData(int rowNum, int colNum, String data) throws Exception {
XSSFRow row = [Link](rowNum);
if (row == null) row = [Link](rowNum);
XSSFCell cell = [Link](colNum);
[Link](data);
FileOutputStream fos = new FileOutputStream(filePath);
[Link](fos);
[Link]();
}

3.6 Integration with TestNG DataProvider


Apache POI is typically used inside a @DataProvider method in TestNG to supply rows of test data to test
methods. The ExcelUtils utility class is instantiated, and the getRowCount() and getCellData() methods are
used to dynamically populate the data array returned by the @DataProvider.
• Keep Excel test data files in a 'testdata' folder under the project root
• Always close streams (FileInputStream/FileOutputStream) after use to avoid file locks
• Handle [Link] carefully – POI reads numbers as doubles by default
• Use DataFormatter class to get cell value as-is, regardless of cell type
4. Page Object Model (POM) Design Pattern

4.1 Overview
Page Object Model is a design pattern where each web page or component is represented by a Java
class. The class contains element locators (WebElements) and methods (actions) that can be performed
on that page. This separates page structure from test logic, improving maintainability and reusability.

4.2 Benefits of POM


• Maintainability – If the UI changes, update only the Page class, not every test
• Reusability – Page methods can be reused across multiple test classes
• Readability – Tests read like business workflows, not Selenium commands
• Reduced Duplication – Locators defined once, used everywhere
• Better Collaboration – Testers/developers can work on pages/tests independently

4.3 Project Structure


src/
■■■ main/java/
■ ■■■ pages/
■ ■■■ [Link]
■ ■■■ [Link]
■ ■■■ [Link]
■■■ test/java/
■ ■■■ tests/
■ ■■■ [Link]
■ ■■■ [Link]
■■■ resources/
■■■ [Link]
■■■ testdata/[Link]

4.4 [Link]
public class BasePage {
protected WebDriver driver;
protected WebDriverWait wait;

public BasePage(WebDriver driver) {


[Link] = driver;
[Link] = new WebDriverWait(driver, [Link](15));
[Link](driver, this);
}

protected void click(WebElement element) {


[Link]([Link](element)).click();
}

protected void type(WebElement element, String text) {


[Link]([Link](element));
[Link]();
[Link](text);
}
}

4.5 [Link] with @FindBy


public class LoginPage extends BasePage {

@FindBy(id = "username")
private WebElement usernameField;

@FindBy(id = "password")
private WebElement passwordField;

@FindBy(css = "button[type='submit']")
private WebElement loginButton;

@FindBy(className = "error-msg")
private WebElement errorMessage;

public LoginPage(WebDriver driver) { super(driver); }

public DashboardPage login(String username, String password) {


type(usernameField, username);
type(passwordField, password);
click(loginButton);
return new DashboardPage(driver);
}

public String getErrorMessage() {


return [Link]();
}
}

4.6 PageFactory
PageFactory is a class in Selenium that supports the @FindBy annotation. It lazily initializes WebElements
– the element is only located in the DOM when it is first accessed in a method, not at object creation time.
This avoids StaleElementReferenceException in many scenarios.
[Link](driver, this); // Must be called in constructor
5. Hybrid Driven Development

5.1 Overview
Hybrid Driven Development is a combination of multiple test automation frameworks – typically Data
Driven, Keyword Driven, and Behavior Driven approaches. It leverages the strengths of each framework to
create a robust, scalable, and maintainable automation suite.

5.2 Frameworks Combined


Data Driven
Test data is externalized (Excel, CSV, DB). Same test logic, multiple data sets. Uses Apache POI +
TestNG @DataProvider.

Keyword Driven
Actions (click, type, verify) are defined as keywords in a spreadsheet. Non-technical users can define test
cases. Framework reads keywords and executes corresponding Java methods.

Behavior Driven (BDD)


Tests written in plain English using Gherkin (Given-When-Then). Bridges gap between business and
development teams. Implemented via Cucumber.

Page Object Model


Structural design pattern that organizes WebElements and page actions into dedicated classes.

Modular Framework
Test scripts are broken into reusable modules (login module, search module, etc.) that can be combined.

5.3 Hybrid Framework Architecture


HybridFramework/
■■■ config/
■ ■■■ [Link] (URLs, credentials, browser)
■■■ pages/ (POM layer)
■■■ tests/ (TestNG test classes)
■■■ utilities/
■ ■■■ [Link] (Apache POI)
■ ■■■ [Link] (Browser setup)
■ ■■■ [Link] (Properties file reader)
■ ■■■ [Link] (Failure evidence)
■■■ testdata/
■ ■■■ [Link]
■■■ keywords/
■ ■■■ [Link] (maps keywords to actions)
■■■ reports/
■ ■■■ ExtentReports/ (HTML reports)
■■■ [Link]

5.4 [Link] Example


browser=chrome
baseUrl=[Link]
implicitWait=10
explicitWait=15
screenshotPath=./screenshots/

5.5 ConfigReader Utility


public class ConfigReader {
private Properties prop;

public ConfigReader() throws Exception {


prop = new Properties();
FileInputStream fis = new FileInputStream("config/[Link]");
[Link](fis);
}

public String getBrowser() { return [Link]("browser"); }


public String getBaseUrl() { return [Link]("baseUrl"); }
}

5.6 DriverFactory
public class DriverFactory {
private static ThreadLocal<WebDriver> driver = new ThreadLocal<>();

public static WebDriver getDriver(String browser) {


if ([Link]("chrome"))
[Link](new ChromeDriver());
else if ([Link]("firefox"))
[Link](new FirefoxDriver());
return [Link]();
}

public static WebDriver getDriver() { return [Link](); }


public static void quitDriver() { [Link]().quit(); [Link](); }
}

Using ThreadLocal ensures thread-safety when running tests in parallel – each thread gets its own
WebDriver instance.
6. Cucumber BDD Framework

6.1 Overview
Cucumber is a BDD (Behavior Driven Development) tool that lets you write test scenarios in plain English
using the Gherkin syntax (Given-When-Then). It bridges the communication gap between business
stakeholders, QA engineers, and developers by creating living documentation.

6.2 Gherkin Syntax


Feature: User Login Functionality

Background:
Given the user is on the login page

Scenario: Successful Login with valid credentials


When the user enters username "admin@[Link]"
And the user enters password "Admin@123"
And the user clicks the Login button
Then the user should be redirected to the Dashboard
And the welcome message should display "Welcome, Admin"

Scenario Outline: Login with multiple users


When the user enters username "<username>"
And the user enters password "<password>"
Then the login result should be "<result>"

Examples:
| username | password | result |
| admin@[Link] | Admin@123 | success |
| wrong@[Link] | wrong123 | failure |

6.3 Step Definitions


public class LoginSteps {
private WebDriver driver;
private LoginPage loginPage;

@Given("the user is on the login page")


public void userOnLoginPage() {
driver = [Link]("chrome");
[Link]("[Link]
loginPage = new LoginPage(driver);
}

@When("the user enters username {string}")


public void enterUsername(String username) {
[Link](username);
}

@Then("the user should be redirected to the Dashboard")


public void verifyDashboard() {
[Link](new DashboardPage(driver).isLoaded());
}
}

6.4 Cucumber Runner Class


@RunWith([Link])
@CucumberOptions(
features = "src/test/resources/features",
glue = "stepDefinitions",
plugin = {
"pretty",
"html:target/[Link]",
"json:target/[Link]"
},
tags = "@regression",
monochrome = true
)
public class TestRunner {}

6.5 Hooks
public class Hooks {
@Before
public void setUp(Scenario scenario) {
// Initialize WebDriver before each scenario
}

@After
public void tearDown(Scenario scenario) {
if ([Link]()) {
// Take screenshot and attach to report
}
[Link]();
}
}

6.6 Tags in Cucumber


• @smoke – Marks a scenario as part of the smoke test suite
• @regression – Full regression suite scenarios
• @wip – Work-in-progress scenarios (often excluded from CI)
• Tags can be combined: @CucumberOptions(tags = "@smoke and @regression")
• Negative tags: @CucumberOptions(tags = "not @wip")
7. DevOps for Test Automation Engineers

7.1 Overview
DevOps integrates development and operations practices to enable continuous delivery. As a test
automation engineer, understanding DevOps helps you integrate your tests into CI/CD pipelines so tests
run automatically on every code commit.

7.2 Key DevOps Tools for Testers


Git / GitHub / GitLab – Version control for test code. Essential for team collaboration.
Jenkins – Open-source CI/CD automation server. Runs your TestNG/Maven tests on every push.
Maven / Gradle – Build tools that manage dependencies and compile/run tests via command line.
Docker – Containerizes the test environment, ensuring consistency across dev/staging/prod.
Selenium Grid / Zalenium – Distributed test execution across multiple browsers/nodes.
Allure / ExtentReports – Rich HTML test reports integrated into the CI pipeline.
JIRA / Zephyr – Test management and defect tracking integration.
SonarQube – Code quality analysis for test automation code.

7.3 Git Workflow for Automation Teams


• Feature Branch Workflow: Create a branch for each feature/fix, merge via Pull Request
• Git commands: git clone, git pull, git add, git commit -m, git push, git merge
• Always add test reports, .class files, screenshots to .gitignore
• Protect the main branch – require PR reviews before merging

7.4 Jenkins Pipeline (Declarative)


pipeline {
agent any
stages {
stage('Checkout') {
steps { git '[Link] }
}
stage('Build') {
steps { sh 'mvn clean compile' }
}
stage('Test') {
steps { sh 'mvn test -Dbrowser=chrome -Dgroups=regression' }
}
stage('Reports') {
steps { publishHTML(target: [reportDir: 'target/reports', reportFiles: 'inde
[Link]']) }
}
}
post {
failure { emailext subject: 'Test Failure', body: 'Check Jenkins for details'
}
}
}

7.5 Docker for Selenium


# [Link] for Selenium Grid
version: '3'
services:
selenium-hub:
image: selenium/hub:4.18
ports: ["4442:4442", "4443:4443", "4444:4444"]

chrome:
image: selenium/node-chrome:4.18
depends_on: [selenium-hub]
environment:
SE_EVENT_BUS_HOST: selenium-hub
deploy:
replicas: 3

7.6 Maven Commands


• mvn clean test – Clean build and run all tests
• mvn test -Dtest=LoginTest – Run a specific test class
• mvn test -Dgroups=smoke – Run tests by TestNG group
• mvn test -Dbrowser=firefox – Pass system property to tests
• mvn verify – Run integration tests (Failsafe plugin)
8. Mini Project – End-to-End Automation Framework

8.1 Project Scope


Build a complete Hybrid Automation Framework for an e-commerce application (e.g.,
[Link]) covering Login, Product Search, Add to Cart, and Checkout flows.

8.2 Tech Stack


• Java 17
• Selenium WebDriver 4.x
• TestNG 7.x
• Apache POI 5.x
• Cucumber 7.x (BDD layer)
• Maven (build tool)
• ExtentReports 5.x
• Jenkins (CI/CD)
• Git/GitHub (version control)
• Log4j2 (logging)

8.3 Framework Setup Steps


Step 1: Create Maven project in IntelliJ/Eclipse
Step 2: Add all dependencies to [Link] (Selenium, TestNG, POI, Cucumber, ExtentReports)
Step 3: Create [Link] with browser, URL, timeouts
Step 4: Build DriverFactory with ThreadLocal for parallel safety
Step 5: Create BasePage with common utility methods
Step 6: Create Page classes for Login, Home, Product, Cart, Checkout
Step 7: Create BaseTest with @BeforeMethod/@AfterMethod for setup/teardown
Step 8: Create [Link] with test inputs
Step 9: Write TestNG test classes using POM page objects
Step 10: Write feature files and step definitions (Cucumber layer)
Step 11: Configure [Link] for suite/parallel execution
Step 12: Integrate ExtentReports via ITestListener
Step 13: Set up Jenkins job with Maven, configure email notifications
Step 14: Push code to GitHub, configure webhook for auto-trigger

8.4 Sample Test Case – Add to Cart


@Test(groups = {"regression"}, description = "Add product to cart")
public void testAddToCart() throws Exception {
ExcelUtils excel = new ExcelUtils("testdata/[Link]", "Cart");
String productName = [Link](1, 0);

LoginPage loginPage = new LoginPage(driver);


HomePage home = [Link](
[Link]("username"),
[Link]("password")
);
ProductPage product = [Link](productName);
[Link]();
CartPage cart = [Link]();

[Link]([Link](productName),
"Product not found in cart: " + productName);
[Link]("Product added to cart successfully");
}

8.5 Reporting
• ExtentReports: Rich HTML dashboard with test status, screenshots, logs, pie charts
• TestNG default: surefire-reports/[Link] generated after mvn test
• Cucumber: [Link] with scenario-level pass/fail breakdown
• Jenkins: Build trend graphs, test result history, email on failure
9. 100 Interview Questions & Answers

SELENIUM
1. What is Selenium WebDriver and how is it different from Selenium RC?
WebDriver communicates directly with the browser using native browser APIs (W3C protocol), without
needing a server. RC used a JavaScript proxy (Selenium Server) injected into the browser, making it
slower and less reliable. WebDriver supports more browsers, is faster, and handles modern dynamic
content better.

2. What are the different types of locators in Selenium?


ID, Name, ClassName, TagName, LinkText, PartialLinkText, CssSelector, and XPath. ID is fastest;
XPath is most flexible; CssSelector is a good balance of speed and flexibility.

3. What is the difference between findElement() and findElements()?


findElement() returns the first matching WebElement or throws NoSuchElementException if not found.
findElements() returns a List – empty list if no match, never throws an exception. Use findElements() to
check if an element exists: [Link]() > 0.

4. Explain Implicit, Explicit, and Fluent Wait.


Implicit Wait: global setting applied to all findElement calls; polls the DOM until the element appears or
timeout expires. Explicit Wait: waits for a specific condition (e.g., visibility, clickability) on a specific
element using WebDriverWait + ExpectedConditions. Fluent Wait: like Explicit Wait but allows custom
polling intervals and ignoring specific exceptions (e.g., NoSuchElementException during polling).

5. What is StaleElementReferenceException and how do you handle it?


Thrown when the element was found but the DOM has changed (e.g., page refreshed, AJAX updated).
Handle by re-locating the element, using a retry mechanism, or wrapping the action in a try-catch with
re-find logic. Explicit waits reduce this issue significantly.

6. How do you handle dynamic web elements?


Use dynamic XPath with contains(), starts-with(), or normalize-space(). Example:
//div[contains(@class,'active')]. Use CSS selectors with partial attribute matching. Combine XPath axes
like following-sibling, ancestor, preceding. Also use explicit waits for elements that appear dynamically.

7. What is JavascriptExecutor and when do you use it?


JavascriptExecutor is an interface allowing JS code execution in the browser. Use cases: scrolling
([Link]), clicking hidden elements, getting element attributes not in DOM, handling shadow
DOM elements, and highlighting elements for debugging.

8. How do you take a screenshot in Selenium?


Use TakesScreenshot interface: File src =
((TakesScreenshot)driver).getScreenshotAs([Link]); then [Link](src, new
File("path/[Link]")). Typically done in @AfterMethod or TestNG Listener's onTestFailure().

9. What is the difference between [Link]() and [Link]()?


close() closes only the current browser window/tab; the WebDriver session remains active. quit() closes
all browser windows/tabs opened by the driver and terminates the entire WebDriver session. Always
use quit() in teardown to avoid memory leaks.

10. How do you handle alerts in Selenium?


[Link]().alert() returns an Alert interface. Methods: accept() (click OK), dismiss() (click
Cancel), getText() (read alert text), sendKeys() (for prompt alerts). Always switch back to the main
window after handling the alert.

11. How do you handle multiple browser windows?


Get current window handle: [Link](). Get all handles: [Link]()
returns a Set. Iterate the set, switch using [Link]().window(handle). After task, switch back to
the original handle.

12. How do you handle iFrames?


Switch using [Link]().frame(index), frame(name/id), or frame(WebElement). After done, switch
back: [Link]().defaultContent() (to main page) or [Link]().parentFrame() (to
immediate parent frame).

13. What is the Actions class?


[Link] provides complex user gesture simulation: mouseHover
(moveToElement), dragAndDrop, rightClick (contextClick), doubleClick, keyDown/keyUp, clickAndHold.
Chain actions and call .perform() at the end.

14. How do you scroll in Selenium?


Using JavascriptExecutor: [Link]("[Link](0,500)") or
[Link]("arguments[0].scrollIntoView(true)", element). With Selenium 4 Actions: new
Actions(driver).scrollToElement(element).perform() or scrollByAmount(x, y).

15. How do you handle dropdowns?


Use the Select class: Select select = new Select([Link]([Link]("dropdown"))). Methods:
selectByValue(), selectByVisibleText(), selectByIndex(), getOptions(), getFirstSelectedOption(),
isMultiple(). For custom dropdowns (not tag), click the dropdown and then click the desired option
element.

TESTNG
16. What is TestNG and why is it preferred over JUnit?
TestNG provides more annotations, flexible grouping, native parallel execution, parameterization,
dependency management, and richer reporting. Unlike JUnit 4, TestNG doesn't require test methods to
be public void, supports @BeforeSuite/@AfterSuite, and allows running specific groups of tests via
XML configuration.

17. What is the execution order of TestNG annotations?


BeforeSuite → BeforeTest → BeforeClass → BeforeMethod → @Test → AfterMethod → AfterClass →
AfterTest → AfterSuite

18. How do you run tests in parallel with TestNG?


In [Link], set parallel attribute on or tag with values: methods (each @Test in its own thread),
classes (each class in its own thread), tests (each tag in its own thread), instances. Also set
thread-count to limit concurrent threads. Use ThreadLocal in DriverFactory for thread safety.

19. What is the difference between hard assert and soft assert?
Hard Assert (Assert class): stops test execution immediately on first failure. Soft Assert (SoftAssert
class): collects all assertion failures and reports them all at once when assertAll() is called. Use
SoftAssert when you want to verify multiple conditions in one test without stopping at the first failure.

20. How do you implement data-driven testing in TestNG?


Using @DataProvider annotation: create a method returning Object[][] with test data rows. Reference it
in @Test(dataProvider = "providerName"). For external data, read from Excel using Apache POI inside
the @DataProvider method. Alternative: @Parameters with [Link] values for simple string
parameters.

21. What are TestNG listeners and how do you implement them?
Listeners hook into TestNG lifecycle events. Implement ITestListener (onTestFailure, onTestSuccess,
onTestSkipped), ISuiteListener, IReporter. Register via @Listeners([Link]) annotation on
test class, or in [Link] section. Common use: auto-screenshot on failure, custom report generation.

22. How do you skip a test in TestNG?


Throw SkipException from within the test method. Or set enabled = false: @Test(enabled = false). Or
use dependsOnMethods – if the dependency test fails, the dependent test is skipped.
@Test(dependsOnMethods = {"testA"}) will be skipped if testA fails.

23. What is the use of [Link]?


[Link] configures the test suite: defines which test classes/methods to run, sets parallel execution
mode and thread count, passes parameters to tests, groups tests into suites, configures listeners, sets
suite name and test names. It allows different configurations for smoke, regression, and sanity runs
without code changes.

24. How do you retry failed tests in TestNG?


Implement IRetryAnalyzer interface with retry() method that returns true if the test should be retried. Set
maxRetryCount. Reference it in @Test(retryAnalyzer = [Link]). Or use a Listener that
applies retry globally. This is useful for handling flaky tests in CI environments.

25. What is @Factory in TestNG?


@Factory creates test object instances dynamically. Useful when you want to run the same test class
with different initialization parameters. The @Factory method returns Object[] where each object is a
test class instance. This is different from @DataProvider which runs the same test method with
different data.

APACHE POI
26. What is Apache POI used for in test automation?
Apache POI is a Java API for reading/writing Microsoft Office formats. In test automation, it is primarily
used to read test data from Excel files (.xlsx/.xls), enabling data-driven testing. It can also write test
results back to Excel for reporting. POI supports both old .xls (HSSF) and new .xlsx (XSSF) formats.

27. What is the difference between HSSF and XSSF in Apache POI?
HSSF (Horrible SpreadSheet Format) handles old Excel 97-2003 .xls files. XSSF (XML SpreadSheet
Format) handles Excel 2007+ .xlsx files. XSSF is OOXML-based, supports more rows (1M+), and is the
modern standard. For both, use SXSSF (Streaming XSSF) when writing very large datasets to avoid
OutOfMemoryError.

28. How do you read a specific cell from Excel using POI?
Open FileInputStream → create XSSFWorkbook(fis) → get sheet by name/index
([Link]("Sheet1")) → get row ([Link](rowNum)) → get cell ([Link](colNum))
→ call appropriate getter based on CellType: getStringCellValue(), getNumericCellValue(),
getBooleanCellValue().

29. How do you handle different cell types in Apache POI?


Check [Link]() which returns CellType enum: STRING, NUMERIC, BOOLEAN, FORMULA,
BLANK. For NUMERIC, dates are also stored as numeric – use [Link](cell) to
distinguish. Best practice: use DataFormatter class which returns the cell value as a formatted string
regardless of cell type.

30. How do you close resources properly when using Apache POI?
Always close FileInputStream after creating the Workbook. Close the Workbook itself with
[Link](). For writing, close FileOutputStream after [Link](fos). Use try-with-resources
(try(FileInputStream fis = new FileInputStream(path))) to automatically close resources even if an
exception occurs.

PAGE OBJECT MODEL


31. What is Page Object Model and why do we use it?
POM is a design pattern where each web page is represented by a Java class containing element
locators and methods for interacting with that page. We use it to: separate page structure from test
logic, improve maintainability (one change for UI update), promote reusability, increase readability, and
reduce code duplication.

32. What is PageFactory and how is it different from regular WebElement declaration?
PageFactory uses @FindBy annotations to declare WebElements as class fields.
[Link]() must be called in the constructor. Elements are lazily initialized (found in
DOM only when first accessed). Regular WebElement via findElement() is eager (found immediately
when the line executes). PageFactory is cleaner and more readable.

33. What is @FindBy annotation?


@FindBy(how = [Link], using = "username") or shortcut: @FindBy(id = "username"). Supports all
Selenium locator strategies. @FindBys (AND condition) and @FindAll (OR condition) for complex
locators. Must use with [Link]() to be effective.

34. What is the difference between POM and PageFactory?


POM is the design pattern/concept – organizing page elements and actions into classes. PageFactory
is a Selenium utility class that implements POM using @FindBy annotations and lazy initialization. You
can implement POM without PageFactory (using regular findElement calls), but PageFactory makes it
cleaner and more maintainable.
35. How do you handle navigation between pages in POM?
Page methods that cause navigation return a new Page object. Example: [Link]() returns a
DashboardPage instance. This makes the test read like a workflow: DashboardPage dashboard =
[Link](user, pass); and the test always works with the correct page object. This is called the
Fluent Page Object pattern.

36. What is BasePage and what goes in it?


BasePage is a parent class extended by all page classes. It contains: WebDriver and WebDriverWait
as protected fields, the constructor that calls [Link](), and common utility methods
(click with wait, type with clear, getText, waitForVisibility, isDisplayed, scrollToElement). This avoids
repeating these utilities in every page class.

37. How do you organize locators in a large POM project?


Options: Keep locators in the page class as @FindBy fields (most common). Or use a separate
constants class/interface (e.g., [Link]) with By objects. Or use a properties/YAML file
for locators. The first approach with @FindBy is most widely adopted for Selenium Java projects.

HYBRID DRIVEN DEVELOPMENT


38. What is Hybrid Driven Framework?
A Hybrid Framework combines multiple framework approaches – typically Data Driven (Apache POI for
Excel data), Keyword Driven (keywords mapped to actions), and BDD (Cucumber for
business-readable tests) – layered over a POM structure. It leverages the strengths of each approach
while minimizing weaknesses.

39. What is ThreadLocal in the context of Selenium parallel execution?


ThreadLocal is a Java class that provides thread-isolated variables. In parallel Selenium execution,
each test thread gets its own WebDriver instance stored in its ThreadLocal copy. This prevents threads
from sharing or overwriting each other's browser instances, ensuring thread safety.

40. What is the DriverFactory pattern?


DriverFactory is a utility/singleton class responsible for creating, providing, and destroying WebDriver
instances. It uses ThreadLocal for parallel safety. Key methods: getDriver(browser) – initializes a new
driver; getDriver() – returns the current thread's driver; quitDriver() – quits and removes from
ThreadLocal.

41. How do you read configuration from properties file?


Create a ConfigReader class: load a Properties object using FileInputStream pointing to
[Link]. Call [Link](fis). Then expose getter methods like getBrowser(), getBaseUrl() etc.
Alternatively, use [Link]() to allow runtime overrides from Maven command line
(-Dbrowser=firefox).

42. What is Extent Reports and how do you integrate it?


ExtentReports is a test reporting library that generates rich HTML dashboards. Integration: create
ExtentReports instance pointing to an output file. Before each test, create an ExtentTest instance. Log
pass/fail/info steps using [Link]() / fail() / info(). On failure, attach screenshot. Flush the report
in @AfterSuite.

CUCUMBER / BDD
43. What is BDD and how does Cucumber support it?
BDD (Behavior Driven Development) is a methodology where tests are defined in terms of business
behavior using plain English. Cucumber is a BDD tool that reads Gherkin-syntax feature files and maps
each step (Given/When/Then) to a Java step definition method via annotations like @Given, @When,
@Then.

44. What is a Feature file?


A feature file (.feature) is a plain-text file containing Gherkin-syntax scenarios describing the system's
behavior. It has: Feature (description of functionality), Scenario (one test case), Background (steps
common to all scenarios), Scenario Outline (parameterized scenario), and Examples table (data for
Scenario Outline).

45. What is the difference between Scenario and Scenario Outline?


Scenario is a single test case with static values. Scenario Outline is a template parameterized with
placeholders, combined with an Examples table. The scenario runs once for each row in the Examples
table. This is Cucumber's built-in data-driven mechanism.

46. What are Cucumber Hooks?


@Before (runs before each Scenario) and @After (runs after each Scenario) are Cucumber Hooks.
They accept a Scenario parameter to get scenario name, status ([Link]()), and attach
screenshots. Tagged hooks: @Before("@web") runs only before scenarios tagged @web. Hooks are in
a separate [Link] class.

47. What is the purpose of Background in Cucumber?


Background contains Given steps that are common and repeated across all Scenarios in a Feature file.
It runs before each Scenario, eliminating repetition. Background is different from @Before Hook:
Background appears in the Gherkin/HTML report as explicit steps; @Before Hook does not appear as a
step in reports.

48. What is Cucumber @CucumberOptions?


@CucumberOptions configures the Cucumber runner: features (path to .feature files), glue (package of
step definitions), plugin (report plugins like pretty, html, json, allure), tags (which scenarios to run),
monochrome (readable console output), dryRun (verify all steps have definitions without running).
Applied on the @RunWith([Link]) runner class.

49. How do you share data between steps in Cucumber?


Options: Instance variables in the same Step Definition class (steps in same class share state).
Dependency Injection with PicoContainer or Spring: share objects between multiple step definition
classes. World object/ThreadLocal context class: pass context between steps thread-safely. Avoid
static variables as they break parallel execution.

50. What is the Gherkin 'And' and 'But' keyword?


And and But are aliases for the previous keyword (Given/When/Then). They make Gherkin more
readable: 'Given logged in, And on dashboard' vs 'Given logged in, Given on dashboard'. Semantically
they're identical to Given/When/Then. But is used for negative conditions: 'But the cart should not show
deleted item'.

DEVOPS
51. What is CI/CD and why is it important for test automation?
CI (Continuous Integration) automatically builds and tests code on every commit. CD (Continuous
Delivery/Deployment) automatically delivers tested code to environments. For test automation, CI/CD
ensures tests run on every code change, bugs are caught early, and the team gets immediate
feedback. Jenkins/GitLab CI/GitHub Actions are common CI tools.

52. How do you integrate Selenium tests with Jenkins?


Create a Jenkins job (Freestyle or Pipeline). Configure Git SCM to pull the test repository. Add a Build
Step: 'Invoke top-level Maven targets' with goal 'clean test'. Optionally install the HTML Publisher plugin
to publish ExtentReports. Configure post-build email notifications. Set up a webhook in GitHub to
trigger Jenkins on push.

53. What is a Jenkinsfile and what are its types?


Jenkinsfile is a text file defining the Jenkins pipeline as code, stored in version control. Two types:
Declarative Pipeline (structured, uses pipeline {} block with stages, steps – recommended) and
Scripted Pipeline (more flexible, uses node {} block with Groovy scripting). Declarative is the modern
standard.

54. What is Docker and how is it useful for test automation?


Docker packages applications and their dependencies into lightweight containers. For testing: it
ensures a consistent test environment (same OS, browser versions) across dev laptops, CI servers,
and staging. Run Selenium Grid in Docker for on-demand browser scaling. Zalenium is a Docker-based
Selenium Grid with live preview and automatic video recording.

55. What is Selenium Grid and how do you set it up?


Selenium Grid allows distributing test execution across multiple machines/browsers. Architecture: Hub
(central server receiving test requests) and Nodes (machines with browsers that register to the Hub).
Setup: start hub (java -jar [Link] hub), start node on each machine pointing to hub URL.
RemoteWebDriver points to hub for test execution.
GENERAL & ADVANCED
56. What is the Page Object Factory pattern vs. Builder pattern in test frameworks?
Page Object Factory (PageFactory) creates page objects by initializing WebElements. The Builder
pattern in test data creation creates test data objects step-by-step with optional fields. Example: new
UserBuilder().withEmail("a@[Link]").withRole("admin").build(). Builder is useful when test data objects
have many optional fields.

57. How do you handle AJAX calls in Selenium?


Use Explicit Wait with appropriate ExpectedConditions: wait for element visibility, element text changes,
or invisibility of loading spinners. Alternatively use JavascriptExecutor to check [Link] == 0
(when site uses jQuery). Never use [Link]() as it's brittle and slows down tests unnecessarily.

58. What is a Robot Framework in comparison to Selenium?


Robot Framework is an open-source keyword-driven testing framework using plain English keywords.
SeleniumLibrary is a plugin for Robot Framework that provides Selenium-based browser automation
keywords. Selenium alone is a library/tool; Robot Framework is a complete test automation framework
that can use Selenium as its browser automation engine.

59. How do you generate Allure Reports?


Add allure-testng dependency and aspectj agent to Maven surefire plugin. Annotate tests with @Step,
@Severity, @Description, @Attachment. Run tests with Maven, then run 'allure serve
target/allure-results' to generate and open the interactive HTML report. Allure provides timelines,
categories of failures, flaky test detection, and trend charts.

60. What is the difference between @Test(invocationCount=3) and @DataProvider?


invocationCount=3 runs the same @Test method 3 times with the same input (useful for reliability/load
testing a single scenario). @DataProvider runs the @Test method once per data row with different
inputs (data-driven testing with varying inputs). They serve different purposes: repetition vs. data
variation.

61. How do you handle SSL certificate errors in Selenium?


Chrome: ChromeOptions options = new ChromeOptions(); [Link](true); new
ChromeDriver(options). Firefox: FirefoxOptions options = new FirefoxOptions();
[Link](true). This should only be used for test environments – never bypass
SSL in production testing.

62. What is Appium and how does it relate to Selenium?


Appium is an open-source mobile automation framework built on WebDriver protocol (W3C). It extends
Selenium WebDriver to support iOS and Android native/hybrid/web apps. Appium uses the same
WebDriver API, so Selenium knowledge transfers. AppiumDriver extends RemoteWebDriver. Many
hybrid frameworks combine Selenium (web) and Appium (mobile).

63. What is RestAssured and how does it complement Selenium testing?


RestAssured is a Java library for API testing. It complements Selenium by: setting up test data via API
before UI tests (faster than UI setup), verifying backend state after UI actions, and testing API
endpoints independently. In a full test suite, API tests run first (fast) followed by UI tests (slower).

64. How do you handle file uploads in Selenium?


For native file upload dialogs (): use [Link]("/path/to/file") – no clicking, directly send the
path. For custom upload dialogs (non-native, e.g., Flash/custom dropzone): use AutoIT or Robot class
for Windows dialogs. For drag-and-drop uploads, use JavaScript to trigger drop events or Actions.

65. What is the difference between CSS Selector and XPath?


CSS Selector: faster (browser optimized), cleaner syntax, can only traverse downward (child direction).
XPath: can traverse up (ancestor, parent axes), supports text() and position(), more powerful for
complex locators, slightly slower. Best practice: prefer CSS Selector for most cases, use XPath when
you need parent traversal or text-based location.

66. How do you verify a PDF download in Selenium tests?


Common approaches: check if the file exists in the download directory using [Link]() after a short
wait. Or configure Chrome to not open PDFs in browser (set download.default_directory preference)
then check the downloaded file. For content verification, use Apache PDFBox to read and assert PDF
text content.

67. What is a headless browser and when would you use it?
A headless browser runs without a GUI. ChromeOptions options = new ChromeOptions();
[Link]("--headless"). Use cases: CI/CD servers without a display, faster test execution
(no rendering overhead), running tests in Docker containers. Limitation: some UI rendering issues may
not be caught without a visible browser.

68. How do you manage test data in automation?


Strategies: External files (Excel via POI, JSON, CSV), Database queries (JDBC), API calls to
create/reset data, Factory methods using Faker library for random realistic data, Environment-specific
config files, Database scripts for test setup/teardown. Keep test data independent between tests to
avoid ordering issues.

69. What is test interdependency and why is it bad?


Test interdependency is when one test relies on the outcome or state created by another test. It's bad
because: tests cannot run in isolation, parallel execution breaks, test order matters, one failure
cascades to many. Solve by: each test sets up its own preconditions (often via API or direct DB),
independent of UI.

70. What is flaky test and how do you fix it?


A flaky test passes sometimes and fails other times with the same code. Causes: timing issues (fix with
proper waits), test data conflicts (fix with test isolation), environment instability, stale elements, race
conditions in parallel tests. Diagnosis: run the test 10+ times; use TestNG retry. Long-term fix: address
root cause, not just add retries.
71. What is an XPath axis?
XPath axes navigate relative to the context node: following-sibling (siblings after), preceding-sibling
(siblings before), parent (immediate parent), ancestor (all parents), child (direct children), descendant
(all children). Example: //label[text()='Username']/following-sibling::input – finds the input next to the
Username label.

72. How do you handle web tables in Selenium?


Locate the table element. Get all rows: [Link]([Link]("tr")). For each row, get cells:
[Link]([Link]("td")). Use XPath for specific cells: //table//tr[3]/td[2]. For dynamic
tables, iterate rows and find specific data using cell text comparison.

73. What is the Singleton pattern in test frameworks?


Singleton ensures only one instance of a class exists. Used for: WebDriver (anti-pattern for parallel –
use ThreadLocal instead), ConfigReader (one instance reads config once), ExtentReports manager
(single report instance). Implementation: private constructor + static getInstance() method checking if
instance is null.

74. How do you verify email sending in automated tests?


Options: Use a test email service like Mailosaur, MailSlurp, or GreenMail that provides a test inbox
accessible via API. Or use JavaMail API to connect to a test IMAP account and read emails. Or stub
the email service with a mock. Never test against real production email systems in automation.

75. What is the difference between absolute and relative XPath?


Absolute XPath: starts from root (html), using single slash: /html/body/div/form/input. Brittle – any DOM
change breaks it. Relative XPath: starts from anywhere in DOM, using double slash:
//input[@id='username']. Robust – recommended always. Never use absolute XPath in test automation.

76. How do you implement log4j logging in a Selenium framework?


Add log4j2 dependency. Create [Link] config file in resources (console appender, file appender
with log level). In classes: private static final Logger log = [Link]([Link]).
Use [Link](), [Link](), [Link](). Integrate with ExtentReports by logging to report and file
simultaneously.

77. What is Maven Surefire Plugin?


Surefire Plugin runs unit/TestNG tests during the Maven test phase. Configuration in [Link]: specify
[Link] location (suiteXmlFiles), include/exclude patterns, system properties (browser, env), argLine
for AspectJ weaving (Allure). The plugin generates surefire-reports in /target directory.

78. How do you pass browser type at runtime in Maven?


In [Link] Surefire plugin: ${browser}. In Java: String browser = [Link]("browser",
"chrome"). Run: mvn test -Dbrowser=firefox. This allows running the same test suite on different
browsers via CI parameters without code changes.

79. What is Dependency Injection in test frameworks?


DI passes required objects (like WebDriver) to classes rather than having classes create them. In
Cucumber with PicoContainer: add picocontainer dependency, create a TestContext class with
WebDriver. Step Definition classes receive TestContext via constructor injection automatically. Ensures
shared WebDriver state across step definition classes.

80. What are the best practices for writing maintainable test automation?
1) Follow POM strictly, 2) Externalize test data, 3) Use constants for locators/URLs, 4) Never use
[Link], 5) Write atomic independent tests, 6) Use descriptive test method names, 7) Log
meaningful messages, 8) Handle exceptions gracefully, 9) Keep one assertion per test where possible,
10) Review and refactor tests regularly like production code.

MORE TOPICS
81. What is the @Suite annotation in TestNG?
There's no @Suite annotation; the suite is defined in [Link] via the tag. However, @SuiteClasses is
a JUnit annotation. In TestNG, you organize suites in [Link] with containing multiple blocks. You
can run multiple [Link] files via a Maven build or Jenkins.

82. How do you implement keyword-driven framework?


Create an Excel file with columns: TestCase, Keyword, ObjectName, Value. Keywords map to Java
methods (click, type, verify, navigate). KeywordExecutor class reads the Excel row by row, looks up the
keyword, and invokes the corresponding method using reflection or a switch statement with page
objects.

83. How do you verify element color or CSS properties?


Use [Link]("color") or getCssValue("background-color"). This returns RGB value like
'rgba(255, 0, 0, 1)'. Convert to hex for comparison. For computed styles not in HTML attributes,
getCssValue() fetches the browser-computed value. For font-size, border, visibility, use the respective
CSS property name.

84. What is Selenium 4 and its new features?


Selenium 4 (released 2021) introduced: W3C WebDriver standard (no JSON Wire Protocol), native
support for Chrome DevTools Protocol (CDP), improved Selenium Grid (supports Docker, Kubernetes,
standalone/hub-node modes), relative locators (near, above, below, toLeftOf, toRightOf), new
window/tab opening API ([Link]().newWindow()), and better documentation.

85. What are relative locators in Selenium 4?


Relative locators find elements by their position relative to another element:
[Link]([Link]("input")).near(emailLabel) – finds input near the email label. Options:
above(), below(), toLeftOf(), toRightOf(), near(). Useful when elements lack unique attributes and are
only identifiable by their visual position on the page.

86. What is Chrome DevTools Protocol (CDP) in Selenium 4?


CDP allows Selenium 4 to interact directly with Chrome browser internals. Use cases: network
request/response interception, emulating network conditions (offline, slow 3G), setting geolocation,
capturing console logs, clearing cache/cookies programmatically, and performance metrics. Accessed
via ((ChromeDriver) driver).executeCdpCommand().

87. How do you handle Calendar/Date pickers?


For native HTML5 date inputs: [Link]("2024-12-25"). For custom JS calendar widgets: click
the calendar icon, navigate months using arrow buttons, click the target date. Or use
JavascriptExecutor to set the value directly: [Link]("arguments[0].value='2024-12-25'",
dateField) if the widget allows.

88. What is TestNG @Factory vs @DataProvider?


@DataProvider: runs the same test method multiple times with different data, creating one instance of
the test class. @Factory: creates multiple instances of the test class with different constructor
parameters, each running all test methods. Factory is useful when different class-level initialization is
needed per test run scenario.

89. How do you implement soft assertions in TestNG?


SoftAssert sa = new SoftAssert(); // create instance. [Link](actual, expected, 'msg'); //
non-stopping assertion. [Link](condition); [Link](condition). [Link](); // must call
at end – this is where failures are reported. If assertAll() is not called, soft assertion failures are silently
ignored!
90. What is OOPS and how is it applied in Selenium frameworks?
Encapsulation: WebElements as private fields with public methods in Page classes. Inheritance:
BaseTest, BasePage extended by all tests/pages. Polymorphism: different browser drivers
(ChromeDriver, FirefoxDriver) treated as WebDriver. Abstraction: DriverFactory hides driver creation
details. OOPS principles make the framework modular and maintainable.

91. How do you test file downloads with Selenium?


Configure browser to auto-download to a known path (no dialog). ChromeOptions: set
'download.default_directory' and 'download.prompt_for_download' to false. After clicking download, use
polling (FluentWait on [Link]()) to wait for file to appear. Then verify file name, size, extension, or
content (POI for Excel, PDFBox for PDF).

92. What is TestContainers?


Testcontainers is a Java library that provides lightweight, throwaway Docker containers for tests. For
Selenium: use BrowserWebDriverContainer to spin up a fresh Chrome/Firefox Docker container for
each test, ensuring a clean, consistent browser environment. It integrates with JUnit/TestNG and
auto-starts/stops containers per test.

93. How do you handle authentications (Basic Auth) in Selenium?


Selenium 4 native: use DevTools Protocol to set network credentials:
[Link]([Link]()); [Link]([Link]()); handle [Link] event to
supply credentials. Simpler approach: embed credentials in URL: [Link] For
form-based auth: simply automate the login form with sendKeys.

94. How do you automate CAPTCHA?


CAPTCHA is intentionally designed to prevent automation. In testing, solutions include: disabling
CAPTCHA in test/staging environments (coordinate with dev team), using test API keys that bypass
CAPTCHA (reCAPTCHA v2 has test keys), third-party CAPTCHA solving services (2Captcha,
Anti-Captcha) for non-critical tests, or mocking the CAPTCHA service response.

95. What is screen resolution testing with Selenium?


Use ChromeOptions to set window size: [Link]("--window-size=1920,1080"). Or after
driver creation: [Link]().window().setSize(new Dimension(1366, 768)). For mobile viewport
emulation: DeviceMetrics via ChromeOptions mobileEmulation. This helps test responsive design
across different screen sizes.

96. What is the Observer design pattern in test frameworks?


The Observer pattern is used via Listeners. TestNG's ITestListener is an Observer that responds to test
lifecycle events (test start, pass, fail, skip). The TestNG runner is the Subject that notifies listeners. This
decouples reporting/screenshot logic from test logic, following the Open/Closed principle.

97. How do you handle dynamic tables with pagination?


Get current page rows and extract data. Check if the 'Next' button is enabled/visible. If yes, click it, wait
for the page to load (URL/row content changes), then process the next page rows. Continue until 'Next'
is disabled. Store all data in a list for assertion. This requires robust waits between page transitions.

98. What is the difference between Maven and Gradle?


Maven uses XML ([Link]) for build configuration and has a fixed lifecycle (compile, test, package,
install, deploy). Gradle uses Groovy/Kotlin DSL ([Link]), is more flexible and faster (incremental
builds, caching). Both manage dependencies and build Selenium projects, but Maven is the dominant
choice in enterprise Java test automation.

99. How do you implement extent report with Cucumber?


Use ExtentCucumberAdapter plugin: add extent-cucumber7-adapter dependency. Create
[Link] file in resources with report path and settings. Add the adapter in @CucumberOptions
plugin: "[Link]:". Scenarios
automatically map to extent test cases with step-by-step detail.

100. How do you ensure your automation framework is scalable?


1) Use POM for page separation. 2) ThreadLocal WebDriver for parallel safety. 3) External config files
for environment switching. 4) External test data (no hardcoding). 5) Modular utilities (reusable). 6)
Consistent naming conventions. 7) Retry mechanism for flaky tests. 8) CI/CD integration. 9) Meaningful
logs and reports. 10) Regular refactoring and code reviews.
10. 50 Real-Time Scenario Questions
The following scenario-based questions test your practical ability to handle real challenges in automation
projects.

1. Your login test passes in isolation but fails when run as part of the suite. What do you
investigate?
Check for test interdependency – a previous test may be leaving the session in a logged-in state. Verify
that @BeforeMethod is properly clearing cookies and navigating to the base URL. Check if browser
state (local storage, session storage) is shared. Ensure tests don't share WebDriver instances. Use
[Link]().deleteAllCookies() before each test and navigate fresh to login URL.

2. A test that worked for 3 months suddenly started failing with ElementNotInteractableException.
No code changes were made. What are the possible causes?
The application UI was changed by the dev team (element now hidden, covered by overlay, or
repositioned). A new modal/cookie banner now appears over the element. Screen resolution or browser
update changed element rendering. Environment-specific issue (slower page load hiding the element
temporarily). Check the application UI, inspect the element in browser DevTools, check recent app
deployment changes.

3. Your test suite takes 4 hours to run. The manager wants it to run in 1 hour. What is your
approach?
Analyze test distribution and identify the slowest tests. Enable parallel execution in [Link]
(parallel='methods' or 'classes', increase thread-count). Move smoke tests to a separate fast suite.
Replace UI setup steps with API calls (login via API instead of UI). Use headless browser execution.
Run on Selenium Grid with multiple nodes. Eliminate redundant [Link]() calls and replace with
explicit waits.

4. You need to test a multi-step checkout flow where each step depends on the previous. How do
you structure the tests?
For unit-style testing: use @BeforeMethod to set up state via API (create cart, apply coupon) so each
test is independent. For end-to-end flow testing: one @Test method covering the complete flow, or use
TestNG dependsOnMethods only within a single test class. Avoid making separate @Test methods
depend on each other across different test scenarios.

5. A dropdown is not a standard HTML tag. How do you handle it?


Identify the custom dropdown structure: usually a div/span that toggles visibility of a list (ul/li or div
elements). Click the dropdown trigger element to open the options list. Wait for the options to become
visible. Find the desired option by text using XPath like //li[normalize-space(text())='OptionText'] or
//div[@class='option-item' and text()='OptionText']. Click the option element.

6. Your test is failing because a loading spinner overlaps the element you want to click. How do
you fix it?
Wait for the spinner/overlay to disappear before clicking:
[Link]([Link]([Link]("spinner"))). Then wait for
the target element to be clickable:
[Link]([Link](targetElement)). If the spinner appears
intermittently, wrap the click in a try-catch and retry. Never use [Link] to guess when the spinner
disappears.
7. You need to verify that a new browser tab opens after clicking a button and perform actions on
it.
Get current window handles before click: Set before = [Link](). Click the button.
Wait until a new handle appears: [Link](d -> [Link]().size() > [Link]()). Get new
handles set, find the new handle by removing the original handles. Switch:
[Link]().window(newHandle). Perform actions. Switch back to original:
[Link]().window(originalHandle).

8. In your framework, how do you ensure WebDriver is not shared between threads during parallel
execution?
Use ThreadLocal in DriverFactory. getDriver() returns [Link]() (the current thread's copy).
setDriver() calls [Link](newDriver). quitDriver() calls [Link]().quit() then [Link]() to clean
up the ThreadLocal. Never use a static WebDriver field – it will be shared across threads causing
interference.

9. A test reads data from an Excel file but sometimes fails with NullPointerException on a cell. How
do you fix it?
The cell is empty in Excel. Check for null before calling getCellType(): if (cell == null) return "". Also
check for BLANK cell type. Use DataFormatter: DataFormatter formatter = new DataFormatter(); return
[Link](cell) – this safely returns empty string for null/blank cells. Add defensive null
checks throughout the ExcelUtils class.

10. A senior developer says you should test via API instead of UI for most scenarios. How do you
respond?
I agree with the testing pyramid principle. API tests are faster, more stable, and test business logic
directly. I would use RestAssured for API testing of CRUD operations, login, and data setup. UI
automation should focus on critical user journeys (end-to-end flows), visual rendering, and features that
only exist in the browser (UI interactions, JavaScript behavior). A balanced approach: ~60-70% API,
~20-30% UI, ~10% exploratory.

11. The CI pipeline runs tests fine locally but fails in Jenkins with WebDriverException: Chrome not
found.
Jenkins server may not have Chrome installed, or it's installed but not in PATH. Solutions: Install
Chrome on Jenkins agent (configure in Jenkins setup scripts). Use Docker containers with Chrome
pre-installed (Selenium Chrome node image). Use WebDriverManager:
[Link]().setup() – auto-downloads and configures the driver. Use headless
Chrome: [Link]("--headless", "--no-sandbox", "--disable-dev-shm-usage") for Linux CI
servers.

12. How would you test a real-time search feature that shows results as you type?
Type character by character using sendKeys() with a loop or send the full string. After each character or
after the full string, wait for the results dropdown to appear using explicit wait. Assert that displayed
results contain or match the search term. Test edge cases: empty search, special characters, very long
strings, minimum character threshold (some search requires 3+ chars). Also test debounce behavior –
results shouldn't fire on every keystroke instantly.

13. You need to validate a graph/chart on the dashboard. How do you approach this?
Direct Selenium element inspection of chart data: if the chart library renders SVG ([Link], Highcharts),
inspect SVG elements and text nodes for axis values and data points. For Canvas-based charts: use
JavascriptExecutor to call the chart library's API methods that expose data. For API-backed charts: call
the data API directly and assert values match what should be displayed. For visual testing: integrate
Applitools or Percy for pixel-comparison of the rendered chart.
14. A feature file has 50 scenarios. Running all takes too long. How do you optimize?
Tag scenarios by type: @smoke (top 5-10 critical), @regression (all), @wip (in progress). Run
@smoke in every commit pipeline (quick feedback). Run @regression nightly or on PRs. Enable
parallel scenario execution using Cucumber's parallel plugin or JUnit 5 parallel execution. Use API
hooks to set up test data instead of UI flows. Combine similar scenarios into Scenario Outline tables.

15. How do you handle a test that requires a file to be uploaded from a path that differs between
local and CI?
Store the file in the project's src/test/resources directory. Access via:
getClass().getClassLoader().getResource("testfiles/[Link]").getPath(). This relative path works
both locally and in CI since it's part of the project classpath. Never hardcode absolute paths like
C:\Users\... in test code.

16. Your automation test sends an OTP to a mobile number for 2FA. How do you automate this?
Approach 1: Use a test-only bypass – coordinate with developers to add a fixed OTP (e.g., 000000) for
test accounts in non-production environments. Approach 2: Use a virtual number service (Twilio, etc.)
with an API to read the received OTP programmatically. Approach 3: Stub the OTP service in the test
environment to always return a known code. Never hardcode real phone numbers in test code.

17. A test is consistently slow because of slow page loads. How do you investigate and fix?
Profile the test: add timestamps around page interactions to identify the slowest steps. Check network
requests in browser DevTools during the slow step. Replace [Link] with precise waits. For slow
API calls: consider mocking at the service layer for speed. Discuss with the team if the page load is a
genuine performance bug (add to performance test suite). Consider running on faster infrastructure or
headless browser.

18. How would you test a drag-and-drop feature in Selenium?


Use Actions class: Actions action = new Actions(driver); [Link](sourceElement,
targetElement).perform(). Or: [Link](source).moveToElement(target).release().perform().
For HTML5 drag-and-drop that doesn't respond to Actions, use JavaScript: inject a JS script that
simulates HTML5 drag events (dragstart, dragover, drop). Verify the element's new position after
dropping.

19. Your test framework has no logging. Tests fail in CI and you cannot diagnose the issue. What
do you add?
Integrate Log4j2: add dependency, configure [Link] (console + file appenders). Log: test start/end
(with test name), all navigation (URL, page title), element interactions (what was clicked/typed), actual
vs expected values, exceptions (full stack trace), screenshot paths. Add ExtentReports with
step-by-step logging. Configure Jenkins to archive log files as build artifacts.

20. A critical test needs to validate data in both the UI and the database. How do you implement
this?
1) Perform UI action (e.g., submit a form). 2) Assert the UI success message. 3) Connect to the test
database using JDBC: Connection conn = [Link](dbUrl, user, pass). 4)
Execute SELECT query to verify the data was persisted. 5) Assert database values match what was
entered via UI. 6) Clean up test data after the test. Keep DB credentials in [Link], not
hardcoded.

21. How do you test localization/internationalization (i18n) with Selenium?


Parameterize the locale: run same tests with different locale settings via [Link] parameters. Store
expected text in locale-specific properties files: messages_en.properties, messages_fr.properties. Load
the appropriate file based on test locale parameter. Assert UI text matches expected locale strings.
Test date formats, number formats, currency symbols, and right-to-left text layouts. Use a Locale utility
class in the framework.

22. How do you handle a scenario where the element XPath keeps changing on every build?
Root cause: developers are using auto-generated IDs or dynamic class names. Solutions: Request
developers to add stable test-specific attributes (data-testid="login-btn"). Use XPath based on stable
structural context (label text, parent element). Use relative locators (Selenium 4). Use CSS selectors
based on stable attributes. Coordinate with dev team to establish a convention for test-friendly
attributes.

23. A test passes in Chrome but fails in Firefox. How do you debug cross-browser issues?
Run the test in Firefox with DevTools open to inspect the element. Compare element attributes in
Chrome vs Firefox. Common differences: CSS rendering differences (element not visible), event
handling differences (click timing), JavaScript compatibility, font rendering affecting element positions.
Add browser-specific wait conditions or use a try-catch per browser. Log browser version in test
reports. File a browser-specific bug if it's an app issue.

24. How would you automate testing of a chat/messaging feature?


Use two separate WebDriver instances (two browser sessions). Session 1: logged in as User A.
Session 2: logged in as User B. User A sends a message via Session 1. In Session 2, wait for the
message to appear (use polling/explicit wait). Assert message content, timestamp, and read receipts.
Test edge cases: long messages, special characters, rapid sequential messages, message delivery on
poor network (DevTools network throttling).

25. The Product Manager wants test results sent to Slack after each CI run. How do you implement
this?
After tests complete in Jenkins, use a Jenkins Slack Notification Plugin to post build status. Or: in
Maven's post-build phase, use a Groovy/Shell script to call the Slack Webhook API with a summary
(total tests, passed, failed, build URL). Or integrate in the IReporter/ISuiteListener's onFinish() method
to post the summary programmatically using Slack's Java SDK or an HTTP POST to the webhook
URL.

26. How do you test a rich text editor (like TinyMCE or CKEditor) with Selenium?
Rich text editors render in an iframe. Switch to the iframe: [Link]().frame("mce_0_ifr"). Then
interact with the body element: [Link]([Link]("tinymce")).sendKeys("text"). For formatting
(bold, italic): send keyboard shortcuts (Ctrl+B). Or use JavascriptExecutor to set the editor's content
programmatically: [Link]("[Link]('text')"). Switch back to default
content after editing.

27. How do you validate that a test is running on the correct environment (dev/staging/prod)?
In ConfigReader, check the baseUrl property against expected environment URLs. Assert
[Link]() contains the expected domain at the start of each test in @BeforeMethod. Add
environment name to ExtentReport configuration. Store an environment flag in [Link]
(env=staging) and assert it matches the URL pattern. This prevents accidentally running destructive
tests on production.

28. You need to test an infinite scroll page. How do you approach it?
Scroll to the bottom using JavascriptExecutor: [Link]("[Link](0,
[Link])"). Wait for new items to load (wait for the item count to increase:
[Link]([Link]("item")).size()). Repeat until no new items load (size doesn't change
after two consecutive scrolls). Assert total items match expected count or specific items are present.
Add a max iteration limit to prevent infinite loops.

29. How do you automate testing of a PDF that is rendered in the browser?
Approach 1: Configure Chrome to download PDFs instead of displaying them, then read the
downloaded PDF using Apache PDFBox. Approach 2: Get the PDF URL from the request (using CDP
network monitoring) and download it programmatically, then parse with PDFBox. Approach 3: For
critical PDF content, verify via the API that generates the PDF (if applicable). Assert text content, table
data, and generated report values.

30. A web page uses Shadow DOM. Standard findElement() fails. How do you handle it?
Selenium 4 supports Shadow DOM natively: WebElement shadowHost =
[Link]([Link]("#host")); SearchContext shadowRoot =
[Link](); WebElement shadowEl =
[Link]([Link]("input")); Note: XPath does NOT work in Shadow DOM – use
CSS selectors only inside shadow roots. For Selenium 3: use JavascriptExecutor:
[Link]("return arguments[0].shadowRoot", shadowHost) to get shadow root.

31. How do you test a single-page application (SPA) like an Angular or React app?
SPAs update content without full page reloads. Don't rely on page load waits (waitForPageLoad via JS
ready state doesn't work reliably). Use explicit waits for specific elements to appear/disappear. For
Angular: use Protractor (deprecated) or wait for Angular-specific conditions. Check URL fragment
changes for navigation. Be aware that element re-renders after state changes may cause
StaleElementReference – re-locate elements after state changes.

32. How do you generate and use test reports in a CI environment?


Configure ExtentReports output to a fixed path in the project (target/extent-reports/). In Jenkins, use the
HTML Publisher plugin to serve the report as a build artifact accessible via browser. For Allure:
configure Allure Jenkins plugin to aggregate results and show trend charts. Email the report path in
post-build email notifications. Archive report directories as Jenkins build artifacts for historical
reference.

33. How do you test the application's response when the network is slow or offline?
Selenium 4 with ChromeDevTools: Set network conditions:
[Link]([Link](false, 100, 500, 1000, [Link]())) to
simulate 3G. Test timeout handling, loading state UI, graceful error messages. Test offline:
[Link]([Link](true, 0, 0, 0, [Link]())). Verify the app
shows appropriate offline messages and doesn't crash.

34. How do you automate testing of tooltips?


Hover over the element using Actions: new Actions(driver).moveToElement(element).perform(). Wait
for tooltip to appear:
[Link]([Link]([Link]("tooltip"))). Assert tooltip text.
For CSS-only tooltips (::after pseudo-elements): use getCssValue("content") or check the title attribute.
Some tooltips are only visible while hovering; ensure the assertion happens before moving the mouse
away.

35. Your team is transitioning from a manual to an automation-first approach. What is your
strategy?
Phase 1: Automate existing smoke tests (10-15 most critical paths). Phase 2: Establish the framework,
get team training, document standards. Phase 3: Automate regression suite, integrate with CI. Phase 4:
Shift testing left – developers run automation before PR merge. Key actions: choose right tech stack for
the team's skills, start with high-value stable features, avoid automating frequently changing UI,
measure ROI (time saved = manual hours per cycle × cycles).

36. How do you test a multi-language form validation that shows error messages in different
languages?
Parameterize locale in [Link]/[Link]. Load expected error messages from locale-specific
resource bundles (.properties files per language). Switch locale in the app (if supported via URL param
or language picker). Submit invalid form. Assert that displayed error message matches the
locale-specific expected string from your resource bundle. Run the same test with different locale
parameters.

37. A test requires database seed data that gets cleaned up after each test. How do you manage
this?
Create a DatabaseUtils class with methods: seedTestData() – inserts required data via JDBC.
cleanTestData() – deletes test records by a unique test identifier. In @BeforeMethod: call
seedTestData() and store returned IDs. In test: use those IDs. In @AfterMethod: call cleanTestData().
Use transactions where possible to rollback instead of explicit delete. Tag test data with a
TEST_RUN_ID for easy identification and cleanup.

38. How do you handle a session timeout during a long-running test?


Detect session timeout: check if the current URL redirected to the login page
([Link]().contains("/login")). Re-authenticate: call the login method from LoginPage.
Resume the test from the last page. Better approach: break very long tests into smaller independent
tests (each starting with a fresh login via API for speed). Configure application session timeout to be
longer in the test environment.

39. How do you integrate accessibility testing with Selenium?


Use Axe-Selenium-Java library: AxeBuilder axeBuilder = new AxeBuilder(); Results results =
[Link](driver); [Link]([Link]().isEmpty(), [Link]()).
This checks WCAG 2.1 AA rules automatically. Also manually verify: keyboard navigation (Tab order),
screen reader labels (aria-label, aria-describedby), color contrast ratios, and focus visibility. Run
accessibility checks on key page transitions.

40. How would you automate a shopping cart discount code validation?
Navigate to cart. Enter discount code in the promo field and apply. Wait for success/error message.
Verify: discount percentage shown correctly, discount amount calculated accurately, total price reduced
correctly. Also test: invalid/expired code error message, maximum use limit, code combination
restrictions, code with minimum order value. Verify the discount is retained through the checkout flow.

41. How do you test for broken links on a webpage?


Find all anchor elements: [Link]([Link]("a")). Extract href attributes. For each URL,
send an HTTP HEAD request using HttpURLConnection or RestAssured and check the response code.
A 200/301/302 response is valid; 404/500 indicates a broken link. Run this check outside main test
threads (parallel HTTP requests). Report all broken links with their page location. This is better done
with specialized tools like Screaming Frog for large sites.

42. How do you handle flaky tests caused by slow third-party services (ads, analytics)?
Block third-party requests that are not under test: use Chrome DevTools Protocol to block URLs
matching third-party patterns ([Link]([Link]([Link]("*analytics*", "*ads*")))).
Or use a proxy (BrowserMob Proxy) to intercept and mock third-party responses. Configure explicit
waits only on first-party elements. This isolates tests from external service instability.

43. A test captures a screenshot but the screenshot is blank. What are the possible causes?
Headless Chrome: ensure window size is set ([Link]("--window-size=1920,1080")).
Screenshot taken before page fully loaded: add appropriate wait. Element is outside viewport: scroll to
element first. Browser window is minimized: [Link]().window().maximize(). CDP screenshotting
for shadow DOM/WebGL content requires special handling. For Selenium Grid, screenshots work
differently on remote nodes.
44. How do you test the print functionality of a web application?
Selenium cannot directly test print dialogs (OS-level dialog). Approaches: 1) Test print preview by
calling [Link]() via JS and checking print-specific CSS media query rendering (using CDP to
emulate print media). 2) Generate PDF via print and validate using PDFBox. 3) If the app has a
'Download PDF' feature, automate that instead. 4) Visual testing tools (Percy) can capture print-preview
mode rendering.

45. How do you manage test execution when some tests require VPN access?
In CI, configure the Jenkins agent to run within the VPN (persistent connection or OpenVPN on
startup). Tag VPN-dependent tests: @vpn. Use separate [Link] files or groups to exclude @vpn
tests in non-VPN environments. Locally, ensure tests check environment connectivity before running
(ping the protected URL, skip with clear message if not reachable). Document VPN prerequisites in the
test README.

46. How would you test a chatbot integration on a web page?


Open the chatbot widget by clicking the chat icon. Wait for the chatbot container to appear. Type a
message in the chat input and send. Wait for the bot response to appear. Assert response text contains
expected keywords or matches expected patterns. Test intent recognition: type variations of the same
question and verify appropriate responses. Test fallback response for unrecognized input. Test
conversation flow (multi-turn dialog).

47. How do you ensure your test framework works on both Windows and macOS?
Use [Link] or [Link]() instead of hardcoded '\' or '/'. Store test data files in src/test/resources
and access via classpath. Use WebDriverManager for automatic driver management (no manual
[Link] vs chromedriver distinction). Avoid OS-specific keyboard shortcuts (use
[Link] on Mac vs [Link]). Test the framework in both OS CI agents. Avoid relying
on system fonts or display settings.

48. How do you test a web application's performance using Selenium?


Capture page load timing via JavascriptExecutor: [Link]("return
[Link] - [Link]"). Measure individual operation
durations using [Link](). For serious performance testing, combine with JMeter
(server load) and integrate Lighthouse (via CDP or a plugin) for Core Web Vitals. Selenium is for
functional verification; specialized tools (JMeter, k6, Gatling) should handle load testing.

49. How do you handle cookie consent popups that appear on first visit?
Option 1: Accept the cookie banner as part of BasePage or @BeforeMethod using a try-catch (popup
may not always appear). Option 2: Set cookies directly via [Link]().addCookie() to pre-accept
consent before page load. Option 3: Configure browser to automatically accept all cookies via Chrome
preference: [Link]("profile.default_content_setting_values.cookies", 1). Option 4: Ask the team to
disable the consent banner in test environments.

50. How do you validate email format in a Selenium test?


1) UI validation: enter invalid email, trigger validation (click elsewhere or submit), assert error message
is displayed with explicit wait. 2) Field-level HTML5 validation:
[Link]("validationMessage") returns browser's built-in validation message. 3) For regex
validation testing: test valid formats (a@[Link]), invalid formats (missing @, missing domain, spaces),
boundary cases (very long email, special chars). 4) Combine with API test to verify backend also
validates and doesn't accept invalid emails that bypass frontend validation.
End of Guide

This guide covers Selenium WebDriver, TestNG, Apache POI, POM design pattern,
Hybrid Driven Development, Cucumber BDD, DevOps practices, a complete mini
project, 100 interview Q&As, and 50 real-time scenario questions. Practice coding these
concepts hands-on for best results.

You might also like