A4Q Selenium Tester Mock Exam #4 — Questions & Answers
Every question in this mock exam, with the correct answer marked and a written rationale behind each option below — for reading and review, not a timed run.
Which statement about the WebDriver method driver.get(String url) is correct?
It loads the page and waits for it to fully load by default.
get() waits until the page load is complete before returning control.
It opens the URL in a new browser tab.
get() reuses the current window; it does not open a new tab.
It returns the page title as a String.
get() returns void; getTitle() returns the title.
It never waits and returns immediately after sending the request.
By default get() is blocking, unlike a fire-and-forget request.
get() navigates to a URL and, by default, blocks until the document readyState is 'complete'.
What is the difference between driver.getWindowHandle() and driver.getWindowHandles()?
getWindowHandle() returns a single current handle; getWindowHandles() returns a Set of all handles.
Correct: singular returns one String, plural returns Set<String>.
Both return a List of handles ordered by open time.
Neither returns a List; the plural returns an unordered Set.
getWindowHandle() closes the window; getWindowHandles() lists them.
getWindowHandle() does not close anything.
There is no difference; they are aliases.
They return different types and meanings.
getWindowHandle() returns the current window's handle (a String); getWindowHandles() returns a Set of all open window/tab handles.
A test clicks a link that opens a second browser tab containing a payment form. Before the click the test stored the original handle with String main = driver.getWindowHandle();. After the click the test must interact with the form in the new tab, complete it, close that tab, and return control to the original page. Which sequence of WebDriver calls correctly performs this switch and cleanup?
Loop over getWindowHandles(), switchTo().window(h) for the handle != main, fill the form, driver.close(), then switchTo().window(main).
Correct: switch to the new tab, act, close it, and explicitly switch back to the stored handle.
Just call driver.switchTo().frame(1) to reach the new tab, fill it, then driver.quit().
frame() switches iframes, not tabs; quit() would end the whole session.
Fill the form directly — WebDriver auto-focuses the newest tab, so no switch is needed.
WebDriver does NOT auto-switch focus to new windows; you must switchTo() explicitly.
Use driver.navigate().forward() to move into the new tab and back() to return.
navigate() controls history within one window, not switching between tabs.
You iterate the handle Set, switch to the one that is not the original, do the work, close the new tab, then switch back to the stored main handle.
When no matching element exists on the page, how do findElement() and findElements() behave?
findElement() throws NoSuchElementException; findElements() returns an empty list.
This is the defined contract of the two methods.
Both return null.
findElement() throws rather than returning null; findElements() returns an empty list.
Both throw NoSuchElementException.
findElements() never throws for no match; it returns an empty list.
findElement() returns an empty list; findElements() throws.
This reverses the actual behaviour.
findElement() throws NoSuchElementException; findElements() returns an empty list.
Which of the following are legitimate responsibilities of the Selenium WebDriver API? (Choose two.)
Driving a real browser through its native automation support.
Core purpose of WebDriver.
Locating elements and simulating user interactions with them.
WebDriver finds elements and clicks/types on them.
Providing assertion methods to verify expected results.
Assertions come from the test framework (JUnit/TestNG/pytest), not WebDriver.
Scheduling and running the test suite in parallel.
Execution/scheduling is handled by the test runner and Grid, not the WebDriver API.
WebDriver drives a real browser via its native automation support and locates/interacts with elements. It is not a test runner and does not include assertions.
You must hover over a menu item to reveal a submenu, then click a link inside that submenu that only appears while hovering. A plain click on the submenu link fails because it is not visible until the hover happens. Which Selenium approach reliably performs a hover-then-click as a single user gesture?
new Actions(driver).moveToElement(menu).click(submenuLink).perform();
Actions chains a mouse move then click into one gesture executed by perform().
submenuLink.click(); called twice in a row.
Repeating a click does not create the hover state that reveals the link.
driver.navigate().refresh(); then submenuLink.click();
Refreshing does not hover the menu; the link stays hidden.
menu.sendKeys(Keys.ENTER); then submenuLink.click();
Sending ENTER to the menu is not a hover and may not open the CSS :hover submenu.
The Actions class builds a composite gesture: moveToElement(menu) then click(submenuLink), finalized with perform().
What is the difference between driver.close() and driver.quit()?
close() closes the current window; quit() closes all windows and ends the session.
This is the precise distinction between the two methods.
They are identical.
They differ in scope: one window vs whole session.
close() ends the whole session; quit() closes one window.
This reverses the real behaviour.
Both keep the driver process running for reuse.
quit() terminates the driver process; it is not reusable afterwards.
close() closes the current window; quit() closes all windows and ends the WebDriver session, freeing the driver process.
Which WebElement method should be used to clear an existing value from a text input before typing a new one?
clear()
clear() removes the current content of an editable input or textarea.
reset()
There is no reset() on WebElement.
delete()
There is no delete() method.
submit()
submit() submits the form; it does not clear the field.
clear() empties the field; sendKeys() then types the new value.
Which By strategy is generally the fastest and most robust when an element carries a unique, stable id attribute?
By.id
An id is unique per page and resolves quickly.
By.xpath with an absolute path
Absolute XPath is brittle and slow, breaking on layout changes.
By.linkText
linkText only works on anchor text, not general elements with an id.
By.tagName
tagName matches many elements and is not unique.
By.id targets the id attribute directly and is the preferred locator when a stable unique id exists.
Given the markup: <div class="card"><button class="btn btn-primary submit-order" data-test="place-order">Place order</button></div> — the class values change between releases but the data-test attribute is stable. Which locator best targets this button in a maintainable way?
By.cssSelector("button[data-test='place-order']")
Targets the stable custom attribute, unaffected by class changes.
By.className("btn btn-primary submit-order")
className accepts only a single class name, and these classes change between releases.
By.cssSelector(".btn-primary")
Depends on a volatile class and may match other buttons.
By.xpath("/html/body/div[1]/div/button")
Absolute path breaks with any structural change.
A CSS attribute selector on the stable data-test attribute is concise and resilient to class churn.
You need an XPath that selects an <a> element by its exact visible text 'Log out'. Which expression is correct?
//a[text()='Log out']
Selects the anchor whose text equals the given string.
//a[@text='Log out']
text is not an attribute; it is a node, so @text is invalid here.
//a=='Log out'
Not valid XPath syntax.
//a(text='Log out')
Not valid XPath syntax.
//a[text()='Log out'] matches anchors whose text node equals 'Log out' exactly.
Which CSS selector matches an input element whose id is exactly 'email'?
input#email
# selects by id in CSS.
input.email
. selects by class, not id.
input=email
Not valid CSS syntax.
input@email
Not valid CSS syntax.
In CSS, # denotes an id, so input#email or #email targets the element with id 'email'.
Which two locator strategies are considered brittle and should generally be avoided when a stable id or data attribute is available? (Choose two.)
Absolute XPath such as /html/body/div[2]/form/input[1]
Any structural change breaks the whole path.
Selectors based on auto-generated class names like css-1a2b3c
Framework-generated hashes change on rebuild, breaking the locator.
By.id on a stable unique id
This is the most robust strategy, not brittle.
A CSS attribute selector on a stable data-test attribute
Data-test attributes are intended for automation and are stable.
Absolute XPath and locators tied to volatile auto-generated class names both break easily on UI changes.
Which XPath axis expression selects a <label> that is the immediate parent of the context node?
parent::label
The parent axis with a node test selects the parent label.
child::label
child selects descendants one level down, not the parent.
following-sibling::label
This selects a sibling, not the parent.
descendant::label
descendant looks downward, not upward to the parent.
.. (or parent::label) moves to the parent; parent::node()/self restrictions can name the tag.
A results table has many rows. You must click the 'Edit' button in the row whose first cell text is 'INV-1042'. The rows share the structure <tr><td>INV-1042</td>...<td><button>Edit</button></td></tr>. Which XPath reliably clicks the correct row's Edit button?
//td[text()='INV-1042']/ancestor::tr//button[text()='Edit']
Anchors on the unique cell text, then scopes the Edit button to that row.
//button[text()='Edit']
Matches every Edit button in the table, not a specific row.
//td[text()='INV-1042']/button
The button is not a direct child of that td; it is in another cell of the row.
//tr[1]//button[text()='Edit']
Hard-codes the first row, ignoring which invoice it is.
You anchor on the td text and navigate to the button within the same row using the ancestor tr.
Which CSS selector matches an element that has BOTH classes 'nav' and 'active'?
.nav.active
No space means both classes must be on the same element.
.nav .active
A space is a descendant combinator: '.active' inside '.nav'.
.nav > .active
> is the direct-child combinator, not 'both classes'.
.nav,.active
A comma is a grouping (OR), matching either class.
Chaining class selectors without a space (.nav.active) requires both classes on the same element.
What is the primary purpose of the Page Object Model (POM) design pattern in Selenium test automation?
To encapsulate a page's locators and interactions so tests are readable and maintenance is centralized.
This is the core benefit: separation of page structure from test logic.
To replace the need for a test framework such as JUnit or TestNG.
POM complements, not replaces, the test framework.
To make the browser run faster by caching pages.
POM is a design pattern; it does not affect browser performance.
To generate test data automatically for each page.
Test data generation is unrelated to POM.
POM encapsulates a page's locators and interactions behind a class, so tests use readable methods and locator changes are made in one place.
A team's LoginPage object exposes a method that types the username and password and clicks submit, then returns a DashboardPage object. A reviewer argues this is good POM practice. Why is returning the next page object from an action method considered a good pattern?
It models the navigation flow and lets tests chain calls fluently and type-safely to the next page.
Correct: the action leads to a new page, so returning it mirrors the real user journey.
Because it lets the page object contain the test assertions.
Assertions belong in tests, not in page objects.
Because it makes the WebDriver instance global and static.
Global static drivers are an anti-pattern, unrelated to returning page objects.
Because it avoids the need for any locators in the page class.
Page objects still hold locators; returning a page does not remove them.
Returning the resulting page object models navigation flow and gives tests a fluent, type-safe chain that reflects the user's journey.
Which two practices are consistent with a well-designed Page Object Model? (Choose two.)
Keep locators private and expose behaviour through intention-revealing methods.
Encapsulation is central to POM.
Each page (or meaningful component) has its own class.
One class per page/component keeps responsibilities clear.
Put the test assertions inside the page object methods.
Assertions belong in the test layer, keeping page objects reusable.
Hard-code Thread.sleep() calls inside every method for stability.
Fixed sleeps are an anti-pattern; explicit waits are preferred.
Page objects should keep locators private and expose intention-revealing methods; they should not contain test assertions.
In a Page Object Model, where should the WebDriver instance typically be provided to a page object?
Injected through the page object's constructor.
Constructor injection is the standard, testable approach.
Created fresh with new inside every method.
Creating a new driver per method would open many browsers and lose session state.
Read from a hard-coded global public static field.
Global static state harms parallelism and testability.
Downloaded from a remote server on each call.
This makes no sense; the driver is a local object reference.
The driver is usually injected into the page object via its constructor, keeping the object testable and free of global state.
A team notices that when a shared header component appears on ten pages, its locators are copied into ten page classes. Which POM refinement removes this duplication?
Extract the header into its own component page object reused by the other pages.
A shared component object centralizes the header's locators and methods.
Copy the locators one more time into a base test class.
This adds another copy rather than removing duplication.
Replace all header locators with absolute XPath.
This changes locator style but keeps the duplication.
Delete the header tests entirely.
Removing coverage is not a valid refactoring.
Extract the header into its own component/page object that the other pages compose or reference, so its locators live in one place.
Which statement best describes the relationship between page objects and test classes?
Tests call page object methods to act, then assert on outcomes themselves.
Clean separation: actions in page objects, assertions in tests.
Page objects call the test classes to run assertions.
Dependency direction is reversed; page objects must not depend on tests.
They are the same class with two names.
They are distinct layers with distinct responsibilities.
There is no interaction; they run independently.
Tests must call page objects to drive the UI.
Test classes call page object methods to perform actions and then assert on the results; the page object hides the how, the test states the what.
How does an implicit wait differ from an explicit wait in Selenium WebDriver?
Implicit applies globally to element lookups; explicit waits for a defined condition on a specific element.
This is the defining distinction between the two wait types.
Implicit waits are more precise than explicit waits.
Explicit waits are the precise, condition-based option.
Explicit waits apply to every command automatically.
That describes an implicit wait, not an explicit one.
There is no difference; both are aliases.
They are genuinely different mechanisms.
An implicit wait applies globally to all findElement calls; an explicit wait (WebDriverWait) waits for a specific condition on a specific element.
A page submits a form via AJAX. After clicking 'Save', a success banner with id 'toast-success' appears about 1–3 seconds later. The test intermittently fails because it checks for the banner immediately. Using an explicit wait, which call best synchronizes the test with the banner's appearance?
wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("toast-success")))
Waits precisely for the banner to become visible, eliminating the race.
Thread.sleep(3000) before checking the banner.
A fixed sleep is fragile: too short it flakes, too long it wastes time.
Increase the implicit wait to 30 seconds only.
Implicit waits affect element lookups but do not wait for visibility conditions well, and mixing them with explicit waits is discouraged.
Call driver.navigate().refresh() and check again.
Refreshing would discard the AJAX result and the banner.
WebDriverWait with ExpectedConditions.visibilityOfElementLocated(By.id("toast-success")) polls until the banner is visible or the timeout is hit.
Why is mixing implicit and explicit waits in the same test generally discouraged?
It can cause unpredictable, sometimes much longer, wait times.
The interaction between the two mechanisms is undefined and can compound delays.
It is a compile error to use both.
It compiles fine; the problem is runtime behaviour, not compilation.
Explicit waits stop working entirely if an implicit wait is set.
They still work, but timing becomes unpredictable.
It doubles the browser memory usage.
Waits do not materially affect browser memory.
Combining them can produce unpredictable and longer-than-expected wait times because the two mechanisms interact non-additively.
Which ExpectedCondition is most appropriate when you must wait until a button is not only present in the DOM but also clickable?
ExpectedConditions.elementToBeClickable(locator)
It ensures the element is visible and enabled before you click.
ExpectedConditions.presenceOfElementLocated(locator)
Presence only checks the DOM; the element may still be hidden or disabled.
ExpectedConditions.titleIs("Home")
This checks the page title, not the button.
ExpectedConditions.alertIsPresent()
This waits for a JavaScript alert, unrelated to a button.
elementToBeClickable waits for the element to be visible and enabled, which is the precondition for a reliable click.
What is the main advantage of a FluentWait over a basic WebDriverWait?
You can set the polling interval and ignore chosen exception types.
FluentWait exposes pollingEvery and ignoring for fine-grained control.
It removes the need for any locators.
FluentWait still needs a condition, usually locator-based.
It runs without a timeout, waiting forever.
FluentWait still has an overall timeout.
It automatically retries the whole test on failure.
FluentWait polls a condition; it does not retry tests.
FluentWait lets you configure the polling interval and ignore specific exception types while waiting, giving finer control.
Why are hard-coded Thread.sleep() calls considered a poor synchronization strategy?
It ignores the actual application state, wasting time or still flaking.
Fixed delays cannot adapt to variable response times.
It only works in headless mode.
Thread.sleep() works regardless of headless mode; that is not the issue.
It throws NoSuchElementException by design.
sleep() just pauses the thread; it does not throw that exception.
It is not supported by the Java language.
Thread.sleep() is standard Java; the problem is that it is a poor practice, not unsupported.
A fixed sleep either wastes time when the app is fast or still flakes when the app is slow, because it does not react to the actual state.
Which method reloads the current page in Selenium WebDriver?
driver.navigate().refresh()
This is the dedicated reload method.
driver.reload()
There is no reload() method on WebDriver.
driver.get()
get() needs a URL; refresh() reloads the current one directly.
driver.switchTo().refresh()
switchTo() changes context; it has no refresh().
driver.navigate().refresh() reloads the current page.
To interact with an element that lives inside an <iframe>, what must the test do first?
Switch into the frame with driver.switchTo().frame(...).
Elements inside an iframe are only reachable after switching to it.
Nothing special; elements in iframes are found like any other.
Without switching, findElement will not see elements inside the iframe.
Call driver.quit() and start a new session.
This throws away the session and does not help reach the iframe.
Delete all cookies first.
Cookies are unrelated to entering an iframe context.
You must switch the driver context into the frame (switchTo().frame(...)) before locating elements inside it.
A test enters data into a field inside an iframe (id 'editor'), then must click a 'Publish' button that sits on the main page OUTSIDE the iframe. After typing in the iframe, what must the test do before clicking Publish, and why?
Call driver.switchTo().defaultContent() to return to the main document, because the driver is still scoped to the iframe.
The context stays in the iframe until you explicitly switch back to the default content.
Nothing — clicking Publish works because it is on the same page.
The driver is still inside the iframe, so it cannot see the outside button.
Call driver.switchTo().frame('editor') again.
That would re-enter the iframe, moving further from the outside button.
Delete the iframe via JavaScript before clicking.
Destroying the iframe is destructive and unnecessary; a context switch is the correct action.
After working inside a frame, you must switchTo().defaultContent() to return to the top-level document before you can find elements outside the iframe.
A native JavaScript alert (window.alert) is showing. Which Selenium call accepts (clicks OK on) the alert?
driver.switchTo().alert().accept()
You switch to the alert, then accept() presses OK.
driver.findElement(By.id('ok')).click()
A native alert is not part of the DOM, so findElement cannot reach its OK button.
driver.navigate().accept()
navigate() has no accept() method.
driver.close()
close() shuts the window rather than accepting the alert.
driver.switchTo().alert().accept() switches to the alert and accepts it.
To select the option with visible text 'Germany' from a standard HTML <select> element, which Selenium support class is designed for this?
The Select class, e.g. new Select(element).selectByVisibleText("Germany").
Select is the dedicated helper for <select> dropdowns.
The Actions class with doubleClick().
Actions handles complex gestures, not <select> option selection.
The Alert class.
Alert handles JavaScript dialogs, not dropdowns.
The WebDriverWait class.
WebDriverWait handles synchronization, not selection.
The Select class provides selectByVisibleText, selectByValue and selectByIndex for HTML <select> elements.
Which navigation call moves the browser back to the previous page in its history?
driver.navigate().back()
It steps back one entry in the browser history.
driver.back()
back() is on the Navigation object, reached via navigate().
driver.previous()
There is no previous() method.
driver.navigate().history(-1)
There is no history() method on Navigation.
driver.navigate().back() is equivalent to pressing the browser Back button.
A CI pipeline runs a suite of 200 UI tests. About 8 tests pass locally but fail roughly one run in five on CI, always on timing-sensitive steps around AJAX updates. Local runs are on fast machines; CI agents are slower and shared. Which root cause and fix best explain and address these flaky failures?
Inadequate synchronization: the tests assume timing; replace fixed sleeps with explicit waits on the specific AJAX-completion condition.
Explicit waits adapt to the slower CI agents, removing the timing race.
The application has a real bug; disable the 8 tests permanently.
Failures are timing-driven and environment-dependent, not a reproducible product defect; disabling loses coverage.
CI is fundamentally unreliable; rerun the suite until it passes.
Blind reruns mask flakiness and can hide genuine regressions.
Add a global Thread.sleep(10000) to every test.
Huge fixed sleeps waste time and still do not guarantee the AJAX call finished.
The symptom — intermittent failures on slower shared CI agents at AJAX steps — points to inadequate synchronization; replacing fixed sleeps with explicit waits on the awaited condition is the correct fix.
What is a 'flaky' test?
A test that passes and fails intermittently on unchanged code.
Non-deterministic results on the same code define flakiness.
A test that always fails.
A consistently failing test is deterministic, not flaky.
A test with more than 100 steps.
Length does not define flakiness.
A test written in a scripting language.
Language choice is unrelated to flakiness.
A flaky test produces different results (pass/fail) on the same code without any change, usually due to timing, ordering, or environment issues.
Which two practices improve the stability and independence of an automated UI test suite? (Choose two.)
Make each test set up and clean up its own data so tests do not depend on each other.
Independence prevents order-dependent, cascading failures.
Synchronize with explicit waits on meaningful conditions instead of fixed delays.
Condition-based waits adapt to timing variance and reduce flakiness.
Let tests share and reuse data created by earlier tests to save time.
Shared state couples tests and causes order-dependent flakiness.
Add generous fixed Thread.sleep() calls everywhere to be safe.
Fixed sleeps slow the suite and still do not guarantee readiness.
Independent tests that set up and tear down their own data, plus robust waits, reduce flakiness. Sharing state between tests and relying on fixed sleeps harm stability.
A StaleElementReferenceException is thrown. What does it usually indicate?
The element reference is no longer attached to the DOM (the page re-rendered).
Re-fetch the element after the DOM changes to resolve it.
The browser has run out of memory.
The exception is about a detached element, not memory.
The locator syntax is invalid.
Invalid syntax throws a different exception (InvalidSelectorException).
The test framework is misconfigured.
It is a runtime DOM condition, not a framework configuration issue.
It means a previously located WebElement reference is no longer attached to the DOM, typically because the page or that part of it was re-rendered.
Which approach best keeps UI tests independent so they can run in any order or in parallel?
Each test creates its own preconditions and cleans up its own data.
Self-contained tests can run in any order and in parallel.
Run tests strictly in a fixed order and rely on earlier tests' data.
Order dependence prevents parallelism and causes cascading failures.
Store shared state in static variables across all tests.
Shared static state couples tests and breaks parallel runs.
Never reset the browser between tests.
Leftover browser state (cookies, sessions) leaks between tests.
Each test should create the state it needs and clean up afterwards, so no test relies on the side effects of another.
A test occasionally hits StaleElementReferenceException right after the results grid reloads. What is the most robust fix?
Re-find the element after the grid reloads, guarded by an explicit wait.
A fresh lookup after the DOM change gives a valid reference.
Catch the exception and ignore it silently.
Swallowing the error hides the problem and may skip the intended action.
Increase the browser window size.
Window size has nothing to do with stale references.
Store the element reference in a static field for reuse.
Caching a reference across DOM changes makes staleness more likely, not less.
Re-locate the element after the DOM update (ideally guarded by an explicit wait) so you hold a fresh reference rather than a stale one.