Interview Qns & Answers
Interview Qns & Answers
Selenium WebDriver is a web automation tool used for automating web application
testing. It allows testers to control a browser programmatically by simulating user
interactions with a web page. WebDriver directly communicates with the browser,
providing faster execution and more control.
- Can be integrated with other testing frameworks like TestNG, JUnit, and Cucumber
Selenium WebDriver is faster than Selenium RC, as WebDriver interacts directly with
the browser. Selenium RC requires a server to execute test cases, making it slower and
more complex. WebDriver also supports a more modern, stable API.
- Cross-browser compatibility
- Provides flexible locators for elements such as XPath, CSS Selector, and ID
XPath is an XML path language used for navigating elements in an XML document. It is
used in Selenium to locate elements when the element has no unique ID, Name, or Class.
XPath is highly flexible and supports locating elements based on attributes, text, or even
partial matches.
Absolute XPath starts from the root node and goes to the target element. It begins with a
single slash “/” and is prone to changes in the HTML structure. Relative XPath starts
from the middle of the HTML document and begins with a double slash “//,” which is
more stable as it doesn’t depend on the entire hierarchy.
In Selenium WebDriver, the driver instance for a specific browser (like ChromeDriver or
FirefoxDriver) is created to launch a browser. For example, `WebDriver driver = new
ChromeDriver();` launches the Chrome browser.
The `navigate()` method in WebDriver allows for browser navigation. For instance:
WebDriver provides `getWindowHandles()` to get the IDs of all open windows and
`switchTo().window(windowID)` to switch control to a particular window. Each
browser window has a unique window handle, which can be iterated over to manage
multiple windows.
12. What are WebDriver waits, and what types are available?
- Implicit Wait: Sets a global wait time for all elements. WebDriver waits until the
specified time before throwing a NoSuchElementException.
- Explicit Wait: Applies to specific elements, allowing for more targeted waiting
conditions (such as element visibility or clickability).
This exception occurs when an element is no longer present in the DOM. This can
happen when the DOM structure changes, such as during page navigation or dynamic
content updates. Solutions include re-locating the element or using wait statements to
wait for the element to reappear.
`findElement` locates the first element matching the locator and returns it, throwing an
exception if no element is found. `findElements` returns a list of all elements matching
the locator, returning an empty list if no elements are found.
17. How can you perform drag and drop in Selenium WebDriver?
The Actions class in WebDriver can be used for drag-and-drop operations. It has
methods like `clickAndHold`, `moveToElement`, and `release` to perform drag-and-drop
actions.
The Actions class in Selenium is used to handle advanced user interactions, such as drag
and drop, keyboard actions, and mouse movements. It provides methods like
`moveToElement`, `clickAndHold`, `doubleClick`, and `contextClick`.
The Select class is used for handling dropdown elements. It provides methods like
`selectByVisibleText`, `selectByIndex`, and `selectByValue` for selecting dropdown
options.
Page Object Model (POM) is a design pattern that enhances code maintainability and
reusability by representing each web page as a separate class containing web elements
and actions. POM reduces code duplication and makes the code cleaner and more
organized.
Fluent Wait allows defining the maximum wait time, polling frequency, and ignoring
specific exceptions while waiting. It repeatedly checks the condition and provides more
flexibility than implicit and explicit waits.
TestNG is a testing framework used for structuring and managing test cases in
Selenium. It provides features like parallel execution, grouping of test cases, data-driven
testing, annotations, and generating reports.
Data-driven testing can be achieved using the TestNG DataProvider or by reading data
from external files (Excel, CSV, etc.) using libraries like Apache POI. It allows running
the same test case with multiple sets of input data.
Cross-browser testing ensures that the web application works consistently across
different browsers. In Selenium, cross-browser testing is performed by specifying the
browser drivers (like ChromeDriver, FirefoxDriver) and executing the same script on
multiple browsers.
To handle dynamically loaded elements, it’s best to use explicit waits, like
WebDriverWait with ExpectedConditions. This allows waiting until a specific condition
is met (like element visibility or clickability) before proceeding, ensuring the element is
available.
32. How can you close all browser windows opened by Selenium?
To close all open browser windows, the `driver.quit()` command is used. This
terminates all active sessions and closes all associated browser windows.
For file uploads, WebDriver can use the `sendKeys()` method to pass the file path
directly to the file input element (typically with a locator for the input field with
`type="file"`). This approach is simple and does not require additional tools.
File downloads are generally handled by setting browser preferences (e.g., setting
default download directory) before initiating a download in Selenium. For instance, in
Firefox, preferences can be set using FirefoxOptions, which specify download behavior.
`driver.close()` closes the current browser window where the focus is present, while
`driver.quit()` closes all browser windows and terminates the WebDriver session.
36. How can you maximize the browser window in Selenium WebDriver?
Right-click actions can be performed using the Actions class with the `contextClick()`
method. For example, `actions.contextClick(element).perform()` performs a right-click
on the specified element.
For browser pop-ups like alerts, WebDriver can handle them using `switchTo().alert()`,
with methods like `accept()` to click OK, `dismiss()` to cancel, and `getText()` to read the
pop-up text.
`getText()` retrieves the visible text of a web element, often used for verification
purposes to check if the displayed text on the webpage matches the expected text.
In TestNG, parallel test execution can be configured in the `testng.xml` file by setting the
`parallel` attribute to methods, classes, or tests. This reduces overall execution time by
running multiple tests concurrently.
`Assert` stops the test execution if the condition fails, while `Verify` checks the condition
but allows the test to continue even if the verification fails. `Assert` is commonly used
when the test cannot proceed without a certain condition being met, whereas `Verify` is
used for optional checks.
44. What is the difference between CSS Selector and XPath in Selenium?
CSS Selector is generally faster and less complex than XPath, making it preferable for
simple element locating. XPath is more flexible and allows navigating in both directions
(parent-child, child-parent) in the DOM, which CSS Selector does not support.
46. What are the benefits of using the Page Factory in Selenium?
Page Factory in Selenium is used to initialize web elements defined in the Page Object
Model. It simplifies element locating by using annotations like `@FindBy`, and
`initElements` to initialize elements, leading to cleaner and more maintainable code.
To handle SSL certificate errors, browser capabilities can be configured. For instance, in
Chrome, `ChromeOptions` has the `acceptInsecureCerts` option which can be set to true
to bypass SSL warnings.
Headless browser testing allows test execution without a visible browser UI. It is faster
and consumes less memory, suitable for environments where visual UI is unnecessary.
Headless mode can be set in Chrome, Firefox, and other browsers.
AJAX calls are asynchronous, so WebDriver needs to wait for the data to load. Explicit
waits, such as WebDriverWait with ExpectedConditions (e.g.,
`visibilityOfElementLocated` or `presenceOfElementLocated`), are helpful in handling
AJAX elements and ensuring the DOM updates before proceeding.
53. How do you execute tests on a remote machine using Selenium Grid?
To execute tests on a remote machine, configure a Selenium Grid with a Hub and
multiple Nodes. The Hub receives the test commands, and the Nodes execute the tests.
By setting the remote WebDriver URL to the Hub’s address and passing the desired
capabilities, tests run on specified browser and OS combinations.
Fluent wait is a type of explicit wait that allows defining the maximum time to wait for a
condition, the frequency to check for the condition, and the ability to ignore specific
exceptions. Fluent wait is useful when dealing with elements that require dynamic
waiting and custom handling.
`findElement()` locates a single element based on the specified locator and throws a
`NoSuchElementException` if not found. `findElements()` returns a list of matching
elements and returns an empty list if no elements are found, allowing for safer handling.
57. How can you handle multiple child windows in Selenium WebDriver?
Multiple child windows can be handled by using `getWindowHandles()` to get a set of all
window handles and iterating over them to switch to each window using
`switchTo().window(handle)`. This is often used for popup handling or switching
between multiple browser tabs.
Absolute XPath starts from the root node (using a single slash '/') and navigates through
the entire DOM hierarchy. Relative XPath starts from any point in the DOM (using
double slashes '//') and is preferred for its flexibility and reliability, especially in
dynamic pages.
`navigate().to()` is used to open a new URL, similar to `get()`, but with additional
navigation control. It allows performing forward and backward navigation through the
browser history with methods like `navigate().back()` and `navigate().forward()`.
Dropdowns in Selenium are handled with the `Select` class, which provides methods
like `selectByVisibleText`, `selectByValue`, and `selectByIndex` to choose options.
`deselectAll()` and other methods can also be used for multi-select dropdowns.
The `getTitle()` method is used to retrieve the page title. Validating the title involves
checking if the title text matches the expected text, often done with assertions to
confirm navigation correctness.
Implicit wait is a global wait that applies to all elements and commands in the
WebDriver session. It waits for a specified time before throwing a
`NoSuchElementException`. It is used when you want to set a default wait time for
locating elements.
`pageLoadTimeout()` sets the maximum time to wait for a page to load. If the page takes
longer than the specified time, a TimeoutException is thrown. It’s useful in handling
scenarios where page load speed may vary.
67. How can you maximize the browser window in Selenium WebDriver?
`@FindBy` is part of the Page Factory in Selenium. It is used to locate elements using
different locators like id, name, class, and XPath. It simplifies locating elements by
directly binding them to variables, making code more readable.
`driver.getCurrentUrl()` retrieves the URL of the current page. This is often used in
verification steps to ensure the user is on the correct page after navigation or
redirection.
To upload a file without `sendKeys()`, third-party tools like AutoIt, Robot Class, or
JavaScriptExecutor can be used. These tools help handle native file upload dialogs that
Selenium cannot directly interact with.
WebDriverWait is an explicit wait that waits for a specified condition to be met before
executing further commands. It helps in handling dynamic elements that may load or
change state unpredictably.
To handle pop-ups, use `Alert` interface methods like `accept()` to confirm or `dismiss()`
to cancel the pop-up. For browser-based pop-ups, switching to the alert using
`driver.switchTo().alert()` is necessary.
Drag-and-drop actions are performed using the `Actions` class with methods like
`clickAndHold(source)`, `moveToElement(target)`, and `release()`. The
`dragAndDrop(source, target)` method also simplifies this process.
Mouse hover actions are achieved using the `Actions` class with
`moveToElement(element)`. This simulates moving the mouse over the element,
triggering any hover effects.
JavaScript execution is done using the `JavascriptExecutor` interface. This is useful for
actions like scrolling, clicking hidden elements, or fetching browser details not
accessible through WebDriver methods.
POM is a design pattern that promotes better test structure by creating separate classes
for each page. It provides a clear representation of elements and actions on each page,
making tests more maintainable.
Page Factory is a class in Selenium that extends the POM concept. It uses `@FindBy`
annotations to initialize elements when an instance of the page class is created,
reducing code and improving readability.
Cookies can be handled using methods like `getCookies()` to retrieve all cookies,
`addCookie()` to add a cookie, and `deleteAllCookies()` to remove all cookies. Managing
cookies helps in maintaining user sessions.
Headless browser testing is executing tests without a visible browser UI. Options like
Chrome and Firefox support headless mode, which reduces resource usage and speeds
up testing.
Keyboard actions are done using the `Actions` class and methods like
`sendKeys(Keys.ENTER)`. This helps simulate keyboard inputs such as pressing keys or
combinations.
Dynamic elements can be handled by using explicit waits like `WebDriverWait` to wait
for specific conditions, such as element visibility or presence, before interacting with
them.
Broken links can be identified by retrieving each link’s URL, making an HTTP request
using tools like `HttpURLConnection` in Java, and checking if the response status is 200
for valid links.
To verify if an image is displayed, use `isDisplayed()` to check its visibility. For further
validation, fetch the image URL and check the HTTP status code to ensure it loads
properly.
Double-click actions are achieved using the `Actions` class with the
`doubleClick(element)` method. This is useful for elements requiring double-click
interactions.
96. How can you get the page source in Selenium WebDriver?
The `getPageSource()` method retrieves the entire HTML source of the current page.
This is helpful for validating if specific content is present or for debugging purposes.
Test retries can be implemented using test frameworks like TestNG or JUnit, which
support retry mechanisms in case of test failures. This approach helps automatically
rerun failed tests, improving test reliability.