0% found this document useful (0 votes)
6 views28 pages

Selenium Java Study Guide

This document is a comprehensive study guide for Selenium and Java, covering automation testing fundamentals, WebDriver architecture, locators, element interactions, and advanced UI handling. It includes setup instructions, best practices for using Selenium 4, and a detailed overview of the Page Object Model and TestNG framework for structuring tests. Additionally, it addresses data-driven testing techniques and project organization for efficient automation workflows.

Uploaded by

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

Selenium Java Study Guide

This document is a comprehensive study guide for Selenium and Java, covering automation testing fundamentals, WebDriver architecture, locators, element interactions, and advanced UI handling. It includes setup instructions, best practices for using Selenium 4, and a detailed overview of the Page Object Model and TestNG framework for structuring tests. Additionally, it addresses data-driven testing techniques and project organization for efficient automation workflows.

Uploaded by

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

SELENIUM + JAVA

Automation Testing — Complete Study Guide


Interview Preparation | Framework Deep-Dive | Day-to-Day Practices
1. SELENIUM FUNDAMENTALS
1.1 What is Selenium?
Selenium is an open-source suite of tools for automating web browsers. It supports multiple
programming languages, browsers, and operating systems, making it the industry-standard choice for
web UI automation.

Component Purpose
Selenium WebDriver Core API for browser automation (W3C WebDriver spec)
Selenium Grid Distributed parallel execution across machines/browsers
Selenium IDE Record-and-playback browser extension (prototyping only)
Selenium Manager Auto-manages browser driver binaries (Selenium 4.6+)

🎯 Interview: What is the difference between Selenium 3 and Selenium 4?


Feature Selenium 4 vs 3
Architecture Selenium 4 uses W3C WebDriver protocol natively; Selenium 3
used JSON Wire Protocol
Relative Locators Selenium 4 adds
findElement(with([Link]()).above/below/near/toLeftOf/toRight
Of)
CDP Support Selenium 4 integrates Chrome DevTools Protocol (CDP) directly
Grid Selenium 4 Grid uses Reactive architecture with Router, Distributor,
Node
BiDi Selenium 4 supports WebDriver BiDirectional (BiDi) for real-time
events

1.2 WebDriver Architecture


Understanding the request flow is essential for debugging.

Test Code → WebDriver API → Browser Driver (chromedriver/geckodriver) → Browser

• Your Java code calls Selenium WebDriver API methods


• Selenium sends W3C-compliant HTTP requests to the browser driver
• The driver translates requests into browser-native commands
• Browser executes the action and returns the result

💡 TIP: Always close the browser driver with [Link]() (not [Link]()) in @AfterTest to release
all browser resources.
1.3 Setting Up the Project

Maven [Link] — Core Dependencies


<dependency>
<groupId>[Link]</groupId>
<artifactId>selenium-java</artifactId>
<version>4.21.0</version>
</dependency>
<dependency>
<groupId>[Link]</groupId>
<artifactId>testng</artifactId>
<version>7.9.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>[Link]</groupId>
<artifactId>webdrivermanager</artifactId>
<version>5.8.0</version>
</dependency>

Driver Initialisation (Selenium 4)


// Selenium Manager handles drivers automatically — no WebDriverManager needed
WebDriver driver = new ChromeDriver();

// Or with options:
ChromeOptions opts = new ChromeOptions();
[Link]("--headless=new", "--window-size=1920,1080");
WebDriver driver = new ChromeDriver(opts);
2. LOCATORS & ELEMENT IDENTIFICATION
2.1 Locator Types — Priority Order
Choose the most stable locator, in this priority:
1. ID — fastest, unique per page: [Link]([Link]("username"))
2. Name: [Link]("email")
3. CSS Selector — flexible, fast: [Link]("#login-btn")
4. XPath — most powerful, use when CSS cannot: [Link]("//button[@type='submit']")
5. LinkText / PartialLinkText: [Link]("Sign In")
6. TagName / ClassName — avoid, rarely unique

⚠️ NOTE: Avoid XPath using absolute paths like /html/body/div[2]/... — they break on any DOM
change. Always use relative XPath starting with //

2.2 CSS Selector Cheat Sheet


Selector Matches
#id Element with id
.className Element with class
input[type='text'] Attribute equals
input[name^='user'] Attribute starts with
input[name$='name'] Attribute ends with
input[name*='ser'] Attribute contains
div > p Direct child
div p Any descendant
li:nth-child(2) nth child
li:first-child First child
input:not([disabled]) Negation

2.3 XPath Cheat Sheet


Expression Purpose
//tag[@attr='val'] By attribute
//tag[text()='Login'] By exact text
//tag[contains(@class,'btn')] Contains in attribute
//tag[contains(text(),'Log')] Contains in text
//tag[normalize- Text ignoring whitespace
space()='Login']
//parent/child Direct child axis
//tag/ancestor::div Ancestor axis
//tag/following-sibling::td Following sibling
(//tag)[2] nth match
//tag[@a='x' and @b='y'] AND condition

🎯 Interview: How do you handle dynamic IDs in locators?


• Use contains(), starts-with() or ends-with() on stable partial values
• Target parent or sibling elements that are stable, then traverse
• Use custom data attributes (data-testid) — advocate for the dev team to add them
• Use CSS nth-of-type or position-based selectors as last resort

2.4 Selenium 4 Relative Locators


WebElement passwordField = [Link](
with([Link]("input")).below([Link]("username")));

// Available: above(), below(), toLeftOf(), toRightOf(), near()


3. ELEMENT INTERACTIONS & WAITS
3.1 Basic Interactions
Method Action
[Link]() Click an element
[Link]("text") Type into input
[Link]() Clear input value
[Link]() Get visible text
[Link]("value") Get attribute
[Link]() Visibility check
[Link]() Enabled check
[Link]() Selected check (checkbox/radio)
[Link]().to(url) Navigate to URL
[Link]().back() Browser back
[Link]() Get current URL
[Link]() Page title

3.2 Waits — The Most Critical Concept


⚠️ NOTE: Never use [Link]() in production code. It is brittle, slow, and hides real issues.
Always use explicit or fluent waits.

Implicit Wait
[Link]().timeouts().implicitlyWait([Link](10));
Sets a global poll interval for every findElement call. Simple but cannot wait for specific conditions.
Mixing with explicit waits causes unpredictable behaviour — pick one approach.

Explicit Wait
WebDriverWait wait = new WebDriverWait(driver, [Link](15));
WebElement el = [Link](
[Link]([Link]("success")));

Fluent Wait
Wait<WebDriver> wait = new FluentWait<>(driver)
.withTimeout([Link](30))
.pollingEvery([Link](500))
.ignoring([Link]);
WebElement el = [Link](d -> [Link]([Link]("result")));
Common ExpectedConditions
Condition Waits For
visibilityOfElementLocated(By Element visible in DOM
)
elementToBeClickable(By) Visible and enabled
presenceOfElementLocated(B Present in DOM (not necessarily visible)
y)
invisibilityOfElementLocated( Element is not visible
By)
titleContains(String) Page title contains text
urlContains(String) URL contains text
textToBePresentInElement(el, Element text matches
txt)
alertIsPresent() An alert is open
frameToBeAvailableAndSwitc Frame exists, switch to it
hToIt()
numberOfElementsToBe(By, Exact number of elements
n)
stalenessOf(element) Element detached from DOM

🎯 Interview: What is StaleElementReferenceException and how do you fix it?


A stale element means the element was found but the DOM was refreshed or updated since then,
making the reference invalid. Fixes:
• Re-locate the element just before the action
• Wrap the action in a retry loop with StaleElementReferenceException catch
• Use [Link]() to wait for the old element to disappear, then re-find
• Avoid storing WebElement references across page navigations

3.3 JavaScript Executor


JavascriptExecutor js = (JavascriptExecutor) driver;

// Click (bypass visibility/overlap issues)


[Link]("arguments[0].click();", element);

// Scroll element into view


[Link]("arguments[0].scrollIntoView(true);", element);

// Set input value directly


[Link]("arguments[0].value='text';", element);

// Get page performance timing


Long loadTime = (Long) [Link](
"return [Link] - [Link];");
💡 TIP: [Link]() bypasses Selenium's click which requires visibility. Useful for
elements behind overlays, but first investigate why the normal click fails — JS clicks skip real user
interaction validation.

3.4 Actions Class — Advanced Interactions


Actions actions = new Actions(driver);

// Hover
[Link](menuItem).perform();

// Right-click
[Link](element).perform();

// Double-click
[Link](element).perform();

// Drag and drop


[Link](source, target).perform();

// Key combination
[Link]([Link]).sendKeys("a").keyUp([Link]).perform();

// Click and hold + move


[Link](slider).moveByOffset(100, 0).release().perform();
4. HANDLING SPECIAL UI ELEMENTS
4.1 Dropdowns (Select Class)
Select dropdown = new Select([Link]([Link]("country")));

[Link]("India");
[Link]("IN");
[Link](2);

// Multi-select
[Link]("Java");
[Link]("Python");
List<WebElement> selected = [Link]();

⚠️ NOTE: Select class only works with native HTML <select> elements. For custom dropdowns
(div-based), click to expand, then findElements on the options list.

4.2 Alerts, Confirms & Prompts


// Switch to alert
Alert alert = [Link]().alert();

String alertText = [Link]();


[Link](); // Click OK
[Link](); // Click Cancel
[Link]("input"); // For prompt

💡 TIP: Always wait for the alert before switching: [Link]([Link]())

4.3 Frames & iFrames


// Switch by index
[Link]().frame(0);

// Switch by name or id
[Link]().frame("frameName");

// Switch by WebElement
WebElement frame = [Link]([Link]("iframe#map"));
[Link]().frame(frame);

// Return to main page


[Link]().defaultContent();

// Return to parent frame


[Link]().parentFrame();
4.4 Multiple Windows & Tabs
String mainWindow = [Link]();

// Click link that opens new tab


Set<String> handles = [Link]();
for (String h : handles) {
if (![Link](mainWindow)) {
[Link]().window(h);
break;
}
}

// Return to main
[Link]().window(mainWindow);

🎯 Interview: How do you open a new tab and switch to it in Selenium 4?


[Link]().newWindow([Link]);
[Link]().newWindow([Link]);

4.5 File Upload & Download

File Upload
// For <input type='file'> — no need to interact with OS dialog
[Link]([Link]("input[type='file']"))
.sendKeys("/absolute/path/to/[Link]");

File Download
ChromeOptions opts = new ChromeOptions();
Map<String, Object> prefs = new HashMap<>();
[Link]("download.default_directory", "/path/to/download/");
[Link]("download.prompt_for_download", false);
[Link]("prefs", prefs);

4.6 Checkboxes, Radio Buttons & Tables

Checkbox
WebElement cb = [Link]([Link]("agree"));
if (![Link]()) { [Link](); } // Check only if not already checked

Iterating a Web Table


List<WebElement> rows = [Link](
[Link]("table#results tbody tr"));
for (WebElement row : rows) {
List<WebElement> cells = [Link]([Link]("td"));
[Link]([Link](0).getText() + " | " + [Link](1).getText());
}
5. FRAMEWORK ARCHITECTURE
5.1 Page Object Model (POM)
POM is the most widely used design pattern in Selenium automation. Each page/component is
represented by a Java class.

Base Page
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 el) {


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

protected void type(WebElement el, String text) {


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

Page Class
public class LoginPage extends BasePage {

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

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

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

@FindBy(css = ".error-message")
private WebElement errorMessage;

public LoginPage(WebDriver driver) {


super(driver);
}

public DashboardPage login(String user, String pass) {


type(usernameField, user);
type(passwordField, pass);
click(loginBtn);
return new DashboardPage(driver); // Method chaining
}

public String getErrorMessage() {


return [Link]([Link](errorMessage)).getText();
}
}

5.2 TestNG Setup

Base Test
public class BaseTest {
protected WebDriver driver;

@BeforeMethod
public void setUp() {
ChromeOptions opts = new ChromeOptions();
if ([Link]("CI") != null) {
[Link]("--headless=new", "--no-sandbox", "--disable-dev-shm-usage");
}
driver = new ChromeDriver(opts);
[Link]().window().maximize();
[Link]().timeouts().pageLoadTimeout([Link](30));
}

@AfterMethod
public void tearDown(ITestResult result) {
if ([Link]() == [Link]) {
[Link](driver, [Link]());
}
if (driver != null) [Link]();
}
}

Sample Test
public class LoginTest extends BaseTest {

@Test(description = "Valid login should redirect to dashboard")


public void validLoginTest() {
LoginPage loginPage = new LoginPage(driver);
[Link](Config.BASE_URL + "/login");

DashboardPage dashboard = [Link](


[Link], [Link]);

[Link]([Link](),
"Welcome message should be visible after login");
}
}
5.3 Project Structure
Package/Folder Contents
src/test/java/pages Page Object classes
src/test/java/tests Test classes (extend BaseTest)
src/test/java/utils Utilities: Config, Screenshot, ExcelReader, etc.
src/test/java/components Reusable UI components: Header, Sidebar, Modal
src/test/java/listeners TestNG listeners for reporting
src/test/resources [Link], [Link], test data files
reports/ Generated Extent / Allure HTML reports
screenshots/ Failure screenshots

5.4 Data-Driven Testing

TestNG DataProvider
@DataProvider(name = "loginData")
public Object[][] loginData() {
return new Object[][] {
{"admin", "admin123", true},
{"user1", "wrongPass", false},
{"locked_user", "pass", false},
};
}

@Test(dataProvider = "loginData")
public void loginTest(String user, String pass, boolean expected) {
LoginPage lp = new LoginPage(driver);
[Link](Config.BASE_URL);
boolean result = [Link](user, pass).isLoggedIn();
[Link](result, expected, "Login status mismatch for: " + user);
}

Excel Data Provider with Apache POI


public static Object[][] readExcel(String file, String sheet) throws Exception {
Workbook wb = [Link](new File(file));
Sheet s = [Link](sheet);
int rows = [Link]();
int cols = [Link](0).getLastCellNum();
Object[][] data = new Object[rows][cols];
for (int r = 1; r <= rows; r++)
for (int c = 0; c < cols; c++)
data[r-1][c] = [Link](r).getCell(c).toString();
return data;
}
6. CONFIGURATION & UTILITIES
6.1 Configuration Management

[Link]
[Link]=[Link]
browser=chrome
[Link]=5
[Link]=15
username=testuser
password=testpass

ConfigReader Class
public class ConfigReader {
private static Properties prop = new Properties();
static {
try (InputStream is = [Link]
.getClassLoader().getResourceAsStream("[Link]")) {
[Link](is);
} catch (IOException e) { throw new RuntimeException(e); }
}
public static String get(String key) { return [Link](key); }
}

6.2 Screenshot Utility


public class Screenshot {
public static String capture(WebDriver driver, String testName) {
String timestamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String path = "screenshots/" + testName + "_" + timestamp + ".png";
File src = ((TakesScreenshot) driver).getScreenshotAs([Link]);
try {
[Link](src, new File(path));
} catch (IOException e) { [Link](); }
return path;
}
}

6.3 TestNG Listeners


public class TestListener implements ITestListener {

@Override
public void onTestFailure(ITestResult result) {
WebDriver driver = ((BaseTest) [Link]()).driver;
String path = [Link](driver, [Link]());
// Attach to Extent or Allure report
[Link]("Screenshot saved: " + path);
}
}
Register in [Link]:
<listeners>
<listener class-name="[Link]"/>
</listeners>

6.4 Parallel Execution — [Link]


<suite name="Regression" parallel="methods" thread-count="4">
<test name="Login Tests">
<classes>
<class name="[Link]"/>
<class name="[Link]"/>
</classes>
</test>
</suite>

⚠️ NOTE: For parallel tests, use ThreadLocal<WebDriver> to prevent threads sharing the same
driver instance.

public class DriverManager {


private static ThreadLocal<WebDriver> tlDriver = new ThreadLocal<>();

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

public static void setDriver(WebDriver driver) { [Link](driver); }

public static void removeDriver() { [Link](); }


}
7. SELENIUM GRID & CI/CD
7.1 Selenium Grid 4 Architecture
Component Role
Router Entry point — routes requests to the correct component
Distributor Tracks available Node slots; assigns sessions
Session Map Maps session IDs to Nodes
Node Machine running actual browsers; can run multiple sessions
Event Bus Internal messaging between Grid components

Start Standalone Grid (local testing)


java -jar [Link] standalone
# Grid console: [Link]

Start Hub + Node


# Hub
java -jar [Link] hub

# Node
java -jar [Link] node --hub [Link]

Remote WebDriver
ChromeOptions opts = new ChromeOptions();
driver = new RemoteWebDriver(
new URL("[Link] opts);

7.2 Docker Compose — Selenium Grid


version: "3"
services:
selenium-hub:
image: selenium/hub:4.21.0
ports: ["4442:4442", "4443:4443", "4444:4444"]
chrome-node:
image: selenium/node-chrome:4.21.0
depends_on: [selenium-hub]
environment:
- SE_EVENT_BUS_HOST=selenium-hub
- SE_EVENT_BUS_PUBLISH_PORT=4442
- SE_EVENT_BUS_SUBSCRIBE_PORT=4443
volumes:
- /dev/shm:/dev/shm
7.3 CI/CD — GitHub Actions Example
name: Selenium Tests
on: [push, pull_request]
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-java@v4
with: { java-version: '17', distribution: 'temurin' }
- name: Run Tests
run: mvn test -Dbrowser=chrome -Dheadless=true
- name: Upload Reports
uses: actions/upload-artifact@v4
if: always()
with:
name: test-reports
path: reports/
8. REPORTING FRAMEWORKS
8.1 Extent Reports
// Initialise (once per suite)
ExtentReports extent = new ExtentReports();
ExtentSparkReporter spark = new ExtentSparkReporter("reports/[Link]");
[Link]().setTheme([Link]);
[Link](spark);

// Per test
ExtentTest test = [Link]("Login Test");
[Link]("Navigating to login page");
[Link]("Login successful");
[Link]("Element not found");
[Link](screenshotPath);

// Flush at end of suite


[Link]();

8.2 Allure Reports


• Add allure-testng dependency to [Link]
• Annotate tests: @Story, @Feature, @Description, @Step
• Run: mvn test, then allure serve target/allure-results

@Feature("Authentication")
@Story("Valid Login")
@Test(description = "Login with valid credentials")
public void loginTest() {
[Link]("Enter username", () -> [Link]("admin"));
[Link]("Enter password", () -> [Link]("pass"));
[Link]("Click login", loginPage::clickLogin);
}
9. DAY-TO-DAY TASKS & CAREER EVOLUTION
9.1 Junior Automation Engineer (0–1 year)

Daily Activities
• Writing new test cases based on manual test scenarios provided by QA lead
• Maintaining and fixing flaky tests reported by the team
• Running regression suite and sharing results
• Updating Page Object classes when developers change the UI
• Raising bugs in JIRA with screenshots and steps to reproduce
• Participating in daily standups, sprint planning, and retrospectives

Key Skills at This Level


• Confident with all locator strategies
• Comfortable writing TestNG @Test, @BeforeMethod, @AfterMethod
• Can read and write basic XPath and CSS selectors
• Understands POM and can create new page objects
• Can debug common exceptions: NoSuchElementException, StaleElementReferenceException,
TimeoutException

9.2 Mid-Level Automation Engineer (1–3 years)

Daily Activities
• Designing new page objects and utility classes from scratch
• Integrating test suite into CI/CD pipeline (Jenkins/GitHub Actions)
• Implementing Extent or Allure reporting with failure screenshots
• Creating data-driven tests with Excel/JSON/DataProvider
• Reviewing automation code from juniors
• Performance and API testing with RestAssured
• Participating in test strategy discussions

Key Skills at This Level


• Deep understanding of waits and when to use each type
• ThreadLocal-based parallel execution
• Selenium Grid setup and Docker containerisation
• Basic API testing skills (RestAssured, Postman)
• Version control best practices (Git branching, PRs, code review)

9.3 Senior Automation Engineer (3+ years)

Daily Activities
• Defining the overall test architecture and tooling choices
• Setting up BDD (Cucumber) framework with Gherkin feature files
• Integrating with cloud grids: BrowserStack, Sauce Labs, LambdaTest
• Defining automation strategy: what to automate, ROI analysis
• Mentoring junior and mid-level engineers
• Establishing coding standards and design patterns across the team
• Performance testing with JMeter/Gatling
• Mobile automation with Appium

9.4 Common Framework Evolution Path


Phase What You Add
Phase 1: Basic WebDriver + TestNG + POM (month 1–3)
Phase 2: Utilities Screenshots, Config, Excel DataProvider (month 3–6)
Phase 3: Reporting Extent Reports + Listeners (month 4–6)
Phase 4: Parallel ThreadLocal + [Link] parallel (month 6–9)
Phase 5: CI Jenkins/GitHub Actions pipeline (month 6–12)
Phase 6: BDD Cucumber + Gherkin + Step Definitions (year 1–2)
Phase 7: Grid/Cloud Selenium Grid / BrowserStack (year 1–2)
Phase 8: API+Mobile RestAssured + Appium integration (year 2–3)
10. BDD WITH CUCUMBER
10.1 Cucumber Maven Dependencies
<dependency>
<groupId>[Link]</groupId>
<artifactId>cucumber-java</artifactId>
<version>7.18.0</version>
</dependency>
<dependency>
<groupId>[Link]</groupId>
<artifactId>cucumber-testng</artifactId>
<version>7.18.0</version>
</dependency>

10.2 Feature File Example


Feature: User Authentication

Scenario: Successful login with valid credentials


Given the user is on the login page
When the user enters username "admin" and password "admin123"
And the user clicks the login button
Then the dashboard page should be displayed

Scenario Outline: Login with multiple users


Given the user is on the login page
When the user enters username "<user>" and password "<pass>"
Then login result should be "<result>"
Examples:
| user | pass | result |
| admin | admin123 | success |
| user1 | wrong | failure |

10.3 Step Definitions


public class LoginSteps {
WebDriver driver = [Link];
LoginPage loginPage = new LoginPage(driver);

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


public void navigateToLogin() {
[Link]([Link]("[Link]") + "/login");
}

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


public void enterCredentials(String user, String pass) {
[Link](user);
[Link](pass);
}

@Then("the dashboard page should be displayed")


public void verifyDashboard() {
[Link](new DashboardPage(driver).isLoaded());
}
}
11. EXCEPTION REFERENCE & DEBUGGING
11.1 Exception Quick Reference
Exception Cause & Fix
NoSuchElementException Element not in DOM — check locator or wait for element
TimeoutException Wait condition not met in time — increase timeout or fix locator
StaleElementReferenceExcep DOM refreshed after element was found — re-locate element
tion
ElementNotInteractableExcep Element in DOM but not visible/enabled — add wait or scroll into
tion view
ElementClickInterceptedExce Another element is overlapping the target — close overlay or use JS
ption click
WebDriverException: crashed Browser crashed — check memory, headless args, or driver version
NoAlertPresentException Alert not present when switching — wait for alertIsPresent()
NoSuchWindowException Window handle no longer valid — verify window was not closed
InvalidSelectorException XPath/CSS syntax error — validate the selector in browser
DevTools
SessionNotFoundException Driver session is null or closed — ensure @BeforeMethod creates
driver

11.2 Debugging Tips


• Use browser DevTools (F12) to test selectors live: $('css'), $x('xpath')
• Enable verbose logging: [Link]("[Link]", "true")
• Take a screenshot on failure and log [Link]()
• Use [Link]().logs().get([Link]) to capture console errors
• Add explicit waits before each assertion, not just before each action
• Run the failing test in non-headless mode to visually observe behaviour

11.3 Flaky Test Strategies


• Add smart waits — wait for specific conditions, not sleep
• Retry failed tests: use TestNG @Test(retryAnalyzer = [Link])
• Isolate test data — each test creates its own data, never shares
• Clear cookies/local storage between tests to avoid state bleed
• Use API calls for test setup/teardown to reduce UI dependency
• Monitor flakiness rate in CI — tests with > 5% flakiness rate get refactored
12. TOP INTERVIEW QUESTIONS & ANSWERS
12.1 Core Selenium
🎯 Interview: What is the difference between [Link]() and [Link]()?
• close() closes only the current browser window. If multiple windows/tabs are open, others
remain. The WebDriver session is still active.
• quit() closes all windows opened by the WebDriver session and ends the session cleanly.
Always use quit() in teardown.

🎯 Interview: What is implicit wait? Can it be combined with explicit wait?


• Implicit wait tells WebDriver to poll the DOM for a set duration before throwing
NoSuchElementException. It applies globally.
• Mixing implicit and explicit waits is strongly discouraged. Implicit wait sets a floor time for every
findElement; when explicit wait polls, the total timeout can double or behave unpredictably.
• Best practice: Set implicit wait to 0 and use only explicit waits for control.

🎯 Interview: How do you handle dynamically loading content (AJAX)?


• Use explicit wait with [Link]()
• Wait for invisibility of a loading spinner if one exists
• For attribute-based load completion, use attributeContains condition
• Fluent wait with short polling and NoSuchElementException ignored

🎯 Interview: What is the Page Object Model and why is it used?


• POM is a design pattern where each web page/component has a corresponding Java class that
holds locators and actions.
• Benefits: separation of concerns, code reuse, single point of change for locators, improved
readability
• An update to the UI only requires changing the page class, not every test that uses that page

🎯 Interview: How do you run tests in parallel in TestNG?


• Set parallel="methods" (or classes/tests) and thread-count in [Link]
• Use ThreadLocal<WebDriver> to give each thread its own driver instance
• Avoid static driver fields — they cause threads to interfere with each other
• Ensure test data is isolated per thread

12.2 Framework Design


🎯 Interview: How would you design a framework from scratch?
7. Decide: TestNG or JUnit 5, Maven or Gradle
8. Create a Maven project with selenium-java, testng, WebDriverManager dependencies
9. Implement DriverFactory with ThreadLocal for cross-browser & parallel support
10. Build BasePage with common wait and interaction methods
11. Create page objects using POM + PageFactory
12. Add ConfigReader for environment-specific properties
13. Implement Screenshot utility and TestNG Listener
14. Integrate Extent or Allure reporting
15. Add DataProvider / Excel reader for data-driven tests
16. Set up [Link] suites for smoke, regression, and sanity
17. Configure Maven Surefire plugin for CI execution

🎯 Interview: How do you handle test data management?


• Environment configs: [Link] per environment (dev/staging/prod)
• Test data: Excel/CSV files, or JSON loaded by DataProvider
• Sensitive credentials: environment variables or a secrets vault — never hardcoded
• Database seeding: pre-populate DB before suite, clean up after
• API-driven setup: call REST endpoints to create test data instead of navigating UI

12.3 Advanced Topics


🎯 Interview: What is Selenium Grid and when would you use it?
• Grid allows running tests in parallel across multiple machines and browsers
• Use cases: cross-browser testing, reducing overall execution time, testing on specific
OS+browser combos
• Selenium 4 Grid uses Router/Distributor/Node architecture compliant with W3C

🎯 Interview: How do you integrate Selenium with Jenkins?


• Create a Freestyle or Pipeline job pointing to your Git repository
• Add a build step: mvn clean test -Dbrowser=chrome -Denv=staging
• Use the HTML Publisher plugin or Allure Jenkins plugin for reports
• Trigger on push via webhook or poll SCM
• For headless execution on Jenkins slave: add --headless=new to ChromeOptions

🎯 Interview: How do you handle cross-browser testing?


public static WebDriver createDriver(String browser) {
return switch ([Link]()) {
case "firefox" -> new FirefoxDriver(new FirefoxOptions());
case "edge" -> new EdgeDriver(new EdgeOptions());
default -> new ChromeDriver(new ChromeOptions());
};
}

Pass browser via system property: -Dbrowser=firefox. For distributed cross-browser testing, use
BrowserStack or LambdaTest with RemoteWebDriver.

🎯 Interview: What is CDP and how is it used in Selenium 4?


• Chrome DevTools Protocol (CDP) allows low-level browser control beyond the W3C spec
• Intercept and mock network requests
• Emulate geolocation, device metrics, network conditions
• Listen to console events and performance metrics
// Emulate geolocation
((ChromeDriver) driver).executeCdpCommand(
"[Link]",
[Link]("latitude", 48.8566, "longitude", 2.3522, "accuracy", 1));
13. BEST PRACTICES & QUICK REFERENCE
13.1 The Automation Golden Rules
18. Tests should be independent — no test should depend on another test's result or state
19. Test data should be isolated — create what you need, clean up after
20. One assertion per test logical scenario — or group related assertions
21. Fail fast and fail clearly — assertion messages must explain what was expected
22. Page objects should return page objects — use fluent method chaining
23. Avoid hardcoded values — use config files and constants
24. Keep tests deterministic — same result every time on same environment
25. Headless for CI, headed for debugging
26. Review and refactor automation code like production code
27. Monitor and maintain — automate alerts when flakiness exceeds threshold

13.2 Common Locator Anti-Patterns


Anti-Pattern Why It's Bad
//div[2]/form/input[1] Absolute XPath — breaks on any DOM change
[Link]("btn") alone Too generic — always combine with context
[Link]("//*[text()='Submit']") Text-based — fails on i18n or minor text changes
[Link]("div:nth- Position-based — unstable if order changes
child(5)")
[Link]("comp-12345abc") Generated ID — changes on redeploy; add data-testid

13.3 TestNG Annotations Cheat Sheet


Annotation When It Runs
@BeforeSuite Runs once before all tests in suite — driver factory init
@AfterSuite Runs once after all tests — report flush
@BeforeTest Runs before each <test> block in [Link]
@AfterTest Runs after each <test> block
@BeforeClass Runs once before first @Test in the class
@AfterClass Runs once after last @Test in the class
@BeforeMethod Runs before EVERY @Test method — driver setup
@AfterMethod Runs after EVERY @Test method — driver quit
@Test Marks a method as a test; accepts groups, priority,
dependsOnMethods, retryAnalyzer
@DataProvider Supplies test data as Object[][]
@Parameters Injects values from [Link] <parameter> tags
@Listeners Attaches a listener class to the test class

13.4 Key Libraries Ecosystem


Library Purpose
selenium-java 4.x Core browser automation
testng 7.x Test framework: annotations, assertions, parallel execution
extent-reports 5.x Rich HTML test reports
allure-testng 2.x Allure reporting integration
webdrivermanager 5.x Auto-download of browser drivers (Selenium 3 era)
apache-poi 5.x Read/write Excel files for data-driven tests
rest-assured 5.x API testing alongside UI automation
log4j2 / slf4j Logging framework
json-simple / jackson JSON parsing for test data and API responses
cucumber-java 7.x BDD Gherkin step definitions
maven-surefire-plugin 3.x Maven plugin to run TestNG/JUnit tests

— End of Study Guide —

Good luck with your interviews!

You might also like