Latest post from this blog

Test Scenarios vs. Test Cases: Understanding the Basics

What Are Test Scenarios Test scenarios represent high-level ideas or conditions that need to be validated to ensure the application works as expected. They provide a broader perspective and are typically used during the test planning phase. Purpose: To capture the "what to test" without going into granular details. Example of a Test Scenario: Verify that a user can successfully log in to the application using valid credentials. Verify the behavior of the login page when invalid credentials are entered. Verify the application behavior when the login button is clicked without entering any credentials. What Are Test Cases Test cases are detailed documents that define the specific steps to execute a test. They cover inputs, execution steps, expected results, and actual outcomes. Purpose: To guide the tester step-by-step on "how to test." Example of a Test Case (for the first scenario): Test Case ID TC_01_Login_Valid_Credentials Test Scenario Verify user login with val...

Selenium Interview Questions and Answers

1. What is Selenium?

Selenium is a free, open-source framework used for automating web browser interactions. It supports multiple programming languages like Java, Python, and C#, and works on various platforms such as Windows, Mac, and Linux. Selenium is widely used for regression testing, cross-browser testing, and functional testing of web applications.

2. What are the components of Selenium?
  • Selenium IDE: A record-and-playback tool for creating simple scripts without programming knowledge.
  • Selenium Remote Control (RC): A server-based tool for running tests in multiple programming languages (now deprecated).
  • Selenium WebDriver: An advanced tool that directly communicates with browsers for more efficient and modern testing.
  • Selenium Grid: Allows parallel execution of tests across multiple machines, browsers, and operating systems.
3. Why is Selenium extensively used for automation?

- Works with multiple browsers (e.g., Chrome, Firefox, Safari, Edge).
- Supports many programming languages (e.g., Java, Python, C#).
- Compatible with various operating systems.
- Free and open-source with strong community support.
- Easily integrates with CI/CD tools (e.g., Jenkins).
- Supports testing frameworks like TestNG and JUnit.

4. Advantages and Disadvantages of Selenium?

Advantages:
- Cross-browser compatibility.
- Multi-language support.
- Parallel and distributed testing via Selenium Grid.
- Open-source with no licensing costs.
Disadvantages:
- Requires programming skills.
- No built-in reporting (relies on third-party tools like TestNG).
- High maintenance effort for test scripts.
- Browser updates can cause compatibility issues.

5. Difference Between WebDriver and Selenium RC?

WebDriver:
- Directly interacts with the browser.
- Faster and supports modern web elements.
- Requires minimal setup.
Selenium RC:
- Uses an intermediate server to communicate with the browser.
- Slower and less efficient.
- Deprecated and not suitable for modern web applications.

6. Types of Testing Possible with Selenium?
  • Regression Testing - Ensures that new changes or enhancements don’t break the existing functionality.
  • Functional Testing - Verifies that the application behaves as expected according to functional requirements.
  • Cross-Browser Testing - Tests the application across multiple browsers like Chrome, Firefox, Safari, and Edge to ensure compatibility
7. What are the different types of waits available in Selenium?
  • Explicit Wait: you can wait for a certain condition, such as an element becoming clickable, visible, or present on the DOM, before taking action.
  • Implicit Wait: implicit wait commands selenium to wait for a certain amount of time before throwing a "No such element" exception
  • Fluent Wait : This wait is used to inform the Webdriver to wait for a specific condition at a given interval during which the condition is checked for a particular amount of time prior to throwing an exception.
8. Differences Between `driver.close()` and `driver.quit()`

driver.close(): Closes the current browser tab/window.
driver.quit(): Closes all browser windows and ends the WebDriver session.

 9. Differences Between `findElement()` and 'findElements()'?

findElement:
- findElement(): Returns the first matching element; throws an exception if not found.
- findElement(): Stops searching after finding the first matching element.
- findElement() Returns the first matching element.

findElements:
- findElements(): Returns a list of matching elements or an empty list if none are found.
- findElements() Continues searching to find all matching elements.
- findElements() Returns all matching elements in a list.

10. Differences Between XPath and CSS Selectors

XPath:
- Supports a wide range of axes (e.g., ancestor, descendant, preceding, following, etc.) to navigate the DOM in any direction.
Example:input[@id='email']/preceding::label finds the label before an input element.
- Can locate elements based on text content.
Example: //a[text()='Login']
  
CSS Selectors:
- CSS Selector is simpler, faster, and better suited for basic element identification (like ID, class, and direct relationships).
- Does not support text-based element identification.

11. What are the Cookies Methods in Selenium?
  • Remove All Cookies: `driver.manage().deleteAllCookies();`
  • Remove Specific Cookie by Name: `driver.manage().deleteCookieNamed("name");`
  • Retrieve All Cookies: `driver.manage().getCookies();`
  • Add a New Cookie: `driver.manage().addCookie(new Cookie("name", "value"));`
12. Which design pattern have you used in your framework?

1. Page Object Model (POM):    
            
  • Used to represent each web page as a class and web elements as variables within the class.
  • Keeps test scripts clean and maintains a separation between the test logic and the underlying page structure.
  • Helps reduce code duplication and improves readability and maintainability.
2. Factory Pattern: 
  • Applied for WebDriver initialization based on browser types like Chrome, Firefox, or Edge.
  • Ensures scalability and encapsulation, making it easy to extend support for more browsers or configurations.
3. Singleton Pattern: 
  • To ensure only one WebDriver instance is used across tests.
  • Avoids unnecessary instantiation and ensures better control over browser sessions.
4. Dependency Injection:
  • Used for sharing WebDriver or other dependencies (e.g., user data, configuration files) between different classes like Steps, Hooks, and Page Objects.
13. Maven Surefire Plugin?

- Executes unit and integration tests.
- Generates test reports in XML and HTML formats.
- Supports parallel test execution.

 14. Handling Failed Test Cases in TestNG?
- Use `testng-failed.xml` to rerun only failed tests.

- Implement the `ITestListener` interface to log failed test data for analysis.

15. Why is WebDriver driver = new ChromeDriver() preferred?

It provides flexibility to switch to other browser drivers (e.g., FirefoxDriver, EdgeDriver) without modifying code that uses WebDriver.

Note: if you are Using ChromeDriver driver = new ChromeDriver(); tightly couples the code to the Chrome browser, making it difficult to switch to other browsers without rewriting the implementation. Because of this issue we preferred the 

WebDriver driver = new ChromeDriver();

15. How do you verify whether an element is inside an iframe? Can you directly access elements inside an iframe without switching to it?

To verify if an element is inside an iframe, inspect the webpage using browser developer tools. Check if the element is nested under an <iframe> tag.
You cannot directly access elements inside an iframe without switching to it because iframes are treated as separate documents within the main webpage.

16. How do you retrieve the number of iframes on a web page?

Use the following Selenium code to count the number of iframes:
List<WebElement> iframes = driver.findElements(By.tagName("iframe"));
System.out.println("Number of iframes on the page: " + iframes.size());

17. How would you handle slow-loading iframes during testing?

Handle slow-loading iframes using explicit waits. For example:
DriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
wait.until(ExpectedConditions.frameToBeAvailableAndSwitchToIt(By.id("iframeId")));
This waits until the iframe is available and switches to it.

18. Different ways to click an element in Selenium?

Selenium is a free, open-source tool designed for web automation testing. It enables testers to perform various actions, such as clicking, typing, and executing mouse or keyboard interactions, on web page elements and verify the resulting behavior.

19. Parent class of all exceptions in Java?

java.lang.Throwable is the parent class of all exceptions in Java.

20. What is normalize-space function in xpath ? What is use of it.

The normalize-space() function in XPath is used to remove leading and trailing whitespace from a string and replace sequences of whitespace characters (such as spaces, tabs, and line breaks) within the string with a single space. This function is particularly useful when dealing with text content that might have inconsistent or irregular spacing.

Syntax:
normalize-space(string)
Example:
 <div id="example"> Hello World. </div>

Without normalize-space():
//div[@id='example' and text()='Hello World']

This XPath would fail because of the extra spaces.

With normalize-space():
//div[@id='example' and normalize-space(text())='Hello World']

This XPath correctly identifies the element by normalizing the text content.

Use Cases:
  • Simplifies handling of irregular whitespace.
  • Makes text comparisons more robust.
  • Reduces the need for manual text cleanup in automation scripts.

21. What are the difference between Action vs. Actions in Selenium?

Action 
  • Represents a single user interaction (e.g., a click or a keypress).
  • It is the result of invoking a method like build() from the Actions class.
Example  
Action action = new Actions(driver).moveToElement(element).click().build();
action.perform();

Actions:
  • A utility class for creating complex user interactions like drag-and-drop or multiple keypresses.
  • Provides methods like clickAndHold(), release(), and moveToElement().
Example 
Actions actions = new Actions(driver);
actions.moveToElement(element).click().perform();

22. What are the difference between get() and navigate()?

get() Method:
  • Purpose - To open a specific URL and load the page.
  • Page Load - Blocks and waits until the page is fully loaded before returning control to the script.
  • Browser History - Does not affect the browser's history; simply loads the new URL.
  • Usage - driver.get("https://example.com");
  • Handling - Handling Page Load Automatically handles waiting for the page to load.
  • Method Type - Direct navigation to the specified URL.
Navigate() Method:
  • Purpose - Provides a broader set of navigation capabilities including going back, forward, and refreshing, in addition to opening URLs.
  • Page Load -`navigate().to(URL)` does not inherently wait for the page to be fully loaded; additional handling may be required.
  • Browser History - Interacts with the browser's history. Allows navigating back, forward, and refreshing.
  • Usage - Syntax - To open a URL: `driver.navigate().to("https://example.com");`
  •  Handling - Handling Page Load Requires additional explicit waits to handle synchronization issues.
  • Method Type - Advanced navigation and browser history management.
23. What are locators in Selenium?
Locators are used to find and interact with elements on a webpage. Types include:
  • ID
  • Name
  • Class Name
  • Tag Name
  • Link Text
  • Partial Link Text
  • CSS Selector
  • XPath
24. What are the methods available in WebDriver?
  • close()
  • findElement()
  • findElements()
  • get()
  • getTitle()
  • getCurrentUrl()
  • manage()
  • quit()
  • switchTo()

25. What is the use of WebDriver?
  • It is mainly used for providing the connection between the browser and local system.
  • It acts as a bridge.
26. What is the difference between Radio and CheckBox button?

Radio button:
  • For radio button we have to select atleast one option.
  • For deselecting we have to select the another option present.
Check box:
  • In checkboxes,we can select more than one option.
  • For deselecting we have to select the same option one more time.

27. What is mean by System.setProperty?
  • System is a class and setProperty is a method which accepts 2 arguments i.e key and path
  • Key represents in which browser we are going to test the application
  • path defines the location of driver executable file.
  • It is used to set the class and path location of driver. 
28 . What are the key differences between getText() and getAttribute() in Selenium WebDriver?

getText()
  • Retrieves the visible text of a web element.
  • Fetches only the content displayed on the web page.
  • Commonly used for validating labels, headings, or other on-screen content.
  • Does not work with attributes or hidden text.
  • Example: For <div>Hello</div>, getText() returns "Hello".
getAttribute()
  • Retrieves the value of a specific attribute of a web element.
  • Works with both visible and hidden attributes (e.g., id, href, value).
  • Commonly used for fetching links, element IDs, input field values, etc.
  • Does not retrieve the visible text unless it's part of an attribute (e.g., placeholder).
  • Example: For <a href="https://example.com">Click</a>, getAttribute("href") returns "https://example.com".
29. In which class/interface getText() and getAttribute() methods present ?

In WebElement interface ,getText() and getAttribute() methods are present

30. What is the use of Thread.sleep (milliseconds)?

Thread.sleep(milliseconds) is used to make your program to wait for some defined time to avoid abnormal termination due to page loading issues.

31. Whether it is possible to get the text from webpage without using getText()?

No,it is not possible to get the text from webpage without using getText() met

32. What are methods available in Actions class ?
  • moveToElement()
  • contextClick()
  • doubleClick()
  • dragAndDrop()
33. What is the difference between moveToElement() & switchTo()?
  • moveToElement() will move to that particular element.
  • switchTo() can be used to move the control to an alert,frame or window
34. What are the screenshot output type formats available?
  • OutputType.FILE
  • OutputType.BYTES
  • OutputType.BASE64
35. What are the methods available in select class?
  • selectByValue();
  • selectByVisibleText();
  • selectByIndex();
  • getOptions();
  • getAllSelectedoptions();
  • getFirstselectedoptions();
  • isMultiple();
  • deSelectByValue();
  • deSelectByVisibleText();
  • deSelectByIndex();
  • deSelectAll();
35. can we deselect the options in dropdown?
Yes, we can deselect the options in dropdown using the below methods.
  • deSelectByValue(); 
  • deSelectByVisibleText(); 
  • deSelectByIndex(); 
  • deSelectAll()



Comments

Popular posts from this blog

Common Exception in Selenium

Test Scenarios vs. Test Cases: Understanding the Basics

Handling Shadow DOM in Selenium WebDriver

Handling HTTPS Websites and SSL Certificate Errors in Selenium

Normalize-space Function In Xpath