These Selenium interview questions for 5 years of experience are for senior automation engineers and SDETs (about 3–5+ years). Interviewers expect you to talk about architecture and scale: Selenium 4 and the W3C standard, Chrome DevTools Protocol, Grid 4 and Docker, cloud platforms, API and UI hybrid tests with database checks, Cucumber integration, visual and self-healing approaches, suite optimisation, CI/CD pipelines and systematic flakiness reduction.
Planning your learning? Follow the Selenium automation testing roadmap.
Selenium 4 Exclusive Features
1. What are the major new features introduced in Selenium 4?
Selenium 4 (released 2021) brought significant improvements over Selenium 3:
- 1. W3C WebDriver Standard: Full compliance — eliminates JSON Wire Protocol inconsistencies. More stable across browsers.
- 2. Chrome DevTools Protocol (CDP): Direct integration to control Chrome internals — network, performance, geolocation, console logs.
- 3. Relative Locators: Find elements by position relative to other elements (above, below, toLeftOf, toRightOf, near).
4. New Window/Tab API: driver.switchTo().newWindow(WindowType.TAB) — open tab without JS.
- 5. Improved Selenium Grid 4: New architecture (Standalone/Hub/Node/Distributed modes), Docker support, observability.
- 6. Selenium Manager: Built-in automatic browser driver management — no more manual ChromeDriver download.
- 7. Element Screenshot: element.getScreenshotAs(OutputType.FILE) — screenshot of specific element only.
- 8. getShadowRoot(): Native Shadow DOM support — shadowHost.getShadowRoot().findElement(By.css("input"))
- 9. getRect(): Returns element Rectangle (location + size) in one call.
- 10. Enhanced Actions:
scrollToElement(), scrollByAmount(), wheel actions.
2. What is the W3C WebDriver standard? How does it affect Selenium 4?
W3C WebDriver is an international standard (RFC) for browser automation.
- Selenium 3 used JSON Wire Protocol (a custom Selenium specification)
- Selenium 4 fully implements W3C WebDriver specification
Benefits of W3C compliance
- All browsers implement the same standard — fewer browser-specific bugs
- DesiredCapabilities replaced by browser-specific Options (ChromeOptions, FirefoxOptions)
- More predictable behavior across Chrome, Firefox, Edge, Safari
- Actions API standardized — drag-drop, scroll more reliable
Breaking changes from Selenium 3 to 4
- DesiredCapabilities removed — use ChromeOptions, FirefoxOptions, etc.
- driver.manage().timeouts() — Duration instead of int/TimeUnit
- findElement() behavior slightly changed
- Some deprecated methods removed
Chrome DevTools Protocol (CDP)
3. What is Chrome DevTools Protocol? How do you use it in Selenium 4?
CDP is the protocol used by Chrome DevTools to communicate with the browser. Selenium 4 exposes it directly.
- Access CDP:
ChromeDriver cd = (ChromeDriver) driver; DevTools devTools = cd.getDevTools(); - Create session:
devTools.createSession();
CAPTURE CONSOLE LOGS
devTools.send(Log.enable());- devTools.addListener(Log.entryAdded(), logEntry -> System.out.println(logEntry.getText()));
CAPTURE NETWORK REQUESTS
- devTools.send(Network.enable(Optional.empty(), Optional.empty(), Optional.empty()));
- devTools.addListener(Network.requestWillBeSent(), req -> System.out.println(req.getRequest().getUrl()));
- BLOCK NETWORK REQUESTS (e.g., block images for speed):
- devTools.send(Network.setBlockedURLs(Arrays.asList("*.png", "*.jpg", "*.gif")));
MOCK NETWORK RESPONSE
- devTools.send(Fetch.enable(Optional.empty(), Optional.empty()));
devTools.addListener(Fetch.requestPaused(), req -> { devTools.send(Fetch.fulfillRequest(req.getRequestId(), 200, Optional.empty(), Optional.empty(), Optional.of("{\"mocked\":true}"), Optional.empty())); });
4. How do you emulate geolocation, network conditions, and mobile devices using CDP?
CDP enables powerful browser simulation capabilities for testing.
GEOLOCATION EMULATION
devTools.send(Emulation.setGeolocationOverride(
Optional.of(17.3850), // latitude
Optional.of(78.4867), // longitude
Optional.of(1.0) // accuracy
));
NETWORK CONDITIONS (throttling)
devTools.send(Network.emulateNetworkConditions(
false, // offline
100, // latency ms
50000, // downloadThroughput bytes/sec
20000, // uploadThroughput bytes/sec
Optional.of(Network.ConnectionType.CELLULAR3G)
));- OFFLINE MODE:
Network.emulateNetworkConditions(true, 0, 0, 0, Optional.empty());
MOBILE DEVICE EMULATION
- devTools.send(Emulation.setDeviceMetricsOverride(375, 812, 2.0, true, Optional.empty(), Optional.empty(), Optional.empty(), Optional.empty(), Optional.empty(), Optional.empty(), Optional.empty(), Optional.empty(), Optional.empty()));
- SET USER AGENT: devTools.send(Network.setUserAgentOverride("Mozilla/5.0 (iPhone...)", Optional.empty(), Optional.empty(), Optional.empty()));
Selenium Grid & Parallel Execution
5. How does Selenium Grid 4 work? What are its different modes?
Selenium Grid 4 distributes test execution across multiple machines and browsers.
STANDALONE MODE: Single node runs Hub+Node together. Best for simple setups.
java -jar selenium-server.jar standalone
Grid console: http://localhost:4444/ui
HUB + NODE MODE: Hub receives requests, routes to registered nodes.
Hub: java -jar selenium-server.jar hub
Node: java -jar selenium-server.jar node --hub http://hub:4444
DISTRIBUTED MODE: Each component runs separately — Router, Distributor, SessionMap, Node.
Best for large-scale cloud deployments
KEY COMPONENTS in Grid 4
- Router: Entry point — routes requests
- Distributor: Knows all nodes and their capabilities
- SessionMap: Tracks active sessions
- EventBus: Internal messaging between components
- Node: Machine that runs actual browser sessions
USING GRID IN TESTS
ChromeOptions options = new ChromeOptions();- driver = new RemoteWebDriver(new URL("http://localhost:4444"), options);
6. How do you implement thread-safe parallel execution in Selenium?
Parallel execution requires each thread to have its own WebDriver instance — use ThreadLocal.
THE PROBLEM: Static WebDriver shared across threads → race conditions, tests interfering
SOLUTION — ThreadLocal WebDriver
public class DriverManager {
private static ThreadLocal<WebDriver> driver = new ThreadLocal<>();
public static WebDriver getDriver() { return driver.get(); }
public static void setDriver(WebDriver d) { driver.set(d); }
public static void quitDriver() {
if(driver.get() != null) { driver.get().quit(); driver.remove(); }
}
}- In @BeforeMethod: DriverManager.setDriver(new ChromeDriver()); // New driver per thread
In @AfterMethod: DriverManager.quitDriver();- In page classes: use DriverManager.getDriver() instead of passing driver
- TestNG XML for parallel: <suite parallel='methods' thread-count='4'>
- Parallel='methods': Each @Test in its own thread
- Parallel='classes': Each test class in its own thread
7. How do you set up Selenium Grid with Docker Compose?
Docker enables reproducible, scalable Grid environments without manual browser installation.
docker-compose.yml:
version: '3'
services:
selenium-hub:
image: selenium/hub:4
ports: ['4442:4442', "4443:4443", '4444:4444']
chrome-node:
image: selenium/node-chrome:4
environment:
- SE_EVENT_BUS_HOST=selenium-hub
- SE_EVENT_BUS_PUBLISH_PORT=4442
- SE_EVENT_BUS_SUBSCRIBE_PORT=4443
- SE_NODE_MAX_SESSIONS=3
shm_size: '2gb' # Required for Chrome
depends_on: [selenium-hub]
firefox-node:
image: selenium/node-firefox:4
environment: [same as chrome-node]
depends_on: [selenium-hub]
- Start: docker-compose up -d
- Scale: docker-compose up -d --scale chrome-node=5
- Verify: http://localhost:4444/ui — Grid console
Cross-Browser & Cloud Testing
8. How do you implement cross-browser testing in Selenium?
Cross-browser testing verifies application works correctly across different browsers.
APPROACH 1 — Driver Factory based on config
String browser = System.getProperty("browser", "chrome"); // Pass via Maven: -Dbrowser=firefox
switch(browser) {
case 'chrome': driver = new ChromeDriver(new ChromeOptions()); break;
case 'firefox': driver = new FirefoxDriver(new FirefoxOptions()); break;
case 'edge': driver = new EdgeDriver(new EdgeOptions()); break;
case 'safari': driver = new SafariDriver(); break;
}
APPROACH 2 — TestNG parameterization
- testng.xml: <parameter name='browser' value='chrome'/>
@Parameters("browser") @BeforeMethod public void setup(String browser) { ... }
APPROACH 3 — TestNG DataProvider
@DataProvider(name="browsers") public Object[][] browsers() { return new Object[][]{{"chrome"},{"firefox"}}; }
@Test(dataProvider="browsers") public void test(String browser) { ... }
- Browser-specific issues: CSS rendering differences, JS engine variations, HTML5 feature support
9. How do you run Selenium tests on BrowserStack? What are its advantages?
BrowserStack provides real browsers and devices on cloud infrastructure.
- String hubURL = "https://"+USERNAME+':'+ACCESS_KEY+"@hub-cloud.browserstack.com/wd/hub";
ChromeOptions options = new ChromeOptions();- HashMap<String, Object> bstackOptions = new HashMap<>();
bstackOptions.put("os", "Windows");bstackOptions.put("osVersion", "11");bstackOptions.put("browserVersion", "latest");bstackOptions.put("projectName", "My Project");bstackOptions.put("buildName", "Build 1.0");bstackOptions.put("sessionName", "Login Test");
options.setCapability("bstack:options", bstackOptions);
- driver = new RemoteWebDriver(new URL(hubURL), options);
ADVANTAGES
- Real devices — not emulators — for mobile testing
- thousands of browser/OS combinations without managing infrastructure
- Videos, screenshots, console logs automatically captured
- Parallel execution without your own Grid setup
- BrowserStack Local: Test internal staging environments via tunnel
API + UI Integration & Design Patterns
10. How do you combine API testing and UI testing in the same Selenium framework?
Hybrid API+UI testing strategy — use API for setup, UI for verification. Much faster than full UI automation.
PATTERN: API → set up test state → UI → verify visual result
Example — Test order confirmation page
- 1. API: POST /api/orders with test data → get orderId from response
- 2. API: POST /api/auth/login → get JWT token → store in cookie
3. UI: driver.get("/orders/" + orderId); // Skip login UI
- 4. UI: Verify order details displayed correctly
- INJECT SESSION VIA COOKIE (bypass UI login):
driver.get(baseUrl); // Open domain first (can't set cookie before)
driver.manage().addCookie(new Cookie("authToken", jwtToken));
driver.navigate().refresh();
// Now logged in without going through UI login flow
- Benefits: Tests run 3-5x faster, login tests not re-tested every time, stable test data setup
- Tools: REST Assured in same Maven project as Selenium
- Best practice: APIHelper class wraps REST Assured for clean reuse across tests
11. Explain the design patterns commonly used in a Selenium framework.
Senior-level question — understanding design patterns shows framework architecture maturity.
- PAGE OBJECT MODEL: Each page = one class. Separates locators and actions from test logic. Most fundamental pattern.
- SINGLETON: One WebDriver instance per thread. Prevents multiple browser windows from opening accidentally.
- FACTORY METHOD: WebDriverFactory creates browser-specific driver based on configuration.
public static WebDriver createDriver(String browser) { switch(browser) { ... } }
- BUILDER PATTERN: Construct complex test data objects.
User user = new User.Builder().withName("John").withRole("Admin").withEmail("j@test.com").build();
- STRATEGY PATTERN: Swap data source at runtime.
interface DataStrategy { Map<String,String> getData(); }
class ExcelStrategy implements DataStrategy { ... }
class JSONStrategy implements DataStrategy { ... }
- FACADE PATTERN: APIHelper hides REST Assured complexity.
apiHelper.createUser(userData); // Simple method call hides headers, auth, serialization
- OBSERVER/LISTENER: TestNG/Cucumber listeners for cross-cutting concerns.
Capture screenshot on failure, log test start/end, update Extent Reports
Visual Testing & Self-Healing Locators
12. What is Visual Testing in Selenium? How do you implement it?
Visual testing verifies that the UI renders correctly — catches CSS/layout regressions that functional tests miss.
APPROACH 1 — AShot (open-source pixel comparison)
Screenshot baseline = new AShot().takeScreenshot(driver); // Save as baselineScreenshot current = new AShot().takeScreenshot(driver); // Current runImageDiff diff = new ImageDiffer().makeDiff(baseline, current);- Assert.assertFalse(diff.hasDiff(), "Visual difference detected");
APPROACH 2 — Applitools Eyes (AI-powered)
Eyes eyes = new Eyes(); eyes.setApiKey("YOUR_KEY");eyes.open(driver, "App Name", "Test Name");eyes.checkWindow("Login Page"); // Visual checkpointeyes.close();- Applitools uses AI to ignore minor rendering differences (fonts, antialiasing)
- BASELINE MANAGEMENT: First run creates baseline; subsequent runs compare against it
- Dynamic content: Mask/ignore dynamic areas (timestamps, ads) using ignore regions
- CI integration: Fail build if visual differences exceed threshold
13. What are self-healing locators? How does Healenium work with Selenium?
Self-healing locators automatically fix broken locators when UI changes, preventing test failures.
PROBLEM: UI changes (dev renames id, adds class) → tests fail with NoSuchElementException
- SELF-HEALING: Framework detects locator failure, searches for element using backup strategies, updates locator
- HEALENIUM — open-source self-healing proxy for Selenium:
- Add dependency: com.epam.healenium:healenium-web
- Wrap driver:
WebDriver healingDriver = SelfHealingDriver.create(driver); - Healenium stores element snapshots in PostgreSQL database
- When locator fails → Healenium uses a tree-comparison algorithm to find element by similarity to stored snapshot
- Reports: Shows which locators were healed and suggests updated selectors
COMMERCIAL ALTERNATIVES
- Testim: AI-powered test authoring with automatic locator healing
- Mabl: ML-based self-healing tests
- Functionize: NLP + AI for test creation and healing
MANUAL SELF-HEALING APPROACH: Store multiple fallback locators, try each on failure
- Limitation: Self-healing is reactive — test still ran with a different element; always review healed locators
Performance Optimization & CI/CD Integration
14. How do you optimize a Selenium test suite for faster execution?
Performance optimization strategies for large Selenium suites:
- 1. PARALLEL EXECUTION: Run tests in parallel with TestNG (thread-count=4 or more). Biggest gain.
- 2. API BYPASS: Use API calls to set up test state instead of navigating through UI flows.
- 3. EXPLICIT WAITS ONLY: Remove Thread.sleep(), use explicit waits with tight timeouts.
- 4. HEADLESS MODE: usually faster than headed — use in CI/CD.
- 5. BLOCK UNNECESSARY RESOURCES: Use CDP to block images, fonts, analytics scripts.
devTools.send(Network.setBlockedURLs(Arrays.asList("*.png","*.css","analytics.js")));
6. PAGE LOAD STRATEGY: options.setPageLoadStrategy(PageLoadStrategy.EAGER); // Don't wait for images
- 7. REUSE DRIVER: Don't create/destroy driver for each test if using same preconditions (with state reset).
- 8. REDUCE ASSERTIONS: Only assert what matters — avoid redundant checks.
- 9. SMART GROUPING: Run smoke tests first, fail fast before running full regression.
- 10. REMOVE REDUNDANT TESTS: Audit suite regularly — remove duplicate/obsolete tests.
15. How do you write a Jenkins Declarative Pipeline for Selenium tests?
A production-ready Jenkins pipeline for Selenium + Maven + TestNG:
pipeline {
agent any
environment { BROWSER = "chrome" }
stages {
stage("Checkout") {
steps { git branch: 'main', url: 'https://github.com/org/repo.git' }
}
stage("Build") {
steps { sh 'mvn clean compile -q' }
}
stage("Test") {
steps { sh 'mvn test -Dbrowser=${BROWSER} -Dheadless=true' }
}
stage("Reports") {
steps { publishHTML(target: [reportDir: 'reports', reportFiles: 'index.html']) }
}
}
post {
always { junit 'target/surefire-reports/*.xml' }
failure { emailext subject: 'Tests FAILED', body: '${BUILD_URL}', to: 'team@company.com' }
success { slackSend message: 'Tests PASSED on ${env.BRANCH_NAME}' }
}
}
16. How do you write a GitHub Actions workflow for Selenium tests?
GitHub Actions provides free CI/CD with Ubuntu runners that support headless Chrome.
- # .github/workflows/selenium-tests.yml
name: Selenium Tests
on: [push, pull_request]
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: actions/setup-java@v3
with: { java-version: '11', distribution: 'temurin' }
- name: Setup Chrome
uses: browser-actions/setup-chrome@latest
- name: Run Selenium Tests
run: mvn test -Dbrowser=chrome -Dheadless=true
- name: Upload Test Reports
if: always()
uses: actions/upload-artifact@v3
with: { name: test-reports, path: reports/ }
Matrix strategy for cross-browser
strategy: { matrix: { browser: [chrome, firefox] } }
run: mvn test -Dbrowser=${{ matrix.browser }}
Selenium Common Issues & Troubleshooting
17. What are the most common Selenium exceptions and how do you handle them?
Understanding exceptions is critical for building robust automation.
18. How do you handle StaleElementReferenceException?
StaleElementReference is one of the most common issues in dynamic web applications.
CAUSE: Element reference becomes stale when DOM is rebuilt after: AJAX reload, page refresh, navigation, JavaScript rendering
SOLUTION 1 — Re-find element on use
- Do NOT store element in variable if page changes between finding and using it
Instead: driver.findElement(locator).click(); // Find and use in one line
SOLUTION 2 — Try-catch with retry
for(int i=0; i<3; i++) {
try { driver.findElement(locator).click(); break; }
catch(StaleElementReferenceException e) { Thread.sleep(500); }
}
SOLUTION 3 — Wait for staleness then re-find
wait.until(ExpectedConditions.stalenessOf(oldElement));
WebElement freshElement = driver.findElement(locator);
SOLUTION 4 — Page Object best practice
- Do not store @FindBy fields outside page object methods — always access fresh from page object
19. What are flaky tests and how do you systematically eliminate them in Selenium?
Flaky tests are non-deterministic — pass sometimes, fail sometimes. They destroy CI/CD confidence.
COMMON CAUSES OF FLAKINESS IN SELENIUM
- Timing issues: Element not ready when script tries to interact — fix with explicit waits
- Hardcoded waits: Thread.sleep() — environment-dependent; remove all of them
- Test order dependency: Test B passes only if Test A ran first — make each test independent
- Shared test data: Tests modifying same data simultaneously in parallel — use unique data per test
- Environment instability: Network blips, slow CI machines — retry logic handles this
- Animation/transition: Element is visible but still animating — wait until animation ends
- Stale elements: Page refreshes between find and interact — re-find elements
SYSTEMATIC APPROACH
- 1. Run failing test 10 times — identify failure rate
- 2. Add detailed logging to each step
- 3. Capture screenshot at failure point
- 4. Review root cause category (timing/data/locator/environment)
- 5. Apply targeted fix
- 6. Run 10 times again to confirm fix
- 7. Add to monitoring — alert if flakiness returns
Cucumber + Selenium Integration
20. How do you integrate Cucumber BDD with Selenium WebDriver? Show a complete working example.
Cucumber BDD allows writing tests in plain English (Gherkin). Selenium executes the steps. Together they provide readable, business-friendly automation.
MAVEN DEPENDENCIES
<dependency><groupId>io.cucumber</groupId><artifactId>cucumber-java</artifactId><version>7.15.0</version></dependency>
<dependency><groupId>io.cucumber</groupId><artifactId>cucumber-testng</artifactId><version>7.15.0</version></dependency>
<dependency><groupId>io.cucumber</groupId><artifactId>cucumber-picocontainer</artifactId><version>7.15.0</version></dependency>
- FEATURE FILE — src/test/resources/features/Login.feature:
Feature: User Login
Scenario Outline: Login with valid and invalid credentials
Given user is on the login page
When user enters '<email>' and '<password>'
Then user should see '<message>'
Examples:
| email | password | message |
| admin@test.com | Admin@123 | Dashboard |
| wrong@test.com | wrongPass | Invalid |
STEP DEFINITIONS — src/test/java/steps/LoginSteps.java
public class LoginSteps {
private WebDriver driver;
private LoginPage loginPage;
public LoginSteps(DriverFactory factory) {
this.driver = factory.getDriver(); // shared via PicoContainer DI
this.loginPage = new LoginPage(driver);
}
@Given("user is on the login page")
public void navigateToLogin() {
driver.get(ConfigReader.getBaseUrl() + "/login");
}
@When("user enters {string} and {string}")
public void enterCredentials(String email, String pass) {
loginPage.enterEmail(email);
loginPage.enterPassword(pass);
loginPage.clickLogin();
}
@Then("user should see {string}")
public void verifyResult(String expected) {
Assert.assertTrue(driver.getTitle().contains(expected)
|| driver.getPageSource().contains(expected));
}
}
DRIVER FACTORY for PicoContainer DI
public class DriverFactory {
private WebDriver driver;
@Before public void setUp() {
driver = new ChromeDriver(); driver.manage().window().maximize();
}
@After public void tearDown() { if(driver!=null) driver.quit(); }
public WebDriver getDriver() { return driver; }
}
- TEST RUNNER — src/test/java/runners/TestRunner.java:
@CucumberOptions(
features = "src/test/resources/features",
glue = {"steps", "hooks"},
plugin = {"pretty", "html:target/cucumber-report.html",
"json:target/cucumber.json"},
tags = "@smoke" // run only @smoke tagged scenarios
)
public class TestRunner extends AbstractTestNGCucumberTests {
@Override @DataProvider(parallel = true)
public Object[][] scenarios() { return super.scenarios(); }
}
REST API + UI Hybrid Testing & DB Validation
21. How do you combine REST API calls with Selenium UI tests? Show a hybrid test example.
Hybrid testing uses APIs for test data setup/teardown and UI for user journey validation — faster, more stable, and more realistic.
PATTERN: API Setup → UI Action → API Verify (or API Cleanup)
- MAVEN DEPENDENCY for REST Assured:
<dependency><groupId>io.rest-assured</groupId>
<artifactId>rest-assured</artifactId><version>5.4.0</version></dependency>
EXAMPLE 1 — API login to skip UI login form (cookie injection)
// Step 1: Get auth token via API
String token = given()
.contentType(ContentType.JSON)
.body("{\"email\":\"admin@test.com\",\"password\":\"Admin@123\"}")
.when().post("/api/auth/login")
.then().statusCode(200)
.extract().path("data.token");
// Step 2: Inject token as cookie into browser (bypass UI login)
driver.get(ConfigReader.getBaseUrl()); // must navigate first before adding cookie
Cookie authCookie = new Cookie("auth_token", token, '/', null, true);
driver.manage().addCookie(authCookie);
driver.navigate().refresh(); // refresh to apply cookie
// Now on dashboard — skipped entire login UI flow!
EXAMPLE 2 — API create test data, then verify via UI
// Step 1: Create product via API
int productId = given().header("Authorization","Bearer " + token)
.contentType(JSON).body("{\"name\":\"Test Product\",\"price\":99.99}")
.when().post("/api/products")
.then().statusCode(201)
.extract().path("data.id");
// Step 2: Verify product appears in UI
driver.get(baseUrl + "/products");
driver.findElement(By.cssSelector("input[placeholder=\"Search\"]")).sendKeys("Test Product");
WebElement product = wait.until(ExpectedConditions.visibilityOfElementLocated(
By.xpath("//td[text()=\"Test Product\"]")));
Assert.assertTrue(product.isDisplayed(), "Product should appear in UI after API creation");
// Step 3: Cleanup via API after test
given().header("Authorization","Bearer "+token)
.when().delete("/api/products/" + productId)
.then().statusCode(204);
EXAMPLE 3 — UI action, then API verify backend state
// UI: Submit order form
orderPage.fillOrderForm("Alice", "123 Main St", "VISA-1234");
orderPage.submitOrder();
String orderId = orderPage.getConfirmationOrderId();
// API: Verify order exists in backend with correct status
given().header("Authorization","Bearer " + token)
.when().get("/api/orders/" + orderId)
.then().statusCode(200)
.body("data.status", equalTo("CONFIRMED"))
.body("data.customerName", equalTo("Alice"));
22. How do you perform database validation in a Selenium test? Show a complete JDBC example.
Database testing after UI actions verifies data persistence — ensuring the UI correctly saves data to the backend database.
MAVEN DEPENDENCY (MySQL):
<dependency><groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId><version>8.0.33</version></dependency>
DB UTILITY
public class DatabaseUtil {
private static Connection connection;
public static void connect() throws SQLException {
String url = System.getProperty("db.url", "jdbc:mysql://localhost:3306/testdb");
String user = System.getenv("DB_USER"); // from env variable — safe
String pass = System.getenv("DB_PASSWORD"); // never hardcode credentials!
connection = DriverManager.getConnection(url, user, pass);
}
public static String queryValue(String sql, String column) throws SQLException {
try (PreparedStatement ps = connection.prepareStatement(sql);
ResultSet rs = ps.executeQuery()) {
return rs.next() ? rs.getString(column) : null;
}
}
public static int queryCount(String sql) throws SQLException {
try (PreparedStatement ps = connection.prepareStatement(sql);
ResultSet rs = ps.executeQuery()) {
return rs.next() ? rs.getInt(1) : 0;
}
}
public static void disconnect() throws SQLException {
if (connection != null && !connection.isClosed()) connection.close();
}
}
USE IN TEST — verify registration saved to DB
@Test
public void testUserRegistration() throws SQLException {
// UI: Fill and submit registration form
registrationPage.registerUser("Alice", "alice@test.com", "Alice@123");
Assert.assertTrue(successPage.isSuccessMessageDisplayed());
// DB: Verify user was saved correctly
DatabaseUtil.connect();
String status = DatabaseUtil.queryValue(
"SELECT status FROM users WHERE email = \\"alice@test.com\\"", "status");
Assert.assertEquals(status, "ACTIVE", "User should be ACTIVE in DB");
// DB: Verify no duplicate created
int count = DatabaseUtil.queryCount(
"SELECT COUNT(*) FROM users WHERE email = \\"alice@test.com\\"");
Assert.assertEquals(count, 1, "Exactly 1 user should exist in DB");
// Cleanup test data
DatabaseUtil.queryValue("DELETE FROM users WHERE email = \\"alice@test.com\\"", "id");
DatabaseUtil.disconnect();
}
Sauce Labs & Complete Coverage Summary
23. How do you run Selenium tests on Sauce Labs? How does it differ from BrowserStack?
Sauce Labs is an enterprise cloud testing platform offering real devices and virtual machines across hundreds of OS/browser combinations.
SAUCE LABS SETUP
MutableCapabilities sauceOptions = new MutableCapabilities();
sauceOptions.setCapability("username", System.getenv("SAUCE_USERNAME"));
sauceOptions.setCapability("accessKey", System.getenv("SAUCE_ACCESS_KEY"));
sauceOptions.setCapability("name", "Login Test - Chrome");
sauceOptions.setCapability("build", "Sprint-45-Build-" + System.currentTimeMillis());
sauceOptions.setCapability("browserVersion", "latest");
sauceOptions.setCapability("screenResolution", "1920x1080");
ChromeOptions chromeOptions = new ChromeOptions();
chromeOptions.setCapability("sauce:options", sauceOptions);
chromeOptions.setPlatformName("Windows 11");
chromeOptions.setBrowserVersion("latest");
String sauceUrl = "https://SAUCE_USERNAME:SAUCE_ACCESS_KEY@ondemand.us-west-1.saucelabs.com/wd/hub";
WebDriver driver = new RemoteWebDriver(new URL(sauceUrl), chromeOptions);
MARK TEST RESULT (pass/fail) in Sauce Labs dashboard
((JavascriptExecutor) driver).executeScript("sauce:job-result=passed");
((JavascriptExecutor) driver).executeScript("sauce:job-result=failed");
SAUCE LABS EXCLUSIVE FEATURES
sauce:options capabilities for custom tunnel, extended debugging, video
Extended Debugging: HAR capture, JS console logs, network logs
Sauce Connect Tunnel: test apps behind firewall (private networks)
Virtual USB: direct connection to real device for deep debugging
- BROWSERSTACK vs SAUCE LABS COMPARISON:
| Real Devices | thousands of real devices | thousands of real devices |
| Virtual Machines | Yes | Yes (more VM options) |
| Tunnel / Local Testing | BrowserStack Local | Sauce Connect Tunnel |
| Extended Debugging | Basic | Advanced — HAR, JS logs, network |
| Pricing Model | Per minute usage | Per concurrency / VM minute |
| Dashboard | Clean, simple UI | More detailed logs and history |
| Appium Support | Yes | Yes |
| Selenium Version Control | Managed by BS | More control over versions |
| Best For | Quick setup, large device matrix | Enterprise, detailed debugging, compliance |
Quick-Fire Questions
Short answers to revise the night before.
24. What is CI/CD?
Continuous Integration (auto-build/test on every commit) and Continuous Delivery (auto-deploy after tests pass). Ensures fast, reliable releases.
25. What is Jenkins?
Open-source CI/CD automation server. Runs pipelines that build, test, and deploy applications. Widely used in enterprise projects.
26. What is a Jenkinsfile?
A text file stored in source control that defines the CI/CD pipeline as code. Uses declarative or scripted pipeline syntax.
27. What is GitHub Actions?
CI/CD service built into GitHub. Triggers automated workflows (build, test, deploy) on events like push or pull request.
28. How do you run Selenium tests in Jenkins?
Create a Pipeline job, write a Jenkinsfile with stages for checkout/build/test, use mvn test to run TestNG suite, publish results with plugins.
29. What is Docker?
Containerization platform. Packages applications and dependencies into isolated containers that run the same everywhere.
30. What is a Docker image vs Docker container?
Image is a read-only blueprint (like a class). Container is a running instance of an image (like an object).
31. What is Maven Surefire Plugin?
Maven plugin that runs unit/integration tests. Configured to run TestNG suites. Generates XML test reports in target/surefire-reports/.
32. How do you pass parameters to tests from the command line?
Use -D flag with Maven: mvn test -Dbrowser=firefox -DsuiteXmlFile=smoke.xml. Access in Java with System.getProperty("browser").
33. What is a build artifact in CI/CD?
Output of a build step saved for later stages or download. In Selenium: test reports, screenshots, logs saved after test run.
34. What does 'fail fast' mean in CI/CD?
Stop the pipeline immediately when any critical test fails, rather than running all tests. Saves time and resources.
35. How do you run tests only on pull requests?
In GitHub Actions: use 'on: pull_request: branches: [main]'. In Jenkins: use GitHub plugin with webhook trigger on PR events.
36. What is a nightly build/test run?
Scheduled test execution that runs automatically every night (using cron). Catches regressions introduced during the day's development.
37. What design patterns do you use in Selenium frameworks?
Page Object Model (separation of concerns), Singleton (ExtentManager, ConfigReader), Factory (DriverFactory), Facade (BasePage), Strategy (browser selection).
38. What is the Singleton design pattern?
Restricts instantiation of a class to ONE object. Used in ExtentManager and ConfigReader to ensure a single shared instance across all tests.
39. How do you handle flaky tests?
Identify root cause (timing/network/data issues), fix with explicit waits, use RetryAnalyzer for genuinely unstable tests, add proper test data cleanup.
40. What is RetryAnalyzer in TestNG?
Implements IRetryAnalyzer interface to automatically re-run failed tests up to a configurable number of times before marking them as failed.
41. What is ITestListener in TestNG?
Interface with callbacks for test events (start, pass, fail, skip). Used to integrate ExtentReports, capture screenshots, and log test execution.
42. What is RestAssured?
Java library for API testing. Provides BDD-style (given/when/then) fluent API for making HTTP requests and validating responses.
43. What is BrowserStack?
Cloud testing platform providing real browsers on real devices. Tests run on their infrastructure — no local browser setup needed.
44. What is Appium?
Mobile test automation framework built on WebDriver protocol. Automates native, hybrid, and mobile web apps on Android and iOS.
45. What is ThreadLocal and why is it important?
ThreadLocal stores a separate value per thread. In parallel test execution, ThreadLocal<WebDriver> ensures each thread has its own browser session.
46. How would you structure a framework for a large team?
Separate base/pages/utils/tests packages, shared BasePage and BaseTest, centralized config and driver management, CI/CD pipeline, code review process for page classes and tests.
47. What is parallel execution at the methods vs class vs tests level?
methods: all @Test methods run in parallel. classes: all classes run in parallel. tests: all <test> tags in testng.xml run in parallel.
48. How do you handle test data cleanup?
Use @AfterMethod to delete created test data. Use unique identifiers (timestamp) for test data to prevent conflicts. Use API calls for cleanup (faster than UI).
49. What is the difference between smoke testing and regression testing?
Smoke: quick sanity check of critical paths (login, checkout) — runs in minutes. Regression: full test suite checking all features — runs in hours. Both are automated.
50. How do you report test results to stakeholders?
Generate Extent HTML reports in CI/CD pipeline, publish as build artifacts in Jenkins/GitHub Actions, send email notifications with report link on failures, integrate with TestOps tools like Jira Xray.
How to Prepare with 5 Years of Experience
- Bring numbers: suite size, run time before and after your changes, flakiness rate, defects caught in CI.
- Be ready to design a framework or a CI pipeline on a whiteboard and defend the trade-offs.
- Know when you would not use Selenium, and how Playwright compares; see Selenium vs Playwright.
- Pair this with the SDET interview preparation guide for 3–5 years.