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.

Question 1

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.

Correct answer

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.

Why

get() navigates to a URL and, by default, blocks until the document readyState is 'complete'.

Question 2

What is the difference between driver.getWindowHandle() and driver.getWindowHandles()?

getWindowHandle() returns a single current handle; getWindowHandles() returns a Set of all handles.

Correct answer

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.

Why

getWindowHandle() returns the current window's handle (a String); getWindowHandles() returns a Set of all open window/tab handles.

Question 3

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 answer

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.

Why

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.

Question 4

When no matching element exists on the page, how do findElement() and findElements() behave?

findElement() throws NoSuchElementException; findElements() returns an empty list.

Correct answer

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.

Why

findElement() throws NoSuchElementException; findElements() returns an empty list.

Question 5

Which of the following are legitimate responsibilities of the Selenium WebDriver API? (Choose two.)

Driving a real browser through its native automation support.

Correct answer

Core purpose of WebDriver.

Locating elements and simulating user interactions with them.

Correct answer

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.

Why

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.

Question 6

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();

Correct answer

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.

Why

The Actions class builds a composite gesture: moveToElement(menu) then click(submenuLink), finalized with perform().

Question 7

What is the difference between driver.close() and driver.quit()?

close() closes the current window; quit() closes all windows and ends the session.

Correct answer

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.

Why

close() closes the current window; quit() closes all windows and ends the WebDriver session, freeing the driver process.

Question 8

Which WebElement method should be used to clear an existing value from a text input before typing a new one?

clear()

Correct answer

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.

Why

clear() empties the field; sendKeys() then types the new value.

Question 9

Which By strategy is generally the fastest and most robust when an element carries a unique, stable id attribute?

By.id

Correct answer

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.

Why

By.id targets the id attribute directly and is the preferred locator when a stable unique id exists.

Question 10

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']")

Correct answer

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.

Why

A CSS attribute selector on the stable data-test attribute is concise and resilient to class churn.

Question 11

You need an XPath that selects an <a> element by its exact visible text 'Log out'. Which expression is correct?

//a[text()='Log out']

Correct answer

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.

Why

//a[text()='Log out'] matches anchors whose text node equals 'Log out' exactly.

Question 12

Which CSS selector matches an input element whose id is exactly 'email'?

input#email

Correct answer

# selects by id in CSS.

input.email

. selects by class, not id.

input=email

Not valid CSS syntax.

input@email

Not valid CSS syntax.

Why

In CSS, # denotes an id, so input#email or #email targets the element with id 'email'.

Question 13

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]

Correct answer

Any structural change breaks the whole path.

Selectors based on auto-generated class names like css-1a2b3c

Correct answer

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.

Why

Absolute XPath and locators tied to volatile auto-generated class names both break easily on UI changes.

Question 14

Which XPath axis expression selects a <label> that is the immediate parent of the context node?

parent::label

Correct answer

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.

Why

.. (or parent::label) moves to the parent; parent::node()/self restrictions can name the tag.

Question 15

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']

Correct answer

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.

Why

You anchor on the td text and navigate to the button within the same row using the ancestor tr.

Question 16

Which CSS selector matches an element that has BOTH classes 'nav' and 'active'?

.nav.active

Correct answer

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.

Why

Chaining class selectors without a space (.nav.active) requires both classes on the same element.

Question 17

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.

Correct answer

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.

Why

POM encapsulates a page's locators and interactions behind a class, so tests use readable methods and locator changes are made in one place.

Question 18

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 answer

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.

Why

Returning the resulting page object models navigation flow and gives tests a fluent, type-safe chain that reflects the user's journey.

Question 19

Which two practices are consistent with a well-designed Page Object Model? (Choose two.)

Keep locators private and expose behaviour through intention-revealing methods.

Correct answer

Encapsulation is central to POM.

Each page (or meaningful component) has its own class.

Correct answer

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.

Why

Page objects should keep locators private and expose intention-revealing methods; they should not contain test assertions.

Question 20

In a Page Object Model, where should the WebDriver instance typically be provided to a page object?

Injected through the page object's constructor.

Correct answer

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.

Why

The driver is usually injected into the page object via its constructor, keeping the object testable and free of global state.

Question 21

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.

Correct answer

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.

Why

Extract the header into its own component/page object that the other pages compose or reference, so its locators live in one place.

Question 22

Which statement best describes the relationship between page objects and test classes?

Tests call page object methods to act, then assert on outcomes themselves.

Correct answer

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.

Why

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.

Question 23

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.

Correct answer

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.

Why

An implicit wait applies globally to all findElement calls; an explicit wait (WebDriverWait) waits for a specific condition on a specific element.

Question 24

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")))

Correct answer

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.

Why

WebDriverWait with ExpectedConditions.visibilityOfElementLocated(By.id("toast-success")) polls until the banner is visible or the timeout is hit.

Question 25

Why is mixing implicit and explicit waits in the same test generally discouraged?

It can cause unpredictable, sometimes much longer, wait times.

Correct answer

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.

Why

Combining them can produce unpredictable and longer-than-expected wait times because the two mechanisms interact non-additively.

Question 26

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)

Correct answer

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.

Why

elementToBeClickable waits for the element to be visible and enabled, which is the precondition for a reliable click.

Question 27

What is the main advantage of a FluentWait over a basic WebDriverWait?

You can set the polling interval and ignore chosen exception types.

Correct answer

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.

Why

FluentWait lets you configure the polling interval and ignore specific exception types while waiting, giving finer control.

Question 28

Why are hard-coded Thread.sleep() calls considered a poor synchronization strategy?

It ignores the actual application state, wasting time or still flaking.

Correct answer

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.

Why

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.

Question 29

Which method reloads the current page in Selenium WebDriver?

driver.navigate().refresh()

Correct answer

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().

Why

driver.navigate().refresh() reloads the current page.

Question 30

To interact with an element that lives inside an <iframe>, what must the test do first?

Switch into the frame with driver.switchTo().frame(...).

Correct answer

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.

Why

You must switch the driver context into the frame (switchTo().frame(...)) before locating elements inside it.

Question 31

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.

Correct answer

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.

Why

After working inside a frame, you must switchTo().defaultContent() to return to the top-level document before you can find elements outside the iframe.

Question 32

A native JavaScript alert (window.alert) is showing. Which Selenium call accepts (clicks OK on) the alert?

driver.switchTo().alert().accept()

Correct answer

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.

Why

driver.switchTo().alert().accept() switches to the alert and accepts it.

Question 33

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").

Correct answer

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.

Why

The Select class provides selectByVisibleText, selectByValue and selectByIndex for HTML <select> elements.

Question 34

Which navigation call moves the browser back to the previous page in its history?

driver.navigate().back()

Correct answer

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.

Why

driver.navigate().back() is equivalent to pressing the browser Back button.

Question 35

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.

Correct answer

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.

Why

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.

Question 36

What is a 'flaky' test?

A test that passes and fails intermittently on unchanged code.

Correct answer

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.

Why

A flaky test produces different results (pass/fail) on the same code without any change, usually due to timing, ordering, or environment issues.

Question 37

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.

Correct answer

Independence prevents order-dependent, cascading failures.

Synchronize with explicit waits on meaningful conditions instead of fixed delays.

Correct answer

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.

Why

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.

Question 38

A StaleElementReferenceException is thrown. What does it usually indicate?

The element reference is no longer attached to the DOM (the page re-rendered).

Correct answer

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.

Why

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.

Question 39

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.

Correct answer

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.

Why

Each test should create the state it needs and clean up afterwards, so no test relies on the side effects of another.

Question 40

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.

Correct answer

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.

Why

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.