Selenium Interview Questions and Answers

Are you preparing for an interview for a Selenium automation testing Job in 2025? Whether you're just a beginner in Selenium or have 3 Years, 5 years, or 10 years of experience in automation testing, being well-prepared before an interview can make all the difference. Selenium is universally used and one of the most popular automation testing tools, and companies are always looking for skilled testers and developers who have a strong understanding of it. 

To help you prepare, I have compiled a set of commonly asked Selenium interview questions and answers based on actual Selenium automation problems and industry best practices. I have automated several projects and have assisted teams in resolving real-world problems with Selenium automation. These are real answers drawn from real experience because I know what works and what does not in real life.

No matter what level of knowledge a person has, these questions seem to encapsulate everything from basic core understanding to advanced level framework building tasks done by a test automation engineer. Whether you are looking for a QA engineer position, test automation developer, or an SDET, this information will definitely help you in your next interview.

Basic Selenium Interview Questions

1. What is Selenium?

Selenium is a free automation testing tool that was initially developed by Jason Huggins. It is used to test web applications on different browsers and platforms. It is not only a browser automation tool, but you can automate your web-based repetitive tasks as well using Selenium.

You can use it to automate testing across several programming languages to develop test scripts. It also supports cross-browser and cross-platform testing using Selenium Grid. You can run Selenium tests on different browsers like Chrome, Firefox, Edge, Opera, and Safari to check browser compatibility. Also, you can run test scripts on different OS easily like Windows, Linux, and mac OS. 

Unlike other automation tools, it interacts with browsers natively just like a real user. So it is easy to find UI level bugs as well.

2. What are the different components of Selenium?

Selenium consists of four main components:
  • Selenium IDE – Shinya Kasatani developed it in 2006. Selenium IDE is an easy-to-use, open source browser extension that is used to record and play back test scripts.
  • Selenium WebDriver – Selenium WebDriver is a very popular and powerful tool for programmatically automating browser interactions.
  • Selenium Grid – Used for parallel execution of tests across multiple machines and browsers.
  • Selenium RC (Deprecated) – The old version of Selenium WebDriver.

3. How does Selenium WebDriver work?

Selenium WebDriver interacts with the browser using a browser-specific driver, i.e. ChromeDriver for Chrome, geckodriver for Firefox, etc. Selenium 3 was using JSON Wire Protocol to communicate with browsers. However, the newer version, Selenium 4, primarily uses the W3C WebDriver protocol to send commands and automate actions like clicking, typing, and navigating web pages.

4. What are the advantages of using Selenium for automation testing?

Here are the main advantages that you can explain to the interviewer.
  • Cost Effective: It is open-source and free, which is the main advantage.
  • Multi Language Support: No language specific dependency. It supports multiple programming languages.
  • Platform Independent: No browser specific dependency. It supports multiple browsers.
  • Saves Time: Selenium Grid allows for parallel test execution, which can save you significant time.
  • Flexible & Easy Integration: Works with various testing frameworks (TestNG, JUnit, NUnit, Jenkins CI/CD, etc.)
  • Active Community Support: Wide community support. Easy to find solutions online.
  • Automate Tests as a Real User Do: It interacts with browsers directly. Same as a real user does.
  • Create Framework As per Your Convenience: You can create different frameworks like data-driven, keyword-driven, Hybrid, etc, easily, as per your requirement.

5. What are the limitations of Selenium?

Main limitations are
  • Cannot automate desktop applications.
  • Limited support to test mobile apps (needs Appium for that)
  • No built-in reporting feature.
  • Cannot handle captchas and OTPs directly
  • It is challenging to handle pop-ups and dynamic web elements in Selenium.

6. What programming languages does Selenium support?

Selenium supports Java, Python, C#, Ruby, and JavaScript.

7. What types of applications can Selenium automate?

It can automate web applications only. You can test mobile apps with the help of Appium. You need third-party tools to automate desktop applications.

8. How do you set up Selenium WebDriver in a project?

  • Download and install Java or Python.
  • Install Eclipse or PyCharm IDE as per the programming language you are working on.
  • Install Selenium WebDriver using Maven (Java) or pip (Python).
  • Download the required browser driver (e.g., ChromeDriver for Chrome).
  • Write and execute your test script.
  • 9. What are the different locators in Selenium?

    Selenium provides 8 locators to find web elements:
    • ID – driver.findElement(By.id("username"))
    • Name – driver.findElement(By.name("email"))
    • Class Name – driver.findElement(By.className("login-btn"))
    • Tag Name – driver.findElement(By.tagName("input"))
    • Link Text – driver.findElement(By.linkText("Click Here"))
    • Partial Link Text – driver.findElement(By.partialLinkText("Click"))
    • CSS Selector – driver.findElement(By.cssSelector("#login"))
    • XPath – driver.findElement(By.xpath("//input[@id='password']"))

    10. What is the difference between findElement() and findElements()?

    findElement() method will return a single Web Element (throws an error if element not found)

    Example: WebElement element = driver.findElement(By.id("login")); // Returns a single element.

    findElements() method is used to get a list of Web Elements (returns an empty list if element not found).

    Example: List<WebElement> elements = driver.findElements(By.tagName("a")); // Returns a list of links  

    11. What is the difference between driver.get() and driver.navigate().to()?

    driver.get("URL"): You can use it to load a new webpage and wait until it’s fully loaded.

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

    driver.navigate().to("URL") – It is similar to the get() method, but provides additional navigation features like back, forward, and refresh.

    Example: driver.navigate().to("https://example.com");

    12. How do you handle browser navigation in Selenium?

    We can use the navigate() method for browser navigations.

    Examples:

    To go back to the previous page, we can use driver.navigate().back(); 

    We can use driver.navigate().forward(); to go forward.

    This syntax is used to refresh the page: driver.navigate().refresh(); 

    13. How do you handle different types of waits in Selenium?

    We mainly use 3 types of waits in Selenium tests as below.

    1. Implicit Wait

    Implicit wait is used to wait for elements globally.

    Example of Implicit Wait: Given syntax will wait for 10 seconds while page is loading.

    driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

    2. Explicit Wait

    Explicit wait is used to wait for specific conditions.

    Example of Explicit Wait: Given syntax will wait for 10 seconds for the element with the 'login' id to be visible.

    WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
    wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("login")));

    3. Fluent Wait

    Similar to Explicit Wait but with polling intervals.

    14. What is the difference between implicit wait and explicit wait?

    The main differences between implicit and explicit wait are given below.

    Implicit Wait

    Applies to: All elements globally.
    Usage: driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
    Checks conditions?: No

    Explicit wait

    Applies to: Specific elements
    Usage: WebDriverWait wait = new WebDriverWait(driver, 10);
    Checks conditions?: Yes (e.g., element visibility, clickable, etc.)

    15. What is a Fluent Wait in Selenium?

    A Fluent Wait in Selenium is a type of dynamic wait that allows you to specify 
    1. The maximum amount of time to wait for a condition, 
    2. The polling frequency.
    3. Ignoring specific exceptions while waiting.
    Example
    Wait<WebDriver> wait = new FluentWait<>(driver)
        .withTimeout(Duration.ofSeconds(10))
        .pollingEvery(Duration.ofSeconds(1))
        .ignoring(NoSuchElementException.class);

    16. How do you handle pop-ups and alerts in Selenium?

    We can handle pop-ups and alerts using the Alert interface. We can use the accept() method to accept or click on the OK button, the dismiss() method to dismiss/cancel the alert. Also, it is possible to type text in the text field of alert using sendKeys() method.

    Here is an example.

        Alert alert = driver.switchTo().alert();
        alert.accept(); // Click OK  
        alert.dismiss(); // Click Cancel  
        alert.sendKeys("Hello"); // Send text  

    17. How do you work with multiple browser windows in Selenium?

    We can use the getWindowHandles() method to switch between windows.

    Example:

        String mainWindow = driver.getWindowHandle();
            for (String window : driver.getWindowHandles()) {
            driver.switchTo().window(window);
        }
    

    18. What is the difference between switchTo().window() and switchTo().frame()?

    Difference between switchTo().window() and switchTo().frame() is as below.
    • switchTo().window("windowID"): It is used to switch between browser tabs/windows.
    • switchTo().frame("frameID"): It is used to switch to an iframe on the page.

    19. How do you handle dropdowns in Selenium?

    We can use the Select class to handle alerts in Selenium. Here is an example on how to select dropdown options using visible text, value, and index.

        Select dropdown = new Select(driver.findElement(By.id("dropdown")));
        dropdown.selectByVisibleText("Option 1");
        dropdown.selectByValue("option1");
        dropdown.selectByIndex(0);

    20. How do you select a value from a dropdown using Selenium?

    There are three ways to select a value from a dropdown.
    1. selectByVisibleText("Option")
    2. selectByValue("option1")
    3. selectByIndex(0)

    Example:

    Select dropdown = new Select(driver.findElement(By.id("dropdown")));
    dropdown.selectByVisibleText("Java");

    Selenium WebDriver Questions

    21 What is WebDriver in Selenium?

    Selenium WebDriver is a browser automation framework. Simply, it automates the browsers. It is open-source so you can use it for free. It allows you to interact with web applications just like a real user. It acts as a mediator to send commands to web browsers and execute actions like clicking buttons, typing text in a textbox, navigating between pages, and many more actions.

    Here are key features of WebDriver:

    • It can directly communicate with the browser.
    • It supports multiple browsers like Chrome, Firefox, Edge, Safari, etc.
    • Works with multiple programming languages like Java, Python, C#, JavaScript, etc.
    • You can easily use it on different OS like Windows, Linux, and Mac.
    WebDriver is one of the most commonly used components of Selenium framework. You can use it to perform UI testing, regression testing, functional testing, cross-browser testing, database testing, and parallel testing.

    You can read this article to read more about WebDriver in Selenium.

    22. How do you launch different browsers in Selenium WebDriver?

    I am using the browser-specific driver executable to launch the browser in Selenium test. I am using Chromedriver to run tests in Google Chrome browser, GeckoDriver for Mozilla Firefox browser, and EdgeDriver to launch tests in Edge browser. Here is a detailed guide on how to download and configure ChromedriverGeckoDriver, and EdgeDriver to use them in Selenium WebDriver.

    Here are the examples to launch different browsers in Selenium WebDriver test.

    Example to launch Chrome browser in Selenium
            WebDriver driver = new ChromeDriver();
            driver.get("https://example.com");
    Example to launch Firefox browser in Selenium
            WebDriver driver = new FirefoxDriver();
            driver.get("https://example.com");
    Example to launch Edge browser in Selenium
            WebDriver driver = new EdgeDriver();
            driver.get("https://example.com");
    Example to launch Safari browser in Selenium
            WebDriver driver = new SafariDriver();
            driver.get("https://example.com");

    23. What is the difference between WebDriver and RemoteWebDriver?

    WebDriver is an interface in Selenium that allows communication directly with browsers. You can use browser-specific drivers like ChromeDriver, GeckoDriver, or EdgeDriver, to execute commands on browsers in the local system.

    On the other hand, RemoteWebDriver is a class that enables running Selenium tests on a remote machine. It communicates with the remote browser using the W3C WebDriver Protocol (previously JSON Wire Protocol in older Selenium versions). Generally, we use RemoteWebDriver to perform distributed testing, Selenium Grid, and cloud-based automation on platforms like BrowserStack and Sauce Labs.

    Key Differences:

    1. Execution Location:
      • WebDriver executes Selenium tests on the local machine.
      • RemoteWebDriver runs tests remotely on another machine or cloud service.
    2. Communication Protocol:
      • WebDriver directly interacts with the browser drivers.
      • RemoteWebDriver executes Selenium commands using the W3C WebDriver Protocol over HTTP.
    3. Use Case:
      • WebDriver is best for local automation on a single browser instance.
      • You can use RemoteWebDriver to perform parallel execution across multiple machines in Selenium Grid or cloud testing services.

    Example of WebDriver (Local Execution)

            WebDriver driver = new ChromeDriver();
            driver.get("https://example.com");

    Example of RemoteWebDriver (Remote Execution)

            URL remoteUrl = new URL("http://192.168.1.100:4444"); // Selenium Grid URL
            ChromeOptions options = new ChromeOptions(); // Use browser options instead of DesiredCapabilities
    
            WebDriver driver = new RemoteWebDriver(remoteUrl, options);
            driver.get("https://example.com");

    24. How do you maximize a browser window in Selenium?

    In Selenium WebDriver, there are two ways to maximize window size. 1) You can use the maximize_window() method, and 2) You can use the setSize() method to manually set the maximized size as per your screen size. If you are using Headless Browsers, you can use addArguments("--start-maximized") to maximize window size.

    Let's see examples

    Example of Maximizing window using maximize_window() method

        // Set up the WebDriver (Make sure ChromeDriver path is set in system properties)
        WebDriver driver = new ChromeDriver();
    
        // Open a website
        driver.get("https://www.example.com");
    
        // Maximize the browser window
        driver.manage().window().maximize();
    
        // Perform any test actions...
    
        // Close the browser
        driver.quit();
    

    Here, driver.manage().window().maximize(); syntax will maximize the window.

    Example of Maximizing window using setSize() method
           WebDriver driver = new ChromeDriver();        
           driver.manage().window().setSize(new Dimension(1200, 800));

    If your screen size is 1200 x 800, then you can use the .setSize() method to maximize the window.

    Example of Maximizing window in Headless Browsers using addArguments("--start-maximized")

            WebDriver driver;
    	FirefoxOptions options=new FirefoxOptions();
    	//To open  browser in Headeless mode.
    	options.addArguments("--headless");	
    	//To open headless browser maximized.
    	options.addArguments("--start-maximized");
    	driver = new FirefoxDriver(options);

    The above example explains how to start a headless browser maximized.

    Tips: You should run Selenium tests in a full-screen environment to prevent UI interaction issues.

    25. How do you take a screenshot in Selenium WebDriver?

    We can use the TakesScreenshot interface to capture a screenshot while running the Selenium test.

    Example to take a Screenshot and Save as a File in Selenium

    package com.secondpr;
    import org.openqa.selenium.*;
    import org.openqa.selenium.chrome.ChromeDriver;
    import java.io.File;
    import java.io.IOException;
    import org.apache.commons.io.FileUtils;
    
    public class takeScreenShot {
    
    	public static void main(String[] args) {
    	// Set up WebDriver
            WebDriver driver = new ChromeDriver();
    
            try {
                // Open a website
                driver.get("https://www.example.com");
    
                // Take a screenshot
                TakesScreenshot ts = (TakesScreenshot) driver;
                File source = ts.getScreenshotAs(OutputType.FILE);
    
                // Define destination path
                File destination = new File("D:\\homePageScreenshot.png");
    
                // Copy file to the destination
                FileUtils.copyFile(source, destination);
    
                System.out.println("Screenshot saved successfully!");
            } catch (IOException e) {
                System.out.println("Error while saving screenshot: " + e.getMessage());
            } finally {
                // Close the browser
                driver.quit();
            }
    	}
    }
    
    Note: You need to add external binary jars of commons-io. You can download the latest jars from the Apache Commons IO Download page.

    26. How do you get the title of a webpage in Selenium?

    In Selenium WebDriver, you can get the title of a webpage using the getTitle() method.

    Example to get webpage title:

            // Get and print the title of the webpage
            String pageTitle = driver.getTitle();
            System.out.println("Page Title: " + pageTitle);
    Here, driver.getTitle(); retrieves the title of the current webpage. It is useful to validate if the correct page is loaded during automation testing. Generally, this method is used to assert the expected title in test cases.

    27. How do you get the current URL of a webpage?

    In Selenium WebDriver, you can use the getCurrentUrl() method to get the current URL of a webpage.

    Example to get current URL of WebPage:
            // Get and print the current URL
            String currentURL = driver.getCurrentUrl();
            System.out.println("Current URL: " + currentURL);
    In the above example, driver.getCurrentUrl() method will return the current URL of the webpage. You can use it to validate or assert that the correct page is loaded.

    28. How do you handle cookies in Selenium WebDriver?

    In Selenium WebDriver, you can use getCookies(), addCookie(), getCookieNamed(), deleteCookieNamed(), and deleteAllCookies() methods to add, retrieve, delete, and clear cookies.

    An example to manage cookies

    package com.secondpr;
    
    import org.openqa.selenium.WebDriver;
    import org.openqa.selenium.chrome.ChromeDriver;
    import org.openqa.selenium.Cookie;
    import java.util.Set;
    
    public class manageCookies {
    
    	public static void main(String[] args) {
    		
    		WebDriver driver = new ChromeDriver();
    
            // Open a website
            driver.get("https://only-testing-blog.blogspot.com/");
    
            // 1. Get all cookies
            Set<Cookie> allCookies = driver.manage().getCookies();
            System.out.println("All Cookies: " + allCookies);
    
            // 2. Get a specific cookie by name
            Cookie specificCookie = driver.manage().getCookieNamed("session_id");
            System.out.println("Session Cookie: " + specificCookie);
    
            // 3. Add a new cookie
            Cookie newCookie = new Cookie("test_cookie", "123456");
            driver.manage().addCookie(newCookie);
            System.out.println("Added new cookie: " + newCookie);
            
            // 4. Delete a specific cookie
            driver.manage().deleteCookieNamed("test_cookie");
            System.out.println("Deleted 'test_cookie'");
    
            // 5. Delete all cookies
            driver.manage().deleteAllCookies();
            System.out.println("All cookies deleted");
    
            // Close the browser
            driver.quit();	}
    
    }
    

    Explanation of Cookie Handling Methods

    • driver.manage().getCookies(); → Fetches all cookies.
    • driver.manage().getCookieNamed("cookie_name"); → Retrieves a specific cookie by name.
    • driver.manage().addCookie(new Cookie("name", "value")); → Adds a new cookie.
    • driver.manage().deleteCookieNamed("cookie_name"); → Deletes a specific cookie.
    • driver.manage().deleteAllCookies(); → Clears all cookies.
    Why Handle Cookies in Selenium?
    • To maintain user sessions without logging in repeatedly.
    • Test authentication by manually adding session cookies.

    29. How do you delete all cookies using Selenium?

    You can use the deleteAllCookies() method for it as described in the example of the previous question's answer.

    30. What is the difference between close() and quit()?

    Here are the Main differences between close() and quit() methods.
    • Functionality:
      • close(): Closes the current browser window.
      • quit(): Closes all browser windows opened by Selenium.
    • Scope:
      • close(): Only the active browser window is closed.
      • quit(): All browser sessions initiated by WebDriver are closed.
    • WebDriver Instance:
      • close(): WebDriver session remains active if multiple windows exist.
      • quit(): WebDriver session is terminated completely.
    • Usage
      • close(): Used when handling multiple windows/tabs and only one needs to be closed.
      • quit(): Used when the entire test execution is complete and no further actions are needed.
    Tips: You can use close() when you want to close only the current window but keep WebDriver running. But you can use the quit() method to close all browser windows and end the WebDriver session.

    Best Practice: Always use quit() at the end of the test execution to avoid memory leaks!

    31. How do you handle JavaScript alerts in Selenium?

    There are three types of JavaScript alerts:
    • Simple Alert → Only has an "OK" button.
    • Confirmation Alert → Has "OK" and "Cancel" buttons.
    • Prompt Alert → Has a text box, along with "OK" and "Cancel" buttons.

    Here is an explanation on how to manage alerts in Selenium.

    Switch to alert:
    You can use the given syntax to switch Selenium test execution on alert.
    Alert alert = driver.switchTo().alert();

    Accepting an Alert (OK Button)
    alert.accept(); // Clicks "OK" button.

    Dismissing an Alert (Cancel Button)
    alert.dismiss(); // Clicks "Cancel" button.

    Getting the Alert Message
    String alertText = alert.getText();
    System.out.println("Alert Message: " + alertText);

    Handling Prompt Alert (Entering Text)
    alert.sendKeys("Test Input"); // Enter text in the alert box
    alert.accept(); // Clicks "OK" button.

    Handling alerts is important for pop-ups, form validations, and confirmations in test automation.

    32. How do you perform drag and drop in Selenium?

    In Selenium, you can use the Actions class to perform drag and drop actions.

    Here is an example of drag and drop

    package com.secondpr;
    
    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.interactions.Actions;
    
    public class dragDrop {
    
    	public static void main(String[] args) {
    	// Set up WebDriver
            WebDriver driver = new ChromeDriver();
    
            // Open a website with drag-and-drop functionality
            driver.get("https://jqueryui.com/droppable/");
    
            // Switch to iframe if the elements are inside one
            driver.switchTo().frame(0);
    
            // Locate source (element to be dragged) and target (element where to drop)
            WebElement source = driver.findElement(By.id("draggable"));
            WebElement target = driver.findElement(By.id("droppable"));
    
            try {
    			Thread.sleep(2000);
    		} catch (InterruptedException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		}
            // Perform drag and drop
            Actions actions = new Actions(driver);
            actions.dragAndDrop(source, target).perform();
            
            try {
    			Thread.sleep(1000);
    		} catch (InterruptedException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		}
    
            System.out.println("Drag and drop successful!");
    
            // Close browser
            driver.quit();
    	}
    }
    
    The above example will drag an element from the source and drop it on the destination. Try it.

    Other Ways to Perform Drag and Drop

    Using clickAndHold(), moveToElement(), and release(). You can use this method when dragAndDrop() doesn’t work due to JavaScript interference.

    Example:

    actions.clickAndHold(source)
                .moveToElement(target)
                .release()
                .build()
                .perform();

    Using moveByOffset() (Dragging to Specific Coordinates). You can use it when drop location is dynamic or doesn’t have a unique identifier.

    Example

    actions.clickAndHold(source)
               .moveByOffset(100, 50) // Move by X and Y offset
               .release()
               .perform();
    Tips
    • Use dragAndDrop(source, target).perform(); for standard cases.
    • Use clickAndHold(), moveToElement(), and release() if dragAndDrop() doesn’t work.
    • Use moveByOffset(x, y) for pixel-based movement.
    • Always switch to the iframe first if elements are inside it.
    You can use drag and drop for file uploads, game testing, and UI interactions.

    33. How do you simulate keyboard and mouse actions in Selenium?

    You can use Actions and Robot classes to simulate keyboard and mouse actions.

    Using Actions Class (Recommended)

    Mouse Actions Example

        Actions actions = new Actions(driver);
        actions.moveToElement(element).perform();  // Hover  
        actions.contextClick(element).perform();   // Right-click  
        actions.doubleClick(element).perform();    // Double-click

    Keyboard Actions

        actions.sendKeys(Keys.ENTER).perform();  // Press Enter  
        actions.keyDown(Keys.SHIFT).sendKeys("text").keyUp(Keys.SHIFT).perform();  // Type in uppercase  

    Using Robot Class (For Advanced Interactions)

    Keyboard Input

        Robot robot = new Robot();
        robot.keyPress(KeyEvent.VK_ENTER);
        robot.keyRelease(KeyEvent.VK_ENTER);

    Mouse Actions

        robot.mouseMove(500, 300);  // Move mouse  
        robot.mousePress(InputEvent.BUTTON1_DOWN_MASK);  // Left-click  
        robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK);

    Tips

    You can use the Actions class for web-based interactions, i.e. hover, right-click, drag & drop, keyboard inputs, and the Robot class for system-level interactions, i.e.. file uploads, screenshots, handling OS pop-ups. Actions class is preferred for browser-based automation, while Robot is used when Actions doesn't work.

    34. What is the Actions class in Selenium?

    The Actions class in Selenium performs advanced user interactions, such as mouse hover, right-click, double-click, drag-and-drop, and keyboard actions. It helps automate complex gestures that require a combination of keyboard and mouse events.

    Its key features include mouse actions, keyboard inputs, and composite gestures for seamless automation.

    35. What is the difference between Action and Actions class?

    Main differences between Action and Actions class are:
    • Type:
      • Action class: It is an Interface.
      • Actions class: It is a Class.
    • Purpose:
      • Action class: It represents a single action.
      • Actions class: It is used to build and perform a series of actions.
    • Usage:
      • Action class: It stores one action at a time.
      • Actions class: It has a chain of multiple actions together.
    Here is an example of the Action interface and the Actions class
    // Using Actions class to build and perform actions
    Actions actions = new Actions(driver);
    actions.moveToElement(element).click().perform(); // Hover and click
    
    // Using Action interface to store an action
    Action action = actions.moveToElement(element).click().build();
    action.perform(); // Perform stored action

    36. How do you simulate right-click in Selenium?

    We can simulate a right-click in Selenium using the contextClick() method from the Actions class.

    Example:

            WebElement element = driver.findElement(By.id("rightClickElement"));
            Actions actions = new Actions(driver);
            actions.contextClick(element).perform();  // Right-click action

    37. How do you simulate double-click in Selenium?

    You can perform a double-click in Selenium using the doubleClick() method from the Actions class.

    Here is an example:

            WebElement element = driver.findElement(By.id("doubleClickElement"));
    
            Actions actions = new Actions(driver);
            actions.doubleClick(element).perform();  // Double-click action
    

    38. How do you handle frames and iframes in Selenium?

    In Selenium, you can switch to a frame or iframe using the switchTo().frame() method. You can switch to frame using Index, name, or ID, or a WebElement.

    Here are examples using different methods:

    Example of switch to frame by Index:

        driver.switchTo().frame(0);  // Switch to the first frame
    
    Example of switch to frame by Name or ID:
        driver.switchTo().frame("frameName");  // Switch using frame name or ID
    
    Example of switch to frame by WebElement:
        WebElement frameElement = driver.findElement(By.tagName("iframe"));
        driver.switchTo().frame(frameElement);  // Switch using WebElement
    
    Example of Switch Back to Main Page:
    driver.switchTo().defaultContent();  // Exit from frame to main content
    

    39. How do you work with checkboxes and radio buttons in Selenium?

    In Selenium, you can interact with checkboxes and radio buttons using the click(), isSelected(), and getAttribute() methods.

    Here is an example of Selecting a Checkbox and Radio Button.

    WebElement checkbox = driver.findElement(By.id("subscribe"));
    checkbox.click();  // Click to select
    
    // Verify if checkbox is selected
    if (checkbox.isSelected()) {
        System.out.println("Checkbox is selected.");
    }
    
    WebElement radioButton = driver.findElement(By.id("genderMale"));
    radioButton.click();  // Select radio button

    40. How do you handle hidden elements in Selenium?

    You can not interact with hidden elements directly in Selenium. But, you can use the following methods to interact with them.

    JavaScript Executor (Force Click)

    JavascriptExecutor js = (JavascriptExecutor) driver;
    WebElement hiddenElement = driver.findElement(By.id("hiddenButton"));
    js.executeScript("arguments[0].click();", hiddenElement);

    Checking Visibility Before Action

    WebElement element = driver.findElement(By.id("hiddenElement"));
    if (element.isDisplayed()) {
        element.click();
    } else {
        System.out.println("Element is hidden");
    }

    Using Actions Class (For Hover to Reveal Elements)

    Actions actions = new Actions(driver);
    WebElement menu = driver.findElement(By.id("menu"));
    actions.moveToElement(menu).perform();  // Hover to make hidden element visible

    Selenium Automation Framework Questions

    41. What is a Selenium Framework?

    Types of Selenium Frameworks:

    Data-Driven Framework → Uses external data sources (Excel, CSV). You can use it to test multiple inputs without modifying scripts.

    String data = excelSheet.getCellData("TestData.xlsx", "Sheet1", 1, 1);
    
    Keyword-Driven Framework → Uses predefined keywords for test execution. It helps you to separate test logic from the script.
    executeAction("Click", "loginButton");

    Hybrid Framework → Combines Data-Driven + Keyword-Driven approaches. It works well for large-scale automation projects.

    Page Object Model (POM) → Organizes elements and actions into separate classes. It helps to improve code reusability & readability.

    LoginPage login = new LoginPage(driver);
    login.enterUsername("user");
    login.clickLogin();

    42. What are the different types of Selenium frameworks?

    Frameworks are already mentioned in the previous answer.

    43. What is the Page Object Model (POM) in Selenium?

    The Page Object Model (POM) is a design pattern that helps organize Selenium test scripts by separating UI elements and test logic into different classes. It enhances the usability, maintenance, and readability of test scripts.

    Key Advantages of POM:

    • Helps to reduce duplicate code.
    • Enhances test script readability.
    • Easy to maintain test scripts when UI changes.
    Example of POM:

    Create a Page Class (LoginPage.java)

    import org.openqa.selenium.WebDriver;
    import org.openqa.selenium.WebElement;
    import org.openqa.selenium.By;
    
    public class LoginPage {
        WebDriver driver;
    
        // Locators
        By username = By.id("user");
        By password = By.id("pass");
        By loginButton = By.id("login");
    
        // Constructor
        public LoginPage(WebDriver driver) {
            this.driver = driver;
        }
    
        // Methods to interact with elements
        public void enterUsername(String user) {
            driver.findElement(username).sendKeys(user);
        }
    
        public void enterPassword(String pass) {
            driver.findElement(password).sendKeys(pass);
        }
    
        public void clickLogin() {
            driver.findElement(loginButton).click();
        }
    }

    Use the Page Class in a Test (LoginTest.java)

    WebDriver driver = new ChromeDriver();
    driver.get("https://example.com");
    
    LoginPage login = new LoginPage(driver);
    login.enterUsername("testUser");
    login.enterPassword("testPass");
    login.clickLogin();

    44. What are the advantages of using POM?

    Main advantages of POM are as below.

    • Better Code Maintainability – You need to update only the page classes, If there is any change in the UI. Do not need to update all test cases.
    • Increased Reusability – You can reuse common UI actions like login, search across multiple tests.
    • Improved Readability – Test scripts are cleaner and easier to understand.
    • Separation of Concerns – Keeps test logic separate from UI element locators.
    • Reduces Code Duplication – No need to define locators in multiple places.

    45. What is Page Factory in Selenium?

    Page Factory is an optimized way to implement the Page Object Model (POM) in Selenium. It simplifies element initialization using the @FindBy annotation and PageFactory.initElements(), which makes test scripts cleaner and more efficient.

    Key Benefits of Page Factory

    • Automatic element initialization using @FindBy.
    • Improves readability & maintainability of test scripts.
    • Faster execution due to lazy loading of elements.

    Example of Page Factory Implementation

    Define Page Class (LoginPage.java)

    import org.openqa.selenium.WebDriver;
    import org.openqa.selenium.WebElement;
    import org.openqa.selenium.support.FindBy;
    import org.openqa.selenium.support.PageFactory;
    
    public class LoginPage {
        WebDriver driver;
    
        // Locate elements using @FindBy annotation
        @FindBy(id = "user") 
        WebElement username;
    
        @FindBy(id = "pass") 
        WebElement password;
    
        @FindBy(id = "login") 
        WebElement loginButton;
    
        // Constructor to initialize Page Factory
        public LoginPage(WebDriver driver) {
            this.driver = driver;
            PageFactory.initElements(driver, this);
        }
    
        // Methods to interact with elements
        public void enterUsername(String user) {
            username.sendKeys(user);
        }
    
        public void enterPassword(String pass) {
            password.sendKeys(pass);
        }
    
        public void clickLogin() {
            loginButton.click();
        }
    }

    Use Page Factory in Test (LoginTest.java)

    WebDriver driver = new ChromeDriver();
    driver.get("https://example.com");
    
    LoginPage login = new LoginPage(driver);
    login.enterUsername("testUser");
    login.enterPassword("testPass");
    login.clickLogin();

    46. How is Page Factory different from POM?

    Key differences between page object model and page factory are as below.
    • Element Initialization
      • POM: Uses driver.findElement() manually.
      • Page Factory: Uses @FindBy annotation with PageFactory.initElements()
    • Code Readability:
      • POM: Requires more lines of code.
      • Page Factory: Cleaner and more concise
    • Performance:
      • POM: Loads elements immediately.
      • Page Factory: Uses lazy initialization, loading elements only when needed.
    • Maintainability
      • POM: Requires explicit element declaration.
      • Page Factory: Automatically initializes elements, making maintenance easier.

    47. How do you handle dynamic elements in Selenium?

    Dynamic elements have changing attributes (like IDs or XPaths) on every page load. You can handle them using:

    Using Dynamic XPath

    Identify elements with partial attributes or text.
    WebElement element = driver.findElement(By.xpath("//*[contains(@id, 'dynamicPart')]"));

    Using CSS Selectors with Wildcards

    Target elements with starts-with (^), ends-with ($), or contains (*) attributes.
    WebElement element = driver.findElement(By.cssSelector("[id^='start']"));

    Using Explicit Wait

    Wait until the element is visible or clickable.
    WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
    WebElement element = wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("dynamicElement")));

    Using JavaScript Executor (If Element is Not Detected)

    Fetch the element using JavaScript.
    JavascriptExecutor js = (JavascriptExecutor) driver;
    WebElement element = (WebElement) js.executeScript("return document.querySelector('[id^=\"dynamic\"]');");

    48. What is TestNG?

    Full form of TestNG is Test Next Generation. It is a powerful testing framework in Java. It is designed to simplify test execution and reporting. It is widely used in Selenium automation for managing test cases efficiently.

    Key Features of TestNG:

    • Annotations: We can use annotations like @Test, @BeforeMethod, @AfterMethod for structured testing.
    • Parallel Test Execution: Allows to run multiple tests simultaneously.
    • Assertions: Has great assertions for result validation.
    • Report Generation: Can generate detailed test results.

    49. What are the advantages of using TestNG?

    Here are the advantages of using TestNG in Selenium.

    Annotations for Better Test Structure → Uses @Test, @BeforeMethod, @AfterMethod for organized test execution.

    Parallel Test Execution → Runs multiple tests at the same time, reducing execution time.

    Built-in Reporting → Generates detailed HTML test reports automatically.

    Data-Driven Testing with @DataProvider → Enables testing with multiple data sets.

    Flexible Test Execution with XML → Run specific tests by modifying the testng.xml file.

    Example:

    @DataProvider(name = "loginData")
    public Object[][] getData() { return new Object[][] { {"user1", "pass1"}, {"user2", "pass2"} }; }

    50. What is the difference between JUnit and TestNG?

    Here are the differences of JUnit and TestNG features.

    JUnit

    • Annotations: You can use @Test, @Before, @After annotations.
    • Dependency Support: No built-in support for test dependencies
    • Parallel Execution: Not supported.
    • Parameterized Tests: Uses @RunWith(Parameterized.class).
    • Reporting: Basic reporting.
    • Test Execution Control: Runs tests alphabetically.

    TestNG

    • Annotations: More powerful annotations that include @BeforeMethod, @AfterMethod. @DataProvider
    • Dependency Support: Supports dependencies using dependsOnMethods.
    • Parallel Execution: Supported using testng.xml.
    • Parameterized Tests: Uses @DataProvider (more flexible).
    • Reporting: Generates detailed HTML reports.
    • Test Execution Control: Runs based on priority using priority attribute.

    51. What is an annotation in TestNG?

    In TestNG, annotations are special markers (starting with @) that control the test execution flow. They define setup, teardown, test execution, and dependencies in a structured way.

    Here is the list of common TestNG annotations with their usage.

    • @Test: Marks a method as a test case.
    • @BeforeMethod: Runs before each test method.
    • @AfterMethod: Runs after each test method.
    • @BeforeClass: Runs once before all test methods in a class.
    • @AfterClass: Runs once after all test methods in a class.
    • @DataProvider: Provides test data for data-driven testing.
    • @Parameters: Passes values from testng.xml to test cases.

    52. What is a DataProvider in TestNG?

    You can use @DataProvider in TestNG to perform data-driven testing. It allows the test method to run multiple times with different data sets. It helps in executing parameterized tests efficiently.

    Here are key features:

    • You can use it to run the same test with multiple inputs.
    • Eliminates hardcoded test data in test scripts.
    • Can fetch data from Excel, CSV, or databases.

    53. How do you use DataProvider to pass test data?

    To use @DataProvider in Selenium test, follow the steps below.
    • Define a method with @DataProvider.
    • Return a 2D Object array containing test data.
    • Use @Test(dataProvider = "providerName") to link the test with the DataProvider.
    Here is an example of how to pass test data using DataProvider.

    Example: Passing Test Data Using DataProvider

    import org.testng.annotations.*;
    
    public class DataProviderExample {
    
        // Step 1: Define DataProvider
        @DataProvider(name = "loginData")
        public Object[][] getData() {
            return new Object[][] {
                {"user1", "pass1"},
                {"user2", "pass2"},
                {"user3", "pass3"}
            };
        }
    
        // Step 2: Use DataProvider in Test
        @Test(dataProvider = "loginData")
        public void testLogin(String username, String password) {
            System.out.println("Testing login with: " + username + " / " + password);
            // Add Selenium code to perform login here
        }
    }

    54. What is a TestNG XML file?

    A TestNG XML file (testng.xml) is a configuration file. It is useful to organize and execute multiple test cases in a structured way. It allows:
    • To run multiple test classes together.
    • To group and prioritize test cases.
    • Parallel test execution.
    • To pass parameters to test methods.

    Example: Basic TestNG XML File (testng.xml)

    <suite name="TestSuite">
        <test name="LoginTest">
            <classes>
                <class name="tests.LoginTest"/>
            </classes>
        </test>
    </suite>

    How to Run Tests Using TestNG XML?

    • Right click on the testng.xml file.
    • Select "Run As → TestNG Suite" in Eclipse.

    55. How do you run tests in parallel using TestNG?

    TestNG allows parallel execution to speed up test runs by running multiple tests simultaneously. You can configure it in the testng.xml file using the parallel attribute.

    Steps to Run Tests in Parallel:

    • Set parallel="methods" or parallel="classes" in testng.xml.
    • Define thread-count to control how many threads run at the same time.

    Example: Parallel Execution of Test Methods (testng.xml)

    <suite name="ParallelSuite" parallel="methods" thread-count="2">
        <test name="ParallelTest">
            <classes>
                <class name="tests.ParallelTest"/>
            </classes>
        </test>
    </suite>

    Java Example: Parallel Test Execution

    import org.testng.annotations.Test;
    
    public class ParallelTest {
        
        @Test
        public void testOne() {
            System.out.println("Test One - " + Thread.currentThread().getId());
        }
    
        @Test
        public void testTwo() {
            System.out.println("Test Two - " + Thread.currentThread().getId());
        }
    }

    56. What is the difference between soft assert and hard assert?

    Difference between soft assert and hard assert is as below.

    Hard Assert: 

    • Stops Execution?: Yes, it stops execution once test fails and so assertion fails.
    • Multiple Assertions?: Not possible, as execution stops on failure.
    • Best For?: Critical validations like login success.

    Soft Assert: 

    • Stops Execution?: Execution will continue even if assertion fails.
    • Multiple Assertions?: Possible, as failures are collected and reported at the end.
    • Best For?: Non-critical checks (e.g., UI element verification).

    57. How do you generate reports in TestNG?

    TestNG has built-in features to generate HTML and XML reports after test execution. However, you can use IReporter or ITestListener to generate interactive custom reports.

    Default TestNG Report (HTML & XML)

    • TestNG creates a report in the test-output folder once you run the test.
    • You can open test-output/index.html file in a browser to view the report.

    Generating Custom Reports Using IReporter

    You can implement IReporter to customize reports as below.

    import org.testng.IReporter;
    import org.testng.ISuite;
    import org.testng.xml.XmlSuite;
    import java.util.List;
    
    public class CustomReport implements IReporter {
        public void generateReport(List<XmlSuite> xmlSuites, List<ISuite> suites, String outputDirectory) {
            System.out.println("Generating custom report...");
        }
    }

    Add to testng.xml:

    <listeners>
        <listener class-name="reports.CustomReport"/>
    </listeners>

    Using ITestListener for Custom Logs

    Capture test start, success, and failure logs.

    import org.testng.ITestListener;
    import org.testng.ITestResult;
    
    public class TestListener implements ITestListener {
        public void onTestSuccess(ITestResult result) {
            System.out.println("Test Passed: " + result.getName());
        }
        
        public void onTestFailure(ITestResult result) {
            System.out.println("Test Failed: " + result.getName());
        }
    }

    Add to testng.xml:

    <listeners>
        <listener class-name="listeners.TestListener"/>
    </listeners>

    58. What is Maven and how does it help in Selenium automation?

    Maven is a build automation and dependency management tool for Java projects. You can use Maven to manage project dependencies. Also, it is useful to build and run selenium test cases efficiently.

    How Maven Helps in Selenium Automation?

    • Manages Dependencies Automatically: No need to download JAR files manually.
    • Standard Project Structure: It follows a predefined structure. So it is easy to maintain a project.
    • Easier Test Execution: You can run tests using a simple command "mvn test".
    • Integration with CI/CD: You can integrate it easily with Jenkins, GitHub Actions, Azure DevOps for automation.
    • Parallel & Cross-Browser Testing: It is easy to configure TestNG for parallel execution using Maven.

    59. What is a pom.xml file in Maven?

    The pom.xml (Project Object Model) file is the core configuration file in a Maven project. It defines:
    • Project details (name, version, description).
    • Dependencies (e.g., Selenium, TestNG).
    • Plugins (e.g., Maven Surefire for running tests).
    • Build and execution commands.

    How pom.xml Helps in Selenium?

    • Manages dependencies automatically: No need to download JARs manually.
    • Easy test execution: Run tests using mvn test.
    • Integrates with CI/CD: Works with Jenkins, GitHub Actions, etc.

    60. How do you integrate Selenium with Maven?

    You can integrate Maven with Selenium to simplify dependency management and test execution. You can follow these steps to set up a Selenium Maven project easily.

    Steps to Integrate Selenium with Maven

    Create a Maven Project

    In Eclipse/IntelliJ: File → New → Maven Project → Select Quickstart Archetype.

    Add Selenium & TestNG Dependencies in pom.xml

    <dependencies>
        <!-- Selenium WebDriver -->
        <!-- https://mvnrepository.com/artifact/org.seleniumhq.selenium/selenium-java -->
    	<dependency>
        		<groupId>org.seleniumhq.selenium</groupId>
        		<artifactId>selenium-java</artifactId>
        		<version>4.29.0</version>
    	</dependency>
    
    
        <!-- TestNG -->
        <!-- https://mvnrepository.com/artifact/org.testng/testng -->
    	<dependency>
        		<groupId>org.testng</groupId>
        		<artifactId>testng</artifactId>
        		<version>7.11.0</version>
        		<scope>test</scope>
    	</dependency>
    
    </dependencies>
    
    

    Write a Sample Selenium Test (Java)

    Create a test class in src/test/java

    import org.openqa.selenium.WebDriver;
    import org.openqa.selenium.chrome.ChromeDriver;
    import org.testng.annotations.Test;
    
    public class GoogleTest {
        @Test
        public void openGoogle() {
            WebDriver driver = new ChromeDriver();
            driver.get("https://www.google.com");
            System.out.println("Title: " + driver.getTitle());
            driver.quit();
        }
    }

    Run Tests Using Maven

    Run all tests:
    mvn test

    General Tips From Experts for Answering Interview Questions

    Here are some expert tips from The Museindeedcareers.govt.nz, and The Guardian articles on how to answer interview questions more precisely to get success.
    • Understand the Question – Ensure that you take a moment before answering the question and ask for clarification if needed.
    • Match Answers to the Company’s Needs: Research about the company and personalize your responses accordingly.
    • Stay Positive & Professional: Avoid insulting past employers and use challenges as a learning experience.
    • Here are a few expert tips from the Muse article 
    • Use the STAR Method – For more clarity, organize your responses using Situation, Task, Action, and Result.
    • Be Concise and Relevant – Try to keep your answers under 2 minutes and avoid going into unnecessary detail.
    • Highlight Results & Impact: You can showcase your impacts using numbers and metrics, which makes your achievements clear, memorable, and results-driven.
    • Practice, But Don’t Memorize: Practice answering common questions while keeping the responses natural.

    No comments:

    Post a Comment