Selenium Junior cheat sheet: interview answers
Every question of this level with its correct answer and explanation, on one page for a quick review before the interview.
1. What is Selenium WebDriver?
Correct answer: A library that drives real browsers through a standard protocol
WebDriver sends commands to a browser driver (chromedriver, geckodriver) using the W3C WebDriver protocol. Test runners like JUnit or TestNG run the tests.
2. What does a browser driver like chromedriver do?
Correct answer: Translates WebDriver commands into actions in that browser
Each browser has its own driver. Selenium sends HTTP requests to it, and the driver controls the browser.
3. What does Selenium Manager (Selenium 4.6+) solve?
Correct answer: It finds or downloads the right driver for the browser automatically
You no longer need to download chromedriver by hand or use a separate WebDriverManager library in most cases.
4. How do you open a page in Selenium Java?
Correct answer:
driver.get("https://example.com")get waits for the page load event by default. navigate().to() does the same and keeps history methods like back().
5. What does
driver.quit()do compared todriver.close()?Correct answer: quit ends the whole session; close shuts only the current window
Call quit in teardown, or browser and driver processes stay alive and pile up on CI agents.
6. Which locator is usually the most stable choice?
Correct answer: A unique id or a dedicated test attribute like data-testid
Absolute paths and positions break with every layout change. Ask developers for stable test ids.
7. What does
By.cssSelector("button.primary")find?Correct answer: Button elements that have the class primary
CSS selectors are fast and readable. Use XPath when you need text or upward navigation.
8. What can XPath do that CSS selectors can't?
Correct answer: Find elements by their text and go up to parents
//button[text()='Save'] or //span/.. are XPath-only. Keep XPaths short and relative.
9. What's wrong with this XPath?
/html/body/div[2]/div/form/div[3]/buttonCorrect answer: It's absolute and breaks on any layout change
Prefer a relative locator tied to meaning, e.g. //form[@id='login']//button[@type='submit'].
10. What's the difference between
findElementandfindElements?Correct answer: findElement throws if nothing matches; findElements returns an empty list
findElements is handy for checking that something is absent, without a try/catch.
11. What does
element.sendKeys("text")do?Correct answer: Types the text into the element, like a user would
It fires key events. Call clear() first if the field may already contain text.
12. What does
element.getText()return?Correct answer: The visible text of the element
For inputs, the typed value is in getAttribute("value") or getDomProperty("value"), not getText().
13. What is an implicit wait?
Correct answer: A global timeout for every findElement call to retry finding elements
Set once on the driver. Mixing implicit and explicit waits can cause unpredictable delays.
14. What is an explicit wait?
new WebDriverWait(driver, Duration.ofSeconds(10)) .until(ExpectedConditions.elementToBeClickable(By.id("save")));Correct answer: Waiting for a specific condition with a timeout
Explicit waits poll a condition and return as soon as it's true. Much better than Thread.sleep.
15. Why is
Thread.sleep(3000)a bad wait in Selenium tests?Correct answer: It wastes time when fast and fails when the app is slower
Fixed sleeps make suites slow and flaky. Wait for the condition you actually need.
16. What does
NoSuchElementExceptionmean?Correct answer: The locator matched no element at that moment
Often the element hasn't loaded yet or the locator is wrong, or it's inside an iframe.
17. What does
StaleElementReferenceExceptionmean?Correct answer: The element was removed or re-rendered after you found it
Find the element again after the page or component re-renders, e.g. after an AJAX update.
18. What does
ElementClickInterceptedExceptionusually mean?Correct answer: Another element, like an overlay, would receive the click
Wait for loaders or cookie banners to go away, or scroll the element into view.
19. How do you work with an element inside an iframe?
Correct answer: Switch into the frame first with
driver.switchTo().frame(...)Switch back with defaultContent() when done, or later lookups will fail.
20. How do you switch to a new tab that the app opened?
Correct answer: Get the window handles and switch to the new one
Store the original handle first, then switchTo().window(handle). Selenium 4 also has newWindow(WindowType.TAB).
21. How do you accept a JavaScript
alert?Correct answer:
driver.switchTo().alert().accept()Alerts aren't part of the DOM. dismiss() cancels, getText() reads the message.
22. How do you pick an option in a
<select>element?Correct answer: Wrap it in
Selectand call selectByVisibleTextSelect also has selectByValue and selectByIndex. Custom dropdowns built from divs need normal clicks.
23. What is the Actions API used for?
Correct answer: Complex input: hover, drag and drop, key combos
new Actions(driver).moveToElement(menu).click(item).perform(). Don't forget perform().
24. What is the Page Object pattern?
Correct answer: A class per page that hides locators behind meaningful methods
Tests call loginPage.loginAs(user) instead of repeating locators. A UI change is fixed in one place.
25. Should page objects contain assertions?
Correct answer: Usually not: they expose state, and tests do the asserting
Keeping checks in tests makes page objects reusable for different scenarios.
26. How do you run Chrome without a visible window?
Correct answer: Add the
--headless=newargument to ChromeOptionsHeadless is common in CI. Some layout or file-download behavior differs, so check both modes.
27. What does
driver.manage().window().setSize(...)help test?Correct answer: Responsive layouts at a specific screen size
Set a fixed size in CI so headless runs don't use a tiny default window.
28. How do you take a screenshot in Selenium Java?
Correct answer: Cast the driver to TakesScreenshot and call getScreenshotAs
Take screenshots on failure in a listener or extension and attach them to the report.
29. What is Selenium Grid?
Correct answer: Running tests on remote browsers and machines in parallel
Tests use RemoteWebDriver with the Grid URL; the hub routes sessions to nodes with the requested browser.
30. What is
RemoteWebDriverused for?Correct answer: Connecting to a browser on Grid or a cloud provider
Capabilities choose the browser and platform. The test code is otherwise the same.
31. What does
JavascriptExecutor.executeScriptlet you do?Correct answer: Run JavaScript in the page, e.g. scroll or read state
Useful as a last resort. Clicking via JS skips real user checks like visibility and overlays.
32. Why is clicking with JavaScript instead of
click()risky in tests?Correct answer: It skips checks a real user faces, like overlays and visibility
A JS click can pass while users can't click the button. Fix the wait or the overlay instead.
33. What does
isDisplayed()check?Correct answer: Whether the element is visible on the page
isEnabled checks enabled state, isSelected checks checkboxes and options.
34. What is a relative locator in Selenium 4?
driver.findElement(RelativeLocator.with(By.tagName("input")).below(By.id("email")));Correct answer: Finding an element by its position relative to another
Options include above, below, toLeftOf, toRightOf and near. Handy when ids are missing, but layout-dependent.
35. How do you read a cookie in Selenium?
Correct answer:
driver.manage().getCookieNamed("session")addCookie can set a session cookie to skip the login UI in tests, after opening the domain.
36. Why can adding a session cookie speed up UI tests?
Correct answer: Tests skip the login form and start signed in
Test the login form in a few dedicated tests; use API or cookie login for the rest.
37. What is a flaky test?
Correct answer: A test that passes or fails at random without code changes
Common causes: missing waits, shared data, test order, animations and environment instability.
38. Where should test data like users come from in UI tests?
Correct answer: Created per test, ideally through an API or fixtures
Shared accounts cause collisions in parallel runs. Fresh data keeps tests independent.
39. What do TestNG and JUnit add to a Selenium project?
Correct answer: Test structure, setup and teardown, assertions, reports
Selenium only drives the browser. The test framework organizes and runs tests.
40. What is the right place to start and stop the browser in tests?
Correct answer: Setup and teardown hooks like @BeforeEach and @AfterEach
A fresh browser per test or class keeps state isolated; always quit in teardown, even on failure.
41. What does
driver.getTitle()return?Correct answer: The text of the page's <title> element
getCurrentUrl() returns the URL. Both are quick checks that navigation worked.
42. How do you go back in browser history?
Correct answer:
driver.navigate().back()navigate() also has forward() and refresh().
43. Why do tests fail when an element is inside a shadow DOM?
Correct answer: Normal locators can't see inside; use getShadowRoot first
In Selenium 4, element.getShadowRoot().findElement(By.cssSelector(...)) reaches inside open shadow roots.
44. What does
ExpectedConditions.visibilityOfElementLocatedwait for?Correct answer: The element is in the DOM and visible
presenceOfElementLocated only needs the DOM. Pick the condition that matches what you'll do next.
45. Why should locators not depend on visible text in multi-language apps?
Correct answer: The text changes with the language and breaks the locator
Use ids or test attributes. Assert texts separately per locale if needed.
46. What does Selenide add on top of Selenium?
Correct answer: Concise API with built-in smart waits and automatic screenshots
$("#save").shouldBe(visible).click() waits automatically. It still uses WebDriver underneath.
47. What is Allure used for in Selenium projects?
Correct answer: Readable test reports with steps, screenshots and history
Allure integrates with JUnit and TestNG and shows attachments, steps and trends.
48. What does Cucumber with Gherkin give a Selenium project?
Correct answer: Scenarios in plain language mapped to step code
Given/When/Then helps when non-developers read scenarios. Without that, it can add overhead.
49. What should a test do after a failing assertion in teardown?
Correct answer: Still quit the browser so the next test starts clean
Put quit in @AfterEach or a finally block so it runs even when tests fail.
50. How do you check that an element is NOT on the page without waiting a long time?
Correct answer: Use findElements and check it's empty, with short waits
With a long implicit wait, findElements also waits the full timeout before returning empty.
51. What does
clear()do on an input field?Correct answer: Removes the current value of the field
Some frameworks don't fire change events on clear; selecting all and deleting may be needed.
52. Why do tests need a fixed window size in CI?
Correct answer: Layouts change with size, and headless defaults can be tiny
A menu may collapse into a burger icon on small widths, hiding the elements tests expect.
53. What does
submit()do on a form element?Correct answer: Submits the form the element belongs to
Clicking the real submit button is closer to user behavior and runs click handlers.
54. What does the W3C WebDriver standard mean for Selenium?
Correct answer: Browsers implement one common protocol for Selenium
Selenium 4 uses the W3C protocol by default, which made behavior more consistent across browsers.
55. How do you upload a file through an
<input type="file">?Correct answer: Send the file's absolute path with sendKeys
OS dialogs are outside the browser. On Grid, a LocalFileDetector sends the file to the node.
56. Why should tests avoid
driver.manage().timeouts().implicitlyWaitwith a long value and explicit waits together?Correct answer: The waits can add up and cause unpredictable delays
Selenium's docs advise not mixing them. Many teams use explicit waits only.
57. What does
getAttribute("href")return on a link?Correct answer: The link's URL
In Selenium 4, getDomAttribute and getDomProperty make the distinction between HTML attribute and DOM property explicit.
58. What is a good assertion after clicking 'Save'?
Correct answer: A visible confirmation or the saved data appears
A click without error says nothing about the result. Check what the user would see.
59. What does
driver.switchTo().defaultContent()do?Correct answer: Returns from an iframe to the main page
parentFrame() moves up one level in nested iframes.
60. Why keep locators in page objects and not in test methods?
Correct answer: One place to update when the UI changes
Tests read as user stories, and refactoring the UI touches only page objects.
61. What is the Screenplay pattern?
Correct answer: Actors perform tasks and questions instead of page methods
It scales better than page objects for large suites, at the cost of more structure.
62. What happens if two tests share one browser session in parallel?
Correct answer: They interfere with each other's pages and state
Give each parallel test its own driver, e.g. per thread.
63. How can tests check a page in Firefox as well as Chrome?
Correct answer: Create the driver from config: ChromeDriver or FirefoxDriver
A driver factory reads the browser from a property, so the same tests run across browsers.
64. What does
Keys.ENTERinsendKeys(Keys.ENTER)do?Correct answer: Presses the Enter key in the element
Keys also has TAB, ESCAPE, arrow keys and modifiers for chords via Actions.
65. What is a good reason to keep UI tests few and focused?
Correct answer: They're slow and brittle; most logic is cheaper below the UI
Test pyramid: many unit and API tests, fewer UI tests for key user flows.
66. What does
getCssValue("color")return?Correct answer: The computed CSS value of that property
Values come in browser format, e.g. rgba(0, 0, 0, 1). Normalize before comparing.
67. How do you hover over a menu to open it?
Correct answer:
new Actions(driver).moveToElement(menu).perform()After hovering, wait for the submenu before clicking.
68. Why log the browser console in UI test failures?
Correct answer: JavaScript errors often explain why the UI didn't work
Selenium 4 BiDi and driver logs can capture console errors and attach them to reports.
69. What is the benefit of
data-testid-style attributes?Correct answer: They don't change with styling or text and exist for tests
Agree on them with developers. CSS classes change with redesigns, test ids don't.
70. What does
driver.getPageSource()return?Correct answer: The current HTML of the page as the browser sees it
It reflects the current DOM. Saving it on failure helps debugging.
71. What is a common cause of
TimeoutExceptionin explicit waits?Correct answer: The condition never became true within the time limit
Check the locator and the expected state first, then whether the app is actually slower.
72. What is the main purpose of the
Byclass?Correct answer: To describe how to locate an element
By.id, By.name, By.cssSelector, By.xpath and others create locator strategies.
73. What does
driver.navigate().refresh()do?Correct answer: Reloads the current page
Refreshing loses unsaved form data, a good check for 'are you sure you want to leave?' prompts.
74. What does
By.linkText("Sign in")find?Correct answer: A link whose full visible text is Sign in
partialLinkText matches part of the text. Text-based locators break with translations.
75. Why should each UI test be independent of the others?
Correct answer: Any test can then run alone, in any order or in parallel
Tests that rely on earlier ones fail in chains and can't be parallelized or rerun alone.