Selenium Testing Framework Selenium Test Design & Page Object Model 2 — Questions and Answers
Question 1: Which locator strategy is generally considered the most reliable and stable in Selenium?
- XPath by position
- CSS class name
- ID (Correct answer)
- Link text
Correct answer: ID
IDs are unique per page and stable, making them the most reliable locator when available in the HTML.
Question 2: What is the purpose of the `By` class in Selenium WebDriver?
- To provide a factory for creating locator strategies (Correct answer)
- To manage browser cookies
- To take screenshots
- To handle JavaScript execution
Correct answer: To provide a factory for creating locator strategies
The By class is a factory that creates locator mechanism objects used by driver.findElement() and driver.findElements().
Question 3: When should you prefer CSS selectors over XPath in Selenium tests?
- When traversing up the DOM tree (parent selection)
- When locating elements by text content
- For most forward-navigation selections — CSS is faster and more readable (Correct answer)
- When elements have no attributes
Correct answer: For most forward-navigation selections — CSS is faster and more readable
CSS selectors are generally faster than XPath and more readable for attribute/class/ID-based selections in most browsers.
Question 4: What is a 'data-testid' attribute and why is it used in Selenium test design?
- A Selenium-specific HTML attribute for locating elements in Grid mode
- A custom HTML attribute added by developers specifically for stable test automation selectors (Correct answer)
- An attribute that identifies the test framework version
- A W3C standard attribute for accessibility
Correct answer: A custom HTML attribute added by developers specifically for stable test automation selectors
data-testid attributes are added by developers to give automation-stable hooks that won't change when styling or layout changes.
Question 5: What does the `driver.findElements()` method return when no matching elements are found?
- null
- An empty list (Correct answer)
- A NoSuchElementException
- A WebElement with isEmpty=true
Correct answer: An empty list
Unlike findElement(), findElements() returns an empty List rather than throwing an exception when no elements match.
Question 6: Which XPath axis selects the parent element of a given node?
- ancestor::
- preceding-sibling::
- parent:: (Correct answer)
- following::
Correct answer: parent::
The `parent::` axis in XPath selects the direct parent of the context node.
Which locator strategy is generally considered the most reliable and stable in Selenium?