Blog Detail

  • Selenium-Framework-Interview-Questions-1_367.png

    Selenium Interview Questions for Intermediate Level

    1. Explain the difference between driver.close() and driver.quit() command in Selenium?

    Following is the major difference between both the commands:

    driver.close() command closes the currently active window on which the user is working or the window being currently accessed by the web driver.
    driver.quit() command, unlike the driver.close() command closes all the windows opened by the program and hence should be used with care.
    Both the commands don’t take any parameter and don’t return any value either.

    2. Explain the various navigation commands supported by Selenium?

    Selenium has the support of majorly 4 navigation commands:

    navigate().back(): This command is used for taking the user to the last webpage of the browser history.
    navigate().forward(): This command is used for taking the user to the next web page of the browser history.
    navigate().refresh(): This command is used for reloading the web components of a webpage by refreshing it.
    navigate().to(): This command is used for navigating to a particular URL in a new web browser. It takes the URL to be migrated to, as a parameter.

    3. Explain the same-origin policy and how Selenium handles it?

    Same Origin policy is a feature adopted for security purposes that allows a web browser to run scripts from one webpage to access the contents of another webpage provided both the pages have the same origin. The URL scheme, hostname, and port number combo are referred to as the origin. This policy was introduced to prevent access to sensitive data on one webpage by another for ill purposes. Consider a Java program used by scaler.com, the program can access domain pages like scaler.com/mentors, scaler.com/courses but none from different domains like facebook.com.

    The Selenium Server (Selenium RC) acts as a client-configured HTTP proxy and "tricks" the browser into believing that Selenium Core and the web application being tested come from the same origin.

    4. Can we handle a windows-based pop-up in Selenium, and if not, then what are the alternatives?

    No, Selenium doesn’t support windows based pop-ups as it’s an automated testing tool built for web application-based testing. However, with the support of third-party tools like AutoIT, Robot class, etc., windows-based pop-ups can be handled in selenium.

    5. With the help of code snippets, explain how we can create right-click and mouse hover actions in Selenium.

    The following code can replicate right-click action:

    actions action = newActions(driver);
    WebElement element = driver.findElement(By.id("elementId"));
    action.contextClick(element).perform();
    The following code can replicate mouse hover action:
    actions action = newActions(driver);
    WebElement element = driver.findElement(By.id("elementId"));
    action.moveToElement(element).perform();

    6. Can you capture a screenshot using Selenium? If yes, write a simple code to illustrate the same.

    Yes, using a web driver in Selenium, we can capture the screenshot. Following is the code to do the same:
    import org.junit.After;
    import org.junit.Before;
    import org.junit.Test;
    import java.io.File;
    import java.io.IOException;
    import org.apache.commons.io.FileUtils;
    import org.openqa.selenium.OutputType;
    import org.openqa.selenium.TakesScreenshot;
    import org.openqa.selenium.WebDriver;
    import org.openqa.selenium.firefox.FirefoxDriver;
    public class TakeScreenshot {
        WebDriver drv;
        @ Before
        public void setUp() throws Exception {
            driver = new FirefoxDriver();
            drv.get("https://google.com");
        }
        @ After
        public void tearDown() throws Exception {
           drv.quit();
        }
        @ Test
        public void test() throws IOException {
           // Capture the screenshot
              File scrFile = ((TakeScreenshot)drv).getScreenshotAs(OutputType.FILE);
          // Code for pasting screenshot to a user-specified location
              FileUtils.copyFile(scrFile, new File("C:\\Screenshot\\Scr.jpg"))
         }
    }

    7. Explain different types of framework and connection of Selenium with Robot Framework.

    Following are the different type of frameworks:

    Behavior-Driven Development Framework: This type of framework provides a readable and easily understandable format to Business Analysts, Developers, Testers, etc.

    Data-Driven Testing Framework: This type of framework helps separate test data from the test-script logic by storing test data in some external database in the form of key-value pairs. These keys can be used for accessing as well as populating data into the test scripts.

    Keyword-Driven Testing Framework: This type of framework is an extension of the data-driven testing framework. In addition to separating test data and the test-script logic, it also separates a part of the test script code by storing it in an external data file.

    Library Architecture Testing Framework: This type of framework groups common steps into functions under a library and calls these functions as and when required.

    Module-Based Testing Framework: This type of framework divides each test application into several isolated and logical modules, with each module having its distinct test script.

    Hybrid Testing Framework: This type of framework is a combination of the above-mentioned frameworks leveraging all their good features.

    Robot Framework is a modular open-source automation framework that can interact with 3rd party libraries and functions. To execute a web testing library such as Selenium, a test automation runner or an automation wrapper is required, which is provided to it in the form of a Robot Framework. Other popular test runners to serve the same purpose are MSTest, TestNG, Nunit, Junit, etc.



    8. Demonstrate usage of Selenium through a test application.

    You need the following prerequisites to run a demo Selenium test script:

    Java SDK in your respective Operating System.

    A Java-based IDE such as Eclipse or IntelliJ.

    A Selenium Web Driver to be added as a dependency to Java IDE.

    package scalerAcademy;
    import org.openqa.selenium.firefox.FirefoxDriver;
    import org.openqa.selenium.WebDriver;
    public class MyFirstTestClass {
         public static void main(String[] args) throws InterruptedException {
              //It sets the system property to the given value.
              System.setProperty("webdriver.gecko.driver","D:\\Softwares\\geckodriver.exe”);
              WebDriver driver = new FirefoxDriver();
              driver.get("https://www.google.com/");
              //Launch website in the browser
              driver.manage().window().maximize();
              //The sleep pauses the execution of the thread for 5000 ms.
              Thread.sleep(5000);
              driver.quit();
         }
    }

    9. Explain the basic steps of Selenium testing and its widely used commands via a practical application.

    Selenium testing can be divided into the following seven basic elements:

    Creating an instance of a web driver: This is the first step for all the usages of a Selenium web driver API. An instance of a web driver interface is created using a constructor of a particular browser. This web driver instance is used to invoke methods and to access other interfaces. Following are the most commonly used commands for initializing a web driver:

    Firefox:
        WebDriver driver = new FirefoxDriver();

    Chrome:
        WebDriver driver = new ChromeDriver();

    Safari Driver:
        WebDriver driver = new SafariDriver();

    Internet Explorer:
        WebDriver driver = new InternetExplorerDriver();

    Navigating to a webpage: The second step after initializing an instance of a webdriver, to navigate to a particular webpage you want to test. Following are the most commonly used commands for webpage navigation:

    Navigate to URL:
    driver.get(“https://www.interviewbit.com”)
    driver.navigateo.to(“https://www.interviewbit.com”)


    Refresh page:
    driver.navigate().refresh()

    Navigate forward in browser history:
    driver.navigate().forward()

    Navigate backward in browser history:
    driver.navigate().backward()

    Locating an HTML element on the webpage: To interact with a web element and perform actions on it like clicking a button or entering text, we first need to locate the desired elements such as the button or the textbox on the web page. Following are the most commonly used commands for web element navigation:

    Locating by ID:
    driver.findElement(By.id("q")).sendKeys("Selenium 3");

    Location by Name:
    driver.findElement(By.name("q")).sendKeys ("Selenium 3");

    Location by Xpath:
    driver.findElement(By.xpath("//input[@id==’q’])).sendKeys("Selenium 3");

    Locating Hyperlinks by Link Text:
    driver.FindElement(By.LinkText("edit this page")).Click();

    Locating by ClassName:
    driver.findElement(By.className("profileheader"));

    Locating by TagName:
    driver.findElement(By.tagName("select')).click();

    Locating by LinkText:
    driver.findElement(By.linkText("NextPage")).click();

    Locating by PartialLinkText:
    driverlindElement(By.partialLinkText(" NextP")).click();


    Performing actions on an HTML element: Once we have located the HTML element, the next step is interacting with it. Following are the most commonly used commands for performing actions on HTML element:

    Entering a username:
    usernameElement.sendKeys("InterviewBit");

    Entering a password:
    passwordElement.sendKeys("Raw");

    Submitting a text input element:
    passwordElement.submit();

    Submitting a form element:
    formElement.submit();

    Anticipating browser response from the action: Once an action is performed, anticipating a response from the browser to test comes under this step. It takes a second or two for the action to reach the browser, and hence wait is often required for this step. There are two main types of wait conditions:

    Implicit Wait: It sets a fixed, definite time for all the webdriver interactions. It’s slightly unreliable as web driver response times are usually unpredictable.

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

    Explicit Wait: This type of wait condition sets an expected condition to occur on the web page or a maximum wait time for all the web driver interactions.

    Eg: WebElement messageElement = wait.until( ExpectedConditions.presenceOfElementLocated(By.id("loginResponse")) );

    Running tests and recording their results using a test framework: in this step, we run tests in an automated test script to evaluate an application's function and performance. Various test frameworks are used for this step, such as:

    JUnit for Java

    NUnit for C#

    Unittest or Pyunit for Python

    RUnit for Ruby

    Most frameworks use some sort of asset statement to verify their test results from the expected results.

    Eg: assertEquals (expectedMessage, actualMessage);

    Concluding a test: In this step, we conclude a test by invoking a quit method on the driver variable. This step closes all the webpages, quits the WebDriver server, and releases the driver.

    Eg: driver.quit();

    The following is an example of an app that covers all the steps mentioned above:

    import org.openqa.selenium.By,
    import org.openqa.selenium.WebElement,
    import org.openqa.selenium.support.ni.ExpectedConditiof, import org.openqa.selenium.support.ni.WebOriverWait,
    import org.junit.Assert;
    public class Example {
        public static void main(String[] args) {
            // Creating a driver instance
            WebDriver driver = new FirefoxDriver(),
            // Navigate to a web page
    ­        driver.get("http://www.foo.com");
            // Enter text to submit the form
            WebElement usernameElement = driver.findElement( By.name("username"));
            WebElement passwordElement = driver.findElement(By.name(”password"));
            WebElement formElement = driver.findElement(By.id(”loginForm"));
            usernameElement.sendKeys("Scaler Academy");
            passwordElement.sendKeys("Raw");
            formElement.submit(); // submit by form element
            //Putting an explicit wait
            WebDriverWait wait = new WebDriverWait(driver, 10);
            WebElement messageElement = wait.until(
            ExpectedConditions.presenceofElementLocated(By.id(”loginResponse"))
        );
        // Run a test
        String message = messageElement.getrept();
        String successMsg = "Welcome to foo. You logged in successfully.”;
        Assert.assertEquals (message, successMsg);
        // Conclude a test
        driver.quit();
     }
    }

    10. How can we launch different browsers in Selenium WebDriver?

    We have to create an instance of a driver of that particular browser.

    WebDriver driver =newFirefoxDriver();

    Here, "WebDriver" is an interface, and we are creating a reference variable "driver" of type WebDriver, instantiated using "FireFoxDriver" class.


    11. Write a code snippet to launch the Firefox browser in WebDriver.

    public class FirefoxBrowserLaunchDemo {
        public static void main(String[] args) {
            //Creating a driver object referencing WebDriver interface 
            WebDriver driver;
            //Setting webdriver.gecko.driver property
            System.setProperty("webdriver.gecko.driver", pathToGeckoDriver + "\\geckodriver.exe");
            //Instantiating driver object and launching browser
            driver = newFirefoxDriver();
            //Using get() method to open a webpage
            driver.get("http://javatpoint.com");
            //Closing the browser
            driver.quit();
        }
    }

    12. Write a code snippet to launch the Chrome browser in WebDriver.

    public class ChromeBrowserLaunchDemo {
        public static void main(String[] args) {
            //Creating a driver object referencing WebDriver interface
            WebDriver driver;
            //Setting the webdriver.chrome.driver property to its executable's location
            System.setProperty("webdriver.chrome.driver", "/lib/chromeDriver/chromedriver.exe");
            //Instantiating driver object
            driver = newChromeDriver();
            //Using get() method to open a webpage
            driver.get("http://javatpoint.com");
            //Closing the browser
            driver.quit();
        }
    }

    13. Write a code snippet to launch the Internet Explorer browser in WebDriver.

    public class IEBrowserLaunchDemo {
        public static void main(String[] args) {
            //Creating a driver object referencing WebDriver interface
            WebDriver driver;
            //Setting the webdriver.ie.driver property to its executable's location
            System.setProperty("webdriver.ie.driver", "/lib/IEDriverServer/IEDriverServer.exe");
            //Instantiating driver object
            driver = newInternetExplorerDriver();
            //Using get() method to open a webpage
            driver.get("http://javatpoint.com");
            //Closing the browser
            driver.quit();
        }
    }

    14. Write a code snippet to perform right-click an element in WebDriver.

    We will use Action class to generate user event like right-click an element in WebDriver.

    Actions action = newActions(driver);

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

    action.contextClick(element).perform();

    15. Write a code snippet to perform mouse hover in WebDriver.

    Actions action = newActions(driver);

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

    action.moveToElement(element).perform();