QA Interview Hub · Knowledge base · Quizzes · Українська
19 Selenium + Java questions that come up in QA interviews, with short answers. Open the topic in the knowledge base for a deeper explanation.
The client library (selenium-java) → the W3C WebDriver protocol (HTTP + JSON, request-response) → the browser driver (chromedriver, geckodriver, msedgedriver) → the browser. All of it is one session: new ChromeDriver() creates it, quit() ends it and stops the driver; close() only closes the current window. Selenium 4 speaks only W3C: JSON Wire and Selenium RC are history.
driver.findElement(By.id("email")) returns a WebElement by a By locator (id, name, cssSelector, xpath, linkText). On it I perform actions: click() to click, sendKeys("text") to type text, clear() to empty the field, getText() for the visible text, getAttribute("value") for an attribute or property value, isDisplayed() to check visibility. Example: driver.findElement(By.id("email")).sendKeys("a@b.com"); driver.findElement(By.cssSelector("button[type=submit]")).click();. On dynamic pages I use explicit waits with WebDriverWait before the action, not Thread.sleep. A found element can go stale after a DOM update (StaleElementReferenceException).
findElement returns the first matching element and throws NoSuchElementException when there is none. findElements returns a List<WebElement> of all matches and, if it finds nothing, returns an empty list with no exception. That makes findElements handy for checking absence: driver.findElements(By.id("error")).isEmpty(), and for working with collections such as table rows. Keep in mind that with an implicit wait findElements also waits the whole timeout before returning an empty list. Found elements are not refreshed, so after a DOM change I look them up again.
First a test attribute (data-testid) or a stable id, then a meaningful CSS, XPath only when CSS is not enough. XPath can search by text and go up to a parent or ancestor; CSS cannot search by text and picks a parent only via :has(); speed is no argument in modern browsers. Avoid absolute paths, indexes and generated classes. findElement throws NoSuchElementException, findElements returns an empty list.
Implicit: a global element lookup timeout (0 by default), waits only for presence in the DOM. Explicit (WebDriverWait + ExpectedConditions or a lambda): waits for a specific condition, otherwise TimeoutException. FluentWait adds a polling interval and exceptions to ignore. Do not mix implicit with explicit: the time becomes unpredictable. Do not use Thread.sleep: it waits for time, not for a state.
A WebElement is a reference to a node in the current DOM; when the page re-renders it, the reference goes stale and any action throws the exception. Avoid it: keep the By instead of the WebElement and look up before acting; wait for a stable state (refreshed, stalenessOf) or a FluentWait that ignores the exception. Do not hide it with an arbitrary sleep in try/catch.
The first: another element took the click (a spinner, a modal, a sticky header): wait for the overlay to disappear (invisibilityOfElementLocated) or scroll the element into view. The second: the element is in the DOM but cannot be used (hidden, zero size): wait for elementToBeClickable or find why it is hidden. A click through JavascriptExecutor bypasses the problem, but a user cannot do that, so it is a last resort.
A class describes a page or part of it: locators and interaction details inside, the test sees only service methods (loginAs, addToCart). A method that leads to another page returns its Page Object. Assertions go in tests, not in the Page Object (the exception: a check in the constructor that the right page is open). Do not expose WebDriver and raw WebElements. Extract repeated blocks into components.
A Selenium class: fields with @FindBy are initialised by PageFactory.initElements(driver, this) as proxies that look the element up on every access (with @CacheLookup once, which can go stale). Downsides: a forgotten initElements gives NullPointerException, a locator is hard to parameterise, reflection complicates debugging; the documentation mentions it only in a legacy section. The alternative: By fields and explicit lookup methods with waits.
A component is a class for a repeated part of the UI (a header, a menu, a modal, a table row) that looks elements up inside its own root WebElement; it is embedded in different pages without duplication. Fluent style: a method returns this or the next page, so the scenario reads as a chain (open().loginAs(u, p).openCart()). Long chains are hard to debug, so break them with variables where checks are needed.
WebDriver is not thread-safe: you need one driver per test. Do not use a static WebDriver in BasePage (threads overwrite one reference). Create the driver in @BeforeEach or @BeforeMethod and pass it to the Page Object constructor, or keep it in a ThreadLocal<WebDriver> and call remove() after the test. In JUnit 5 it is convenient to make the driver an extension with a ParameterResolver.
Setup: @BeforeEach/@AfterEach (JUnit) versus @BeforeMethod/@AfterMethod (TestNG); @BeforeAll versus @BeforeClass. Data: @ParameterizedTest (@CsvSource, @MethodSource) versus @DataProvider. Groups: @Tag versus groups and testng.xml. Dependencies between tests exist only in TestNG, and are discouraged. Extension: the Extension API versus listeners (ITestListener, IRetryAnalyzer). Parallelism: junit-platform.properties versus the parallel and thread-count attributes. New projects more often pick JUnit Jupiter (JUnit 5, now JUnit 6 with the same API).
Modes: Standalone (everything in one process), Hub and Node, Distributed. Components: Router (accepts requests), Distributor (finds a free slot), Session Map (which session is on which Node), New Session Queue (a queue when there are no slots), Node (runs browsers), Event Bus. A test connects through RemoteWebDriver to one URL (port 4444 by default); the state is at /status, the UI at /ui.
Images selenium/standalone-chrome (and firefox) or hub + node-chrome: docker run -p 4444:4444 -p 7900:7900 --shm-size="2g" ... You need --shm-size (or /dev/shm), otherwise Chrome crashes on heavy pages. Port 7900 is a session view through noVNC for debugging. By default a container runs one session (SE_NODE_MAX_SESSIONS); the variable allows more, but resources set the limit. In CI Grid is started as a service and /status is awaited. Uploading files to a remote machine needs a LocalFileDetector.
One WebDriver per thread (a ThreadLocal or a driver per test), no static driver; data isolation (accounts, records, files are not shared); independence from execution order; the thread count matched to the resources of Grid or the runner. Enabling: junit.jupiter.execution.parallel.enabled=true and mode.default=concurrent (JUnit 5), parallel and thread-count in testng.xml (TestNG). Mark retried failures as flaky.
Causes: wrong waits (sleep, a click before readiness), dependencies between tests and shared data, unstable locators, a slow or limited environment (CI, container memory), external services, animations and overlays. Diagnosis: run the test in a loop 20-50 times, compare failed and passed runs by screenshot, DOM, logs, step timing. Only then fix the cause; a retry without a flaky mark hides defects.
A screenshot ((TakesScreenshot) driver).getScreenshotAs, the URL, the page source, browser and server logs, a video on Grid. Automatically: JUnit 5 with an extension using TestWatcher.testFailed, TestNG with ITestListener.onTestFailure; the driver must still be open at that moment, and TestWatcher runs after @AfterEach, so quit() goes in the same extension after the screenshot. Allure (allure-jupiter, formerly allure-junit5, or allure-testng): @Step, Allure.addAttachment, results in allure-results, the report via allure generate; history shows unstable tests.
iframe: switchTo().frame(...), back with parentFrame() or defaultContent(); frameToBeAvailableAndSwitchToIt combines waiting and switching. Windows: remember the handle, wait for numberOfWindowsToBe, switchTo().window(new one); switchTo().newWindow(WindowType.TAB) opens a tab; after close() switch back to the needed window. Upload: sendKeys with an absolute path into input type=file; on Grid add a LocalFileDetector.
For complex gestures: hover (moveToElement), drag and drop (dragAndDrop), double and context click, key combinations (keyDown, keyUp), scrolling (scrollToElement). The method chain ends with perform(); without it nothing runs. For hover menus a short pause or a wait for the submenu to appear is sometimes needed. Do not confuse it with Select, which is only for the select element.