A4Q Selenium Tester Mock Exam #6 — 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

What is the key difference between an implicit wait and an explicit wait in Selenium WebDriver?

An implicit wait applies globally to all element lookups, while an explicit wait waits for a specific condition on a specific element.

Correct answer

Correct: implicit is set once on the driver and affects every findElement; explicit (WebDriverWait) waits for one ExpectedCondition.

An implicit wait pauses the thread for a fixed time, while an explicit wait never polls.

Wrong: that describes Thread.sleep. Both implicit and explicit waits poll the DOM repeatedly until the timeout.

An explicit wait is global, while an implicit wait targets a single element.

Wrong: this reverses the two — the global one is the implicit wait.

There is no functional difference; the two terms are synonyms.

Wrong: they behave differently and mixing them is discouraged.

Why

An implicit wait is a global polling timeout applied to every element lookup; an explicit wait targets one condition on one element.

Question 2

A test submits a search form. The results are fetched by an AJAX call and injected into a container: after the response the DOM contains a div matching the CSS selector div.results li.item, but before the response that container is empty. The team keeps getting NoSuchElementException when asserting the first result immediately after clicking Search. Which snippet most reliably makes the test wait for the results before reading them?

new WebDriverWait(driver, Duration.ofSeconds(10)).until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("div.results li.item")));

Correct answer

Correct: it polls until the first result item is present and visible, exactly synchronising with the AJAX render.

Thread.sleep(10000); then driver.findElement(By.cssSelector("div.results li.item"));

Wrong: a fixed sleep is slow and still flaky — it fails if the response takes longer and wastes time when it is fast.

driver.findElement(By.cssSelector("div.results li.item")); called immediately after the click.

Wrong: this is exactly what throws NoSuchElementException because the element does not yet exist.

driver.manage().timeouts().pageLoadTimeout(Duration.ofSeconds(10));

Wrong: page-load timeout governs full navigations, not an in-page AJAX DOM update.

Why

The correct fix waits for the specific result element to become visible via an explicit WebDriverWait and ExpectedConditions, not a fixed sleep or a bare findElement.

Question 3

Why is using Thread.sleep() for synchronisation considered a bad practice in Selenium tests?

It always pauses for the full fixed duration, making tests slow when it is too long and flaky when it is too short.

Correct answer

Correct: it cannot adapt to the actual load time, unlike a polling explicit wait.

It is deprecated and removed from modern Java.

Wrong: Thread.sleep is a valid Java method; the problem is behavioural, not deprecation.

It only works on Firefox.

Wrong: it is browser-independent — it just pauses the test thread.

It throws NoSuchElementException by design.

Wrong: sleep does not locate elements, so it throws no such exception.

Why

Thread.sleep always waits the full fixed duration regardless of readiness, making tests both slow and flaky.

Question 4

A checkout page renders the Place order button as <button id="placeOrder" disabled>Place order</button>. JavaScript removes the disabled attribute only after all required fields validate. A test fills the fields and then clicks the button, but intermittently gets ElementClickInterceptedException / a no-op click because the button is still disabled. Which explicit wait condition best synchronises the click?

ExpectedConditions.elementToBeClickable(By.id("placeOrder"))

Correct answer

Correct: it waits until the button is visible and enabled (not disabled), so the click lands.

ExpectedConditions.presenceOfElementLocated(By.id("placeOrder"))

Wrong: the button is already in the DOM from the start, so presence is satisfied immediately while it is still disabled.

ExpectedConditions.visibilityOfElementLocated(By.id("placeOrder"))

Wrong: the disabled button is already visible; visibility does not check the enabled state.

ExpectedConditions.titleContains("Checkout")

Wrong: the page title has nothing to do with the button becoming enabled.

Why

elementToBeClickable waits until the element is both visible and enabled, which is exactly the condition being missed here.

Question 5

Why does the Selenium documentation warn against combining implicit and explicit waits in the same test?

The two timeouts can interact and add up unpredictably, causing waits far longer than expected.

Correct answer

Correct: the documented risk is unpredictable, compounded wait times.

Explicit waits stop working entirely once an implicit wait is set.

Wrong: explicit waits still work; the issue is unpredictable timing, not total failure.

Implicit waits throw a compile error when an explicit wait exists.

Wrong: there is no compile-time conflict; both are valid API calls.

Combining them makes the browser run headless automatically.

Wrong: waits have nothing to do with headless mode.

Why

Mixing them can compound timeouts unpredictably, producing wait times that are hard to reason about.

Question 6

A confirmation banner exists in the DOM at page load as <div id="banner" style="display:none">Saved</div> and is only shown (display changed) after a save completes. A test needs to assert the banner actually appears to the user. Using presenceOfElementLocated(By.id("banner")) passes even before the save. Which condition correctly waits for the banner to be shown to the user?

ExpectedConditions.visibilityOfElementLocated(By.id("banner"))

Correct answer

Correct: visibility requires the element to be displayed and have a size, matching the user-visible assertion.

ExpectedConditions.presenceOfElementLocated(By.id("banner"))

Wrong: this is already true at load because the hidden div is in the DOM — it does not wait for it to be shown.

ExpectedConditions.invisibilityOfElementLocated(By.id("banner"))

Wrong: that waits for it to disappear — the opposite of the requirement.

ExpectedConditions.numberOfElementsToBe(By.id("banner"), 1)

Wrong: the count is already 1 while it is still hidden, so this does not confirm visibility.

Why

presence only checks the element is in the DOM; visibility additionally requires it to be displayed (not display:none, non-zero size).

Question 7

Which of the following are legitimate ExpectedConditions provided by Selenium for explicit waits? (Choose two.)

textToBePresentInElement

Correct answer

Correct: a real condition that waits for given text inside an element.

alertIsPresent

Correct answer

Correct: a real condition that waits until a JavaScript alert is present.

elementToBeColored

Wrong: no such ExpectedCondition exists in Selenium.

pageToBeFastEnough

Wrong: this is not a real ExpectedCondition.

Why

textToBePresentInElement and alertIsPresent are real ExpectedConditions; the other two are invented.

Question 8

A FluentWait is being configured in Java as new FluentWait<>(driver).withTimeout(...).pollingEvery(...).ignoring(...). Which two statements about FluentWait are correct? (Choose two.)

You can define how frequently the condition is polled with pollingEvery.

Correct answer

Correct: the polling interval is explicitly configurable in FluentWait.

You can specify exception types to ignore while polling, such as NoSuchElementException.

Correct answer

Correct: ignoring() lists exceptions that should not end the wait early.

FluentWait guarantees the element will always be found within the timeout.

Wrong: if the condition never becomes true it throws a TimeoutException.

FluentWait can only be used with Firefox.

Wrong: it is browser-independent like all WebDriver waits.

Why

FluentWait lets you set the polling interval and the exception types to ignore during polling; it is a generalisation of WebDriverWait.

Question 9

In test automation, what best describes a flaky test?

A test that passes and fails intermittently on the same code and environment without changes.

Correct answer

Correct: non-deterministic results with no code change is the definition of flakiness.

A test that always fails after a code change.

Wrong: a consistently failing test is deterministic, not flaky.

A test that takes longer than one minute to run.

Wrong: slowness is not the same as non-deterministic results.

A test written without assertions.

Wrong: missing assertions is a different defect, not flakiness.

Why

A flaky test produces different results (pass/fail) on the same code without any change to that code.

Question 10

A test iterates over a list of rows, and for each row it reads a cell, clicks an Edit link that reloads the table via AJAX, and then continues the loop. It frequently throws StaleElementReferenceException on the second iteration. What is the root cause and the correct fix?

The stored element references become detached after the AJAX reload; re-locate the elements (e.g. re-run findElements) after each reload instead of reusing old references.

Correct answer

Correct: stale references point to nodes no longer attached to the DOM; re-finding them resolves it.

The locator is wrong; switch every By.id to By.xpath.

Wrong: the locator works on the first iteration — the problem is staleness after reload, not the locator strategy.

Add a large implicit wait; that removes StaleElementReferenceException.

Wrong: an implicit wait does not refresh already-captured references, so the staleness remains.

Run the browser in headless mode.

Wrong: headless mode does not change DOM detachment behaviour.

Why

After the AJAX reload the previously stored WebElement references point to detached DOM nodes; they must be re-located inside the loop after each reload.

Question 11

Which practice most improves the stability of a test suite that must run repeatedly in a CI pipeline?

Make each test independent and self-contained, creating and cleaning up its own test data.

Correct answer

Correct: independence removes ordering and shared-state failures, the biggest CI stability wins.

Increase every Thread.sleep to at least 30 seconds.

Wrong: longer fixed sleeps slow the suite and do not remove the underlying non-determinism.

Have all tests share one browser session and one dataset to save time.

Wrong: shared state between tests is a leading cause of order-dependent flakiness.

Catch and swallow every exception so tests never report failures.

Wrong: hiding failures makes tests useless, not stable.

Why

Independent, self-contained tests that set up and tear down their own data avoid order dependencies and shared-state flakiness.

Question 12

A team notices that a small number of tests fail only when the CI grid is heavily loaded and agents respond slowly, but always pass locally. What is the most likely cause?

Timing assumptions that hold locally break when the loaded grid renders pages more slowly than the waits allow.

Correct answer

Correct: environment-dependent timing is a classic flake; the remedy is robust explicit waits, not fixed delays.

The application source code is different on the grid than locally.

Wrong: normally the same build is deployed; the difference is timing/load, not source code.

WebDriver cannot run on loaded machines at all.

Wrong: WebDriver runs under load; it just exposes fragile timing assumptions.

The assertions are too strict and should be removed.

Wrong: removing assertions hides the problem; the cause is timing, not the checks.

Why

Hard-coded timing assumptions (fixed sleeps or too-short waits) break under slower, loaded environments — a classic environment-dependent timing flake.

Question 13

Which approach to locators most improves the long-term stability of UI tests against a frequently changing front end?

Prefer stable, dedicated attributes such as data-test or a fixed id over absolute XPath and styling classes.

Correct answer

Correct: purpose-built test hooks survive layout and styling changes, reducing locator breakage.

Always use absolute XPath from the html root, e.g. /html/body/div[3]/div[2]/table/tr[4]/td[2].

Wrong: absolute XPath is extremely brittle — any structural change breaks it.

Locate elements by their auto-generated framework class such as css-1a2b3c.

Wrong: hashed framework classes change on every build and are unstable locators.

Locate every element by its exact pixel coordinates.

Wrong: coordinates are not a WebDriver locator strategy and break with any layout shift.

Why

Stable, intention-revealing hooks such as dedicated data-test attributes are far less brittle than absolute XPath or auto-generated CSS classes.

Question 14

Which two of the following are common root causes of flaky Selenium tests? (Choose two.)

Race conditions caused by interacting with elements before they are ready (missing explicit waits).

Correct answer

Correct: acting before the UI is ready is a primary flakiness source.

Tests depending on shared or leftover data from previous tests.

Correct answer

Correct: shared/leftover state creates order-dependent, non-deterministic results.

Using a Page Object Model to structure the tests.

Wrong: POM improves maintainability and generally reduces, not causes, flakiness.

Adding descriptive assertion messages.

Wrong: assertion messages aid debugging and have no effect on determinism.

Why

Race conditions from missing synchronisation and dependence on shared or leftover state are two classic flakiness causes.

Question 15

A team wants to reduce flakiness without hiding real defects. Which two measures are appropriate? (Choose two.)

Replace fixed Thread.sleep calls with explicit WebDriverWait conditions.

Correct answer

Correct: synchronising on actual conditions removes race-condition flakiness without masking defects.

Quarantine tests identified as flaky and investigate their root cause before re-enabling them.

Correct answer

Correct: isolating and diagnosing flaky tests keeps the signal trustworthy while the cause is fixed.

Automatically retry every failing test up to 10 times and report a pass if any attempt passes.

Wrong: blind retries mask genuine intermittent defects and let real bugs through.

Remove the assertions from flaky tests so they can no longer fail.

Wrong: deleting assertions makes the test worthless and hides defects entirely.

Why

Replacing fixed sleeps with explicit waits and quarantining/investigating flaky tests are sound; blanket retries-until-pass and deleting assertions hide defects.

Question 16

Which WebDriver method reloads the current page, equivalent to pressing the browser refresh button?

driver.navigate().refresh()

Correct answer

Correct: refresh() reloads the current page.

driver.navigate().back()

Wrong: back() goes to the previous entry in browser history, not a reload.

driver.get("about:blank")

Wrong: this navigates to a blank page, it does not reload the current one.

driver.close()

Wrong: close() closes the current window/tab; it does not refresh.

Why

driver.navigate().refresh() reloads the current URL; the other navigate methods move in history or to a new URL.

Question 17

A page embeds a payment form inside <iframe id="payframe" src="...">. A test does driver.switchTo().frame("payframe"), types the card number, and submits. After that it must click a Continue button that lives on the main page (outside the iframe), but findElement throws NoSuchElementException. What must the test do first?

Call driver.switchTo().defaultContent() to return focus to the main document before locating the Continue button.

Correct answer

Correct: after working in an iframe you must switch back to the top document to reach main-page elements.

Call driver.switchTo().frame("payframe") a second time.

Wrong: switching into the same frame again keeps focus inside the iframe, not on the main page.

Add driver.manage().window().maximize().

Wrong: window size has nothing to do with frame context.

Increase the implicit wait to 30 seconds.

Wrong: the element is unreachable because of frame context, not timing — waiting longer will still fail.

Why

WebDriver remains scoped to the iframe until you switch back to the top-level document with switchTo().defaultContent().

Question 18

Clicking a Delete button opens a native JavaScript confirmation dialog (window.confirm) reading "Delete this item?". The test must accept it to proceed. Which sequence is correct?

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

Correct answer

Correct: switching to the alert and calling accept() confirms the native dialog.

driver.findElement(By.xpath("//button[text()='OK']")).click();

Wrong: a native confirm dialog is not part of the DOM, so it cannot be located with findElement.

driver.switchTo().alert().dismiss();

Wrong: dismiss() cancels the dialog (Cancel), which would not proceed with the deletion.

driver.navigate().refresh();

Wrong: refreshing the page abandons the dialog and the delete action.

Why

You must switch to the alert and call accept(); ordinary findElement cannot interact with native browser dialogs.

Question 19

A product page has a dropdown <select id="qty"><option value="1">1</option><option value="2">2</option><option value="3">3</option></select>. The test needs to choose the option with visible text "2". Which Selenium code selects it correctly?

new Select(driver.findElement(By.id("qty"))).selectByVisibleText("2");

Correct answer

Correct: Select.selectByVisibleText is the intended API for standard select dropdowns.

driver.findElement(By.id("qty")).sendKeys("2");

Wrong: sendKeys on a select is unreliable and not the standard way to choose an option by text.

driver.findElement(By.id("qty")).click();

Wrong: a single click only opens the dropdown; it does not select the option "2".

new Select(driver.findElement(By.id("qty"))).deselectAll();

Wrong: deselectAll clears selections and only works on multi-selects; it does not choose "2".

Why

The Select support class provides selectByVisibleText for standard HTML select elements.

Question 20

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

close() closes only the current window, while quit() closes all windows and ends the session.

Correct answer

Correct: this is the documented distinction between the two.

close() ends the session, while quit() closes only the current window.

Wrong: this reverses the two methods.

They are identical and interchangeable.

Wrong: they differ in scope — one window versus the whole session.

close() clears cookies, while quit() reloads the page.

Wrong: neither method is about cookies or reloading.

Why

close() closes the current window/tab only; quit() closes all windows and ends the WebDriver session.

Question 21

A test hovers over a Products menu to reveal a submenu, then clicks the Laptops link that only appears on hover. A plain click on the hidden link fails. Which Selenium approach correctly performs the hover-then-click?

new Actions(driver).moveToElement(productsMenu).click(laptopsLink).perform();

Correct answer

Correct: Actions.moveToElement hovers to reveal the submenu, then click targets the now-visible link, finished by perform().

laptopsLink.click(); called directly without any hover.

Wrong: the link is not interactable until the hover reveals it, so the direct click fails.

driver.navigate().to(productsMenu.getText());

Wrong: this misuses navigate with menu text as a URL and does not perform a hover or click.

new Select(productsMenu).selectByVisibleText("Laptops");

Wrong: Select only works on <select> elements, not a hover navigation menu.

Why

The Actions class chains moveToElement (hover) and click to interact with hover-revealed menus.

Question 22

Clicking a Report link opens a new browser tab. The test must read a value in the new tab and then return to the original tab. Which two steps are required? (Choose two.)

Capture driver.getWindowHandles() and switch to the new handle with driver.switchTo().window(newHandle).

Correct answer

Correct: enumerating handles and switching by handle is the standard way to work in the new tab.

Store the original handle beforehand and switch back to it with driver.switchTo().window(originalHandle).

Correct answer

Correct: keeping the original handle lets you return to the first tab after reading the new one.

Call driver.switchTo().frame(1) to reach the new tab.

Wrong: frame() switches between iframes within a document, not between browser tabs.

Use driver.navigate().forward() to move into the new tab.

Wrong: forward() moves in the current tab's history; it does not switch tabs.

Why

You capture window handles and use switchTo().window(handle) to move between tabs; getWindowHandles returns all open handles.

Question 23

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 in a dedicated class, improving maintainability and reuse.

Correct answer

Correct: centralising locators/actions per page is the core benefit of POM.

To make the browser run faster by caching pages.

Wrong: POM is a design pattern for structure, not a performance/caching mechanism.

To replace the need for any locators.

Wrong: POM still uses locators — it just organises them inside page classes.

To automatically generate test data.

Wrong: test-data generation is unrelated to the POM pattern.

Why

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

Question 24

In a Page Object, a login method is written as: public DashboardPage login(String user, String pass) { type(userField, user); type(passField, pass); click(submitBtn); return new DashboardPage(driver); }. Why does the method return a new DashboardPage instead of void?

Because a successful login lands on the dashboard; returning that page object models the navigation and lets tests chain the next actions.

Correct answer

Correct: returning the resulting page object is the idiomatic POM way to represent page transitions.

Because a method must always return an object in Java.

Wrong: Java methods can return void; the return type here is a deliberate design choice.

Because returning DashboardPage makes the login faster.

Wrong: the return type has no effect on execution speed.

Because it avoids the need for any locators on the dashboard.

Wrong: the DashboardPage still defines its own locators; returning it does not remove them.

Why

Returning the next page object models the navigation result and enables readable, chainable test flows across pages.

Question 25

Which statement best reflects a good separation of concerns when using the Page Object Model?

Page objects expose actions and page state, while assertions live in the test methods.

Correct answer

Correct: keeping assertions in tests and behaviour in page objects is the recommended separation.

Every assertion should be placed inside the page object methods.

Wrong: embedding assertions in page objects couples them to specific tests and reduces reuse.

The WebDriver instance should be created inside every page object method.

Wrong: the driver is typically shared/injected, not re-created per method.

Locators should be hard-coded directly inside each test method, not in the page object.

Wrong: that defeats POM — locators belong centralised in the page object.

Why

Assertions belong in the tests; page objects expose actions and state but should not contain the test's assertions.

Question 26

A UI redesign changes the login button's id from loginBtn to signInBtn. In a well-structured Page Object Model suite with 30 tests that log in, how many places must be updated?

One — the single locator definition in the LoginPage class.

Correct answer

Correct: centralised locators mean one change covers all 30 tests.

Thirty — one per test that logs in.

Wrong: that is the situation POM avoids; duplicated locators would be the anti-pattern.

None — Selenium updates locators automatically.

Wrong: Selenium does not auto-heal locators; the definition must be changed manually.

Two — the locator plus the browser driver configuration.

Wrong: the driver configuration is unrelated to a locator id change.

Why

With POM the locator is defined once in the LoginPage class, so only that single definition changes.

Question 27

What is a recommended relationship between test data and page objects in a maintainable Selenium framework?

Page object methods accept data as parameters from the tests, keeping the page objects reusable.

Correct answer

Correct: passing data in keeps page objects generic and reusable across scenarios.

Each page object should hard-code one specific username and password.

Wrong: hard-coding data ties the page object to one scenario and hurts reuse.

Test data must be stored inside the WebDriver instance.

Wrong: the WebDriver instance is not a data store for test values.

Page objects should generate random data and never accept parameters.

Wrong: forcing random data removes control over test conditions and reproducibility.

Why

Page objects should be parameterised with data passed in by tests, keeping them reusable rather than tied to fixed values.

Question 28

Which two are genuine benefits of applying the Page Object Model? (Choose two.)

Reduced code duplication because locators and actions are defined once per page.

Correct answer

Correct: centralisation cuts duplication across tests.

Improved maintainability, since UI changes are handled in one page class.

Correct answer

Correct: single-point updates for locators are a key maintainability benefit.

It removes the need for any explicit waits.

Wrong: synchronisation is still required; POM does not replace waits.

It guarantees the tests can never be flaky.

Wrong: POM improves structure but does not eliminate timing or environment flakiness.

Why

POM reduces code duplication and improves maintainability by centralising locators; it does not remove waits or guarantee zero flakiness.

Question 29

Given the markup <input type="email" name="email" data-test="signup-email" class="form-control ng-untouched">, which locator is the most robust choice for a test that must survive styling and framework-state changes?

By.cssSelector("[data-test='signup-email']")

Correct answer

Correct: a purpose-built data-test attribute is stable against styling and framework-state changes.

By.cssSelector(".form-control.ng-untouched")

Wrong: ng-untouched is a transient framework state class that changes as the user interacts, breaking the locator.

By.xpath("/html/body/div[2]/form/div[1]/input")

Wrong: an absolute XPath is extremely brittle and breaks on any structural change.

By.className("form-control")

Wrong: form-control is a generic shared class likely matching many inputs, so it is not unique.

Why

The dedicated data-test attribute is stable; class values contain framework/state noise (ng-untouched) that changes at runtime.

Question 30

A table row is <tr><td>SKU-9921</td><td>In stock</td><td><button>Reorder</button></td></tr> among many rows. The test must click the Reorder button in the row whose first cell text is SKU-9921. Which XPath selects that button correctly?

//td[text()='SKU-9921']/ancestor::tr//button

Correct answer

Correct: it anchors on the SKU cell, climbs to its row, and selects the button within that same row.

//button[text()='Reorder']

Wrong: this matches every Reorder button in the table, not the one tied to SKU-9921.

//td[text()='SKU-9921']/button

Wrong: the button is not a direct child of the SKU cell; it is in a sibling cell of the same row.

//tr[1]//button

Wrong: this targets the first row by position, which may not be the SKU-9921 row.

Why

You locate the td by its exact text, walk up to the ancestor tr, then find the button within that row.

Question 31

The DOM has <a href="/logout" class="nav-link"> Log out </a> with leading and trailing spaces around the text. Which XPath reliably matches the link by its visible text despite the surrounding whitespace?

//a[normalize-space()='Log out']

Correct answer

Correct: normalize-space() removes the surrounding whitespace so the text matches cleanly.

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

Wrong: the exact text node includes the leading/trailing spaces, so a strict match fails.

//a[@class='nav-link'][1]

Wrong: this relies on class and position, not the visible text, and may match another nav link.

//a[contains(@href,'Log out')]

Wrong: it searches the href attribute (/logout) for 'Log out', which it does not contain.

Why

normalize-space() trims and collapses whitespace so 'Log out' matches even with surrounding spaces; a strict text()='Log out' would fail.

Question 32

Which CSS selector matches an input whose id attribute value ends with the suffix _email, for example user_email or admin_email?

input[id$='_email']

Correct answer

Correct: $= is the 'ends-with' attribute operator in CSS.

input[id^='_email']

Wrong: ^= means 'starts with', which would match ids beginning with _email.

input[id*='_email' ]

Wrong: *= means 'contains', which is broader than the required ends-with match.

input[id='_email']

Wrong: this requires the id to equal exactly _email, matching neither user_email nor admin_email.

Why

The CSS attribute selector [id$='_email'] matches values ending with the given substring.

Question 33

Why are id and name generally preferred locator strategies over XPath when a stable id is available?

A stable id/name is simple, unambiguous and less brittle than a complex XPath expression.

Correct answer

Correct: a good id is the most direct and robust locator when one exists.

XPath cannot locate elements by id at all.

Wrong: XPath can match on @id; the point is simplicity and robustness, not capability.

id locators automatically wait for the element to load.

Wrong: no locator strategy adds waiting by itself; synchronisation is separate.

name locators only work in headless mode.

Wrong: locator strategies are independent of headless mode.

Why

id/name lookups are simple, fast and less brittle; complex XPath is more fragile and can be slower.

Question 34

Given <button data-test="save" class="btn primary" type="submit">Save</button>, which two locators would correctly match this button? (Choose two.)

By.cssSelector("button[data-test='save']")

Correct answer

Correct: the data-test attribute is present and uniquely identifies the button.

By.cssSelector("button.btn.primary")

Correct answer

Correct: the compound class selector matches an element carrying both btn and primary classes.

By.id("save")

Wrong: the button has no id attribute, only data-test='save', so By.id will not match.

By.name("save")

Wrong: there is no name attribute on the element, so By.name fails.

Why

The data-test attribute selector and the compound class selector both match; the id and name selectors do not because the element has neither.

Question 35

What does the driver.get(String url) method do in Selenium WebDriver?

It loads the given URL in the current browser window and waits for the page to load.

Correct answer

Correct: get() opens the URL and blocks until the page load completes.

It returns the HTTP response body as a String.

Wrong: get() returns void and drives the browser; it does not return the response body.

It retrieves the value of a form field.

Wrong: reading a field value uses getAttribute or getText, not driver.get.

It closes the current browser session.

Wrong: closing the session is quit(); get() opens a URL.

Why

get() navigates the browser to the given URL and waits for the page load to complete.

Question 36

An element is <input id="promo" value="WELCOME10">. During the test a user types SUMMER over it, but the visible DOM attribute still shows value="WELCOME10" in the page source. The test needs the current text the user sees in the field. Which call returns SUMMER?

element.getAttribute("value")

Correct answer

Correct: getAttribute("value") reflects the live value property, returning the typed SUMMER.

element.getText()

Wrong: getText() returns the visible inner text, which is empty for an <input> element.

element.getTagName()

Wrong: getTagName() returns 'input', not the field's value.

element.getCssValue("value")

Wrong: getCssValue reads CSS properties, not the input's value.

Why

getAttribute("value") returns the live current value property (SUMMER), whereas the static HTML attribute may still read WELCOME10; getText() returns empty for inputs.

Question 37

In JUnit-based Selenium tests, why is it good practice to instantiate the WebDriver in a @BeforeEach method and call driver.quit() in an @AfterEach method?

It gives each test a clean, isolated browser session and reliably releases the driver afterwards.

Correct answer

Correct: fresh setup and guaranteed teardown per test maximise isolation and stability.

It makes the tests run in parallel automatically.

Wrong: parallelism is configured by the test runner, not by per-test setup/teardown alone.

It removes the need for any locators.

Wrong: lifecycle methods do not affect how elements are located.

It guarantees the application has no defects.

Wrong: setup/teardown organises tests; it cannot guarantee a defect-free application.

Why

Per-test setup/teardown gives each test a clean, isolated browser session and releases the driver, improving independence and stability.

Question 38

Which exception does Selenium throw when findElement cannot locate any element matching the given locator?

NoSuchElementException

Correct answer

Correct: this is the exception thrown by findElement when nothing matches.

TimeoutException

Wrong: TimeoutException is thrown by a wait whose condition never becomes true, not by a plain findElement.

StaleElementReferenceException

Wrong: that occurs when a previously found element is no longer attached to the DOM, not when nothing is found.

ElementClickInterceptedException

Wrong: that is thrown when another element intercepts a click, not for a failed lookup.

Why

findElement throws NoSuchElementException when no matching element is found.

Question 39

What is the difference between findElement and findElements in Selenium WebDriver?

findElement returns the first matching element or throws if none exist; findElements returns a list, empty if none match.

Correct answer

Correct: this is the documented behavioural difference between the two.

Both throw NoSuchElementException when nothing matches.

Wrong: findElements returns an empty list instead of throwing.

findElements returns only the last matching element.

Wrong: findElements returns all matches as a list, not just the last.

findElement works only with XPath, findElements only with CSS.

Wrong: both accept any By locator strategy.

Why

findElement returns the first match or throws NoSuchElementException; findElements returns a list that is empty when nothing matches.

Question 40

Which two statements about Selenium WebDriver are correct? (Choose two.)

It automates real browsers through their native automation support.

Correct answer

Correct: WebDriver drives actual browsers via their automation interfaces.

It offers official language bindings such as Java, Python, C# and JavaScript.

Correct answer

Correct: WebDriver provides multiple official bindings, making it language-agnostic.

It is itself a unit-test framework that replaces JUnit or TestNG.

Wrong: WebDriver drives the browser; you still need a test runner such as JUnit or TestNG.

It requires an implicit wait to be set or it cannot find any element.

Wrong: WebDriver finds elements without any implicit wait; the wait only adds polling tolerance.

Why

WebDriver drives real browsers via their automation interfaces and is language-agnostic through official bindings; it is not a test runner and does not need an implicit wait to function.