top of page
arrow.png
arrow_edited_edited.jpg

Selenium Interview Questions

Differences between driver.get() and driver.navigate().to() in Selenium WebDriver:

​

​

​

​

​

​

​

​

​

​

What is the purpose and functionality of the @FindBy annotation in Selenium WebDriver?

When using Page Factory in Selenium, we typically create a separate class representing the page, and then use the @FindBy annotations to locate elements.

@FindBy is an annotation in Selenium WebDriver used in conjunction with the Page Object Model (POM). It helps in locating and initializing WebElement instances in a page class.

 

import org.openqa.selenium.WebElement;

import org.openqa.selenium.support.FindBy;

public class HomePage {

public WebDriver driver;

// Constructor initializes elements using PageFactory

    public HomePage(WebDriver driver) {

             this.driver=driver

             PageFactory.initElements(driver, this);

    }

  // Using @FindBy to locate the WebElement with a specified XPath

    @FindBy(xpath = "//input[@id='username']")

    private WebElement  usernameInput;

    // Another example with different locator strategy (CSS selector)

    @FindBy(css = "button[type='submit']")

    private WebElement submitButton;

 // Methods to interact with the located elements

    public void enterUsername(String username) {

                 usernameInput.sendKeys(username);

    }

    public void clickSubmitButton() {

                 submitButton.click();

    }

}

In this example:

@FindBy(xpath = "//input[@id='username']") is used to locate an input element with the id attribute set to "username."

@FindBy(css = "button[type='submit']")is used to locate a button element with the type attribute set to "submit."

 

The PageFactory.initElements(driver, this) initializes the WebElements with the annotated locators.

In the test script, we can then create an instance of ‘HomePage’ and use its methods to interact with the elements. That is,  In test class, instantiate the HomePage class and call the methods like enterUsername(), clickSubmitButton().

 

public class HomePageTest {

   @Test

   Public void homePageMehtod(){

        WebDriver driver = new ChromeDriver();

            driver.get("https://testingQa.com");

            HomePage homePage = new HomePage(driver);

          // Use the methods from the page class

           homePage.enterUsername("exampleUser");

           homePage.clickSubmitButton();

           // Perform additional test steps or assertions

          driver.quit();

}

}

Using @FindBy helps make home Page Object classes more maintainable and readable by keeping the locators centralized within the class.

How is the try-catch block utilized in Selenium WebDriver?

In Selenium WebDriver, a try-catch block is commonly used to handle exceptions that may occur during the execution of test scripts.

​

import org.openqa.selenium.By;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.WebElement;

import org.openqa.selenium.chrome.ChromeDriver;

public class TryCatchBlockExample {

    public static void main(String[] args) {

        // Set the path to the ChromeDriver executable

          System.setProperty("webdriver.chrome.driver", "path/to/chromedriver");

                 // Initialize the ChromeDriver

            WebDriver driver = new ChromeDriver();

        try {

              // Navigate to a website

              driver.get("https://example.com");

          // Locate an element (assuming it's present on the page)

            WebElement element = driver.findElement(By.id("someElementId"));

            // Perform an action on the element

              element.click();

              }

             catch (Exception e) {

            // Handle the exception

           System.err.println("An exception occurred: " + e.getMessage());

         } finally {

            // Perform any cleanup or closing actions

         driver.quit();

        }

    }

}

Provide an explanation of the DesiredCapabilities class in Selenium WebDriver?

The DesiredCapabilities class in Selenium WebDriver is used to configure and set various properties for the WebDriver browser instances. It allows to customize the behavior of the browser or WebDriver session before initiating it. Some common use cases for DesiredCapabilities include setting browser-specific properties, managing timeouts, and enabling or disabling certain features. Eg., to launch Chrome with specific options

 

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.chrome.ChromeDriver;

import org.openqa.selenium.remote.DesiredCapabilities;

 

public class DesiredCapbilitiesExample {

             public static void main(String[] args) {

                         // Set the path to the ChromeDriver executable

                 System.setProperty("webdriver.chrome.driver", "path/to/chromedriver");

                  // Create DesiredCapabilities for Chrome

               DesiredCapabilities capabilities = DesiredCapabilities.chrome();

               // Create ChromeOptions

               ChromeOptions   chromeOptions = new ChromeOptions();

                   chromeOptions.setCapability("version", "119");

                   chromeOptions.setCapability("platform", "Windows");

                      // Set specific Chrome options if needed

                  capabilities.setCapability("chromeOptions", "value");

                // Initialize ChromeDriver with DesiredCapabilities

                 WebDriver driver = new ChromeDriver(capabilities);

                          driver.get("https://www.amazon.com/");

                        // Close the browser

                  driver.quit();

    }

}

Extent Reports vs TestNG reports

​

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Test NG Soft Assertions vs Hard Assertions

​

​

​

​

​

​

​

​

​

​

​

​

​

​

​

​

​

​

​

​

driver.close() vs driver.quit()

​

​

​

​

​

​

​

​

​

​

​

​

​

​

​

​

 

WebDriverWait
WebDriverWait is a part of the Selenium WebDriver library in various programming languages (such as Java, Python, C#, etc.). It provides a way to dynamically wait for a certain condition to be met before proceeding with the execution of the test script. This is particularly useful in scenarios where elements on a web page might load asynchronously or might take some time to appear.
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class Example {
public static void main(String[] args) {
            // Setup and configure ChromeDriver using WebDriverManager
               WebDriverManager.chromedriver().setup();
          // Create a WebDriver instance (in this case, ChromeDriver)
              WebDriver driver = new ChromeDriver();
          // Navigate to a web page
              driver.get("https://Software testing. com");
         // Create a WebDriverWait instance with a timeout of 10 seconds
             WebDriverWait wait = new WebDriverWait(driver, 10);
        // Example: Wait until an element with the specified locator is visible
            WebElement element=wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("exampleId")));      

         // Perform actions with the found element
             element.click();
           // Close the browser window
             driver.quit();
}
}


WebDriverManager
The WebDriverManager library is a Java library that simplifies the management of WebDriver binaries
(such as ChromeDriver, GeckoDriver, etc.) in the Selenium WebDriver projects. The line
WebDriverManager.chromedriver().setup(); specifically is used for setting up and configuring the ChromeDriver.

Dependency:

 

​

​

 

 

 

 

Setting Up ChromeDriver
The line WebDriverManager.chromedriver().setup(); automatically downloads the appropriate version of ChromeDriver based on the system configuration (Windows, Linux, macOS) and the version of the Chrome browser installed on the machine.It manages the driver executable's download, caching, and setup, eliminating the need for manual downloading and updating of WebDriver binaries.

Usage in a Selenium Project
     Once the setup is done, one can create an instance of ChromeDriver without specifying the path to the
ChromeDriver executable. WebDriverManager takes care of providing the correct path.


import io.github.bonigarcia.wdm.WebDriverManager;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
  public class Example {
  public static void main(String[] args) {
        // Setup and configure ChromeDriver using WebDriverManager 

            WebDriverManager.chromedriver().setup();
      // Create an instance of ChromeDriver
            WebDriver driver = new ChromeDriver();
            driver.get(“https://www.amazon.com/”)
     // Close the browser window
            driver.quit();
}
}
This approach is convenient as it ensures that the appropriate version of ChromeDriver is used without the need for manual intervention. It also makes automation framework/Selenium projects more portable across different environments.

What is an Object Repository in page Object design pattern?
                  In the context of the Page Object design pattern, an Object Repository is a central storage location for the various elements and components of a web page or application user interface. The main purpose of an Object Repository is to keep the page-specific elements separate from the test code, promoting better maintainability and reusability of the code.

                 The Object Repository typically contains information about the web elements on a page,such as buttons, text fields, dropdowns, etc. Each web element is identified by a unique name or identifier, and associated properties like XPath, CSS selector, ID, etc., which are used to locate and interact with the element on the page.
                 By maintaining a centralized Object Repository, if there are changes to the structure or layout of the web page, you only need to update the repository rather than modifying multiple instances of the test code. This makes the code more modular and easier to maintain.
       

        public class LoginPage {
                // Object Repository
               public static final String USERNAME_FIELD = "username";
               public static final String PASSWORD_FIELD ="password";
               public LoginPage(WebDriver driver){
                   this.driver=driver;
                   PageFactory.initElements(driver,this);
                 }
   @FindBy(name ="userName")
      WebElement userName;
  @FindBy(id = "Password")
     WebElement password;
  @FindBy(css= "#SubmitButton")
     WebElement submitButton;
           // Methods related to the login page
              public void enterUsername(String username) {
                    userName.sendKeys(USERNAME_FIELD);
               }
              public void enterPassword(String password) {
                     password.sendKeys(PASSWORD_FIELD);
               }
              public void clickLoginButton() {
                     submitButton.click();
               }
        }

What normalize-space () does?
              XPath expressions that use normalize-space () are often used in web scraping, data extraction, and testing scenarios to locate and compare text values in HTML documents that may have inconsistent whitespace. This function ensures that you can effectively match or extract text content, regardless of variations in whitespace formatting.


             1. Trims Leading and Trailing Whitespace ie., removes any leading and trailing spaces, tabs, or
newline characters from the input string.
             2. Collapses Multiple Spaces, It replaces consecutive white space characters (e.g., multiple
spaces or tabs) within the string with a single space character.


Example:
//button[normalize-space()='Login']
this XPath expression would select the <button> element with the exact text content "Login"
//button : buttonelement in the HTML document
[normalize-space()='Login']:

It checks if the normalized text content of the <button> element is equal to "Login".
 

    //span[normalize-space(text ())='My Account']
    //span[contains(normalize-space (),'My Account')]
    //span[normalize-space ()='My Account']
    //span[text ()[normalize-space ()= 'My Account']
    //a[normalize-space()='Login']

What are locators in Selenium?
In Selenium, locators are used to identify and locate web elements on a web page so that the automation scripts can interact with them. Locators provide a way to specify how Selenium should find and interact with the HTML elements on a webpage. Selenium supports various types of locators, each with its own way of identifying and locating elements.


ID: The id attribute of an HTML element is unique on a page.
One can Use it to locate an element using driver.findElement(By.id("elementId")).
               Eg., WebElement element = driver.findElement(By.id("username"));


Name: You can locate elements by their name attribute using
             driver.findElement(By.name("elementName")).
               Eg., WebElement element = driver.findElement(By.name("password"));

 

ClassName: The class attribute is used to locate elements using
             driver.findElement(By.className("className")).

              Eg., WebElement element = driver.findElement(By.className("loginButton"));
 

TagName: You can locate elements by their HTML tag name using
            driver.findElement(By.tagName("tagName"))
              Eg., WebElement element = driver.findElement(By.tagName("a"));

 

Link Text and Partial Link Text: These locators are used for locating hyperlinks (<a> elements).
               Link Text is the exact text of the link, and Partial Link Text is a partial match of the link text.
                  Eg., WebElement element = driver.findElement(By.linkText("Login"));

                                                                     // or

                  Eg., WebElement element = driver.findElement(By.partialLinkText("Log"));
 

XPath: XPath is a powerful locator that allows to navigate through the XML structure of an HTML document. It can be used like this: 

                  Eg.,WebElement element=driver.findElement(By.xpath("//input[@id='username']")); 

                                                                                                                                                                               

CSS Selector: CSS selectors are patterns used to select elements in an HTML document.
                  Eg.,WebElement element=driver.findElement(By.cssSelector("input#username"));

How do you employ Selenium to perform file uploads?
              To upload a file using Selenium, you can use the sendKeys method on the WebElement representing the file input element. The sendKeys method allows you to specify the path of the file you want to upload.


import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
            public class FileUploadExample {
            public static void main(String[] args) {
            // Set the path to the chromedriver executable
                   System.setProperty("webdriver.chrome.driver", "path/to/chromedriver");
            // Initialize the ChromeDriver
                   WebDriver driver = new ChromeDriver();
            // Navigate to the web page with the file upload functionality
                   driver.get("https://the-internet.herokuapp.com/upload");

            // Locate the file input element using its ID, Name, XPath, or other locators
                   WebElement fileInput = driver.findElement(By.id("fileInputId"));
            // Specify the path of the file you want to upload
                   String filePath = "path/to/your/file.txt";
            // Use sendKeys to set the file path in the file input element
                  fileInput.sendKeys(filePath);
            // Close the browser
                 driver.quit();
              }
           }

​

Selenium3 vs Selenium4

​

​

​

​

​

​

​

​

​

​

​

​

​

​

​

​

​

Desired capabilities

  • A set of configuration options

  • Defines basic test requirements or how a specific browser should behave during automated testing 

  • Include details like the browser name, version, platform, and additional settings such as proxy,

  • timeouts, logging, mobile

  • emulation, and SSL certificates

  • Used to perform cross browser testing of web applications.

  • Stored as key-value pairs encoded in a JSON object

​

Initialize chrome Driver using Desired Capabilities Class

               *   DesiredCapabilities capabilities = DesiredCapabilities.Chrome();

               *   capabilities.setCapability(CapabilityType.BROWSER_NAME, "Chrome");

               *   capabilities.setBrowserName();

               *   capabilities.getBrowserName();

               *   capabilities.setVersion();

               *   capabilities.getVersion();

               *   capabilities.setPlatform();

               *   capabilities.getPlatform();

                 capabilities.setCapability();

               *   capabilities.getCapability();

This code is typically used when configuring the capabilities of the Selenium WebDriver for the Chrome browser. Setting Desired Capabilities is often not required for the latest versions of Selenium WebDriver, as the browser-specific options are usually provided through their respective classes (e.g., ChromeOptions for Chrome).  We can use the ChromeOptions class for more flexibility

​

     import org.openqa.selenium.chrome.ChromeOptions;

     import org.openqa.selenium.WebDriver;

     import org.openqa.selenium.chrome.ChromeDriver;

​

     ChromeOptions options = new ChromeOptions();

            // Add any desired options here using the setCapability method if needed

     WebDriver driver = new ChromeDriver(options);

​

Chrome Options Class

It is Used to manipulate various properties of the Chrome driver.

​

It is Used to manipulate various properties of the Chrome driver.

 

  ChromeOptions options = new ChromeOptions();

        options.addArguments("start-maximized");

        options.addArguments("--incognito");

        options.addArguments("--disable-infobars");

        options.addArguments("--window-position=100,100");

        options.addArguments("--window-size=1280,1024");

        options.addArguments("--disable-notifications");

        options.setHeadless(true);

   ChromeDriver driver = new ChromeDriver(options);

How can pass both ChromeOptions and DesiredCapabilities to the driver?

DesiredCapabilities capabilities = DesiredCapabilities.chrome();

    ChromeOptions options = new ChromeOptions();

        options.addArguments("start-maximized");

        options.addArguments("--incognito");

        options.addArguments("--disable-infobars");

       options.setBinary("C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe");

capabilities.setCapability(ChromeOptions.CAPABILITY, options);

webDriver driver = new ChromeDriver(capabilities);

Difference between DesiredCapabilities and ChromeOptions?

​

​

​

​

 

Difference between UI testing and API testing

​

​

​

​

​

​

​

​

​

​

​

​

​

​

​

​

​

​

What are the different ways for refreshing the page using Selenium WebDriver?
// Refresh the current web page
                                  driver.navigate().refresh();
refresh(): The refresh() method, belonging to the Navigation interface, is used to reload the current page. When this method is called, the browser will re-fetch the page content from the server, and any changes made since the last request will be discarded.

// Refresh the page using the current URL
                                  driver.get(driver.getCurrentURL());
         driver.getCurrentURL() retrieves the current URL.
driver.get(driver.getCurrentURL()) then navigates to that same URL, effectively refreshing the page

// Reload the page by navigating to the current URL
                                  driver.navigate().to(driver.getCurrentURL());
driver.getCurrentURL() retrieves the current URL.
driver.navigate().to(driver.getCurrentURL()) then navigates to that same URL, effectively reloading the page.

// Refresh the page using the F5 key
                                  Actions actions=new Actions(driver);
                                  actions.sendKeys(Keys.F5).build().perform();

This code creates an Actions object, sends the F5 key, and then performs the action. 
The perform() method is necessary to execute the sequence of actions.

// Refresh the current page using JavaScript
                                  JavascriptExecutor js=(JavascriptExecutor)driver
                                  js.executeScript("window.location.reload();");

The executeScript method is used to execute JavaScript code, and in this case, it's reloading the current page using window.location.reload().

Slide1_edited.jpg
Slide2_edited.jpg
Slide3_edited.jpg

<dependency>         <groupId>io.github.bonigarcia</groupId>       <artifactId>webdrivermanager</artifactId>               <version>5.0.3</version>   

 <scope>test</scope>

</dependency>

Slide1.JPG
Slide3_edited.jpg
Slide1_edited.jpg
Slide2_edited.jpg
bottom of page