QA Interview: Top 70: Selenium With Java Interview Questions

Other Useful Links:


1. What is Selenium and History of Selenium?

  • Selenium is a free -open-source automated testing framework and is use for validating web based applications.
  • Selenium Scripts can be written in a variety of programming languages, including Java, C#, and Python.
  • Testing performed using the Selenium testing tool is known as Selenium Testing.
History:
  • In 2004, Jason Huggins developed Selenium.
  • He was working as an engineer at ThoughtWorks on a web application that required repetitive testing.
  • As the repetitive manual testing of their application was tedious, he created a JavaScript program that would automatically control the browser’s actions.
  • This application is known as the "JavaScriptTestRunner." He open-sourced JavaScriptRunner, which was later renamed Selenium Core.


The Same Origin Policy Issue:

  • JavaScript code cannot access elements from a domain other than the one where it was launched due to the Same Origin policy.

  • The HTML code of www.google.com, for example, employs the JavaScript programme "randomScript.js." RandomScript.js will only be able to visit pages on google.com such as google.com/mail, google.com/login, and google.com/signup if the same origin policy is applied.

  • it cannot access pages from other sites such as yahoo.com/search because domains are distinct.


Birth of Selenium Remote Control (Selenium RC)

  • Testers using Selenium Core had to install the entire application under test and the web server on their local machine due to the limitations imposed by the same-origin policy.
  • So another ThoughtWork engineer, Paul Hammant, decided to create a server that would act as an HTTP proxy to "fool" the browser into believing that the Selenium Core and the web application under test were from the same domain.
  • This technology was known as the Selenium Remote Control, or Selenium 1.


Birth of Selenium Grid

  • Selenium Grid was established by Patrick Lightbody in response to the necessity to speed up the execution of tests as much as possible.

  • He initially called the system “Hosted QA.” 

  • It was capable of capturing browser screenshots, and also of sending out Selenium commands to different machines simultaneously.


Birth of Selenium IDE

  • Selenium IDE is a Firefox and Chrome extension that allows you to record and replay tests.

  • Selenium IDE now allows you to export your code in a variety of predefined languages.

  • It also allows you to nest test cases.


2. What is Selenium WebDriver?

  • Simon Stewart created WebDriver at a time when browsers and web applications were becoming more powerful and more restrictive.

  • Selenium 2 was the result of the WebDriver and RC projects coming together. WebDriver and RC functionalities were combined in version 2 of WebDriver, which was dubbed Selenium 2.

  • In many ways, Selenium 3 was an improvement over Selenium 2. Selenium 3 became a World Wide Web Consortium  (W3C) standard.

  • Furthermore, Selenium 4 is a new member of the family (the most recent version of Selenium) that is still in beta for end-users.


3. Why the Name Selenium?

  • During the development of Selenium, Mercury Interactive released another automated testing framework.

  • Jason suggested the name Selenium because it is a well-known remedy for Mercury toxicity, and his teammates agreed.


4. Why is Selenium so popular, and what does it do?

  • Selenium has become one of the most popular tools for automating web applications and is supported by a large community. 

  • Google, Apple, Amazon, and many more Fortune 500 firms utilise Selenium on a daily basis and have even offered support to the tool.

  • The original Selenium contributors continue to contribute on a regular basis, allowing Selenium to keep up with the problems of current web application testing.

  • Selenium also includes multiple components for automation across different browsers, platforms, and programming languages, such as Selenium IDE, WebDriver, and Grid.

  • Selenium also supports all major operating systems, including macOS, Windows, and Linux, as well as mobile platforms such as iOS and Android.


5. What can Selenium do?

  • Open Source: Selenium is free to set up and use because it is open source. Downloading and using Selenium is free.

  • Mimic User Actions: Selenium can automate almost all real-world user operations such as button clicks, drag-and-drop selection, checkboxes, keypresses, taps, and scrolling.

  • Easy Implementation: Selenium is well-known for being user-friendly.

  • Language Support: Selenium support programming languages like Java, Python, JavaScript, C#, Ruby, Perl, among others.

  • Browser Support: Selenium has support for Chrome, Firefox, Edge, Internet Explorer, Safari.

  • OS Support: Selenium bindings are available for all major operating systems, including Linux, macOS, and Windows.

  • Framework Support: Selenium supports a variety of frameworks, including Maven, TestNG, PYTest, NUnit, Mocha, Jasmine, and others.

  • Code Reusability: In a Grid arrangement, the same code can be run for numerous browsers using different browser binaries and on different devices.

  • Community Support: Because there are so many QAs working on this technology, finding resources, tutorials, and support on sites like Github, StackOverflow, and others is a breeze.


6. What Selenium can't do?

  • No support to automate native desktop-based applications: There is no support for automating native desktop applications: Selenium is a tool for automating web applications that run in browsers.

  • No support for assertions and validity: Selenium gives you control over your browser, but it doesn't provide you with assertions or checking tools. For assertions, Selenium must be used in conjunction with a testing framework such as JUnit, TestNG, PyTest, etc.

  • No support for image and code scanning: Selenium is unable to automate code scanning scenarios such as bar code reading and CAPTCHA.

  • No support for API Testing: Selenium does not allow API testing since it mimics user actions in the browser. As a result, Selenium does not provide the ability to test APIs.

  • No support for Performance Testing: Selenium is unable to check or verify the performance of web applications.

  • No inbuilt Reporting: Reporting capability is also not provided by Selenium. That is to say; reporting can be done only by pairing it with a framework like JUnit, TestNG.


7. A Comparison between Selenium and QTP (UFT)

Selenium 

QTP

It's open source, free to use, and costless.

Commercial

Highly extensible

Limited add-ons

Can run tests across different browsers

Only Firefox, Internet Explorer, and Chrome are supported for testing.

Supports various operating systems

QTP - Can only be used in Windows


Can only be used in Windows

Supports mobile devices

QTP supports mobile app test automation (iOS and Android) with the HP Mobile Center solution.

Tests can be run while the browser is minimised.

The application being tested must be displayed on the desktop.

Can execute tests in parallel.

Can only run in parallel if Quality Center is used, which is another expensive product.

8. Advantages of QTP over Selenium

Selenium

QTP

Can only test web applications.

Can test both web and desktop applications.

Has no built-in object repository.

Comes with a built-in object repository.

Because it lacks a native IDE and can only use third-party IDEs for development, it automates at a slower rate.

Because it is a full-featured IDE, it automates faster than Selenium.

Access to elements outside of the under test web application is not possible.


Can access controls within the browser(such as Address bar, Back and Forward buttons, etc.)

No official user support is being offered.

Provides professional customer support.

Programming can be used to parameterize, but it is difficult to implement.

Parameterization Support is built.

There is no native capability for creating test/bug reports.

Test Reports are generated automatically.


9. What is RemoteWebDriver?

  • Selenium RemoteWebDriver is used to execute browser automation suite on remote machine

  • RemoteWebDriver class implements WebDriver interface to execute scripts through RemoteWebDriver server on remote machine.

           FirefoxOptions opt = new FirefoxOptions();

           WebDriver driver = new RemoteWebDriver(new URL(url),opt);


10. What Are Locators?

  • Locators are an important part of the Selenium infrastructure since they assist Selenium scripts in uniquely identifying WebElements (such as text boxes, buttons, and so on) on a web page.
        By.className The value of the "class" attribute is used to locate items. findElement(By.className(“someClassName”))      By.cssSelector finds elements based on the driver’s underlying CSS Selector engine findElement(By.cssSelector(“input#email”))      By.id The value of the "id" attribute is used to locate items. findElement(By.id(“someId”)) By.linkText discovers a link element based on the text it displays findElement(By.linkText(“REGISTRATION”)) By.name The value of the "name" attribute is used to locate items. findElement(By.name(“someName”)) By.partialLinkText finds items with the specified link text findElement(By.partialLinkText(“REG”)) By.tagName locates elements by their tag name findElement(By.tagName(“div”)) By.xpath locates elements via XPath findElement(By.xpath(“//div[@class="className"]”))


          

11. Which one is faster: Xpath or cssSelector?

  • cssSelector performs far better than xpath and it is well documented in selenium.

  • Each browser's Xpath Engine is different, making them inefficient.

  • Xpath tends to be more complex


12. findElement vs findElements

findElement

findElements

It will find only one element

It will find a collection of elements.

Return the first element if multiple elements are found with the same locator. 

Return a list of web elements.

Throw exceptions if there are no web element matching locator strategies.

Return empty list if no web elements matches locator strategy

We can not use indexing with findElement.

Each web element is index with number starting from 0 like Array


Example:

WebElement element = driver.findElement(By.xpath("//input[@class="classname"]"));

List<WebElement> elements = driver.findElements(By.xpath("//div[@class="cname"]"));


13. What is the return type of findElements

  • list of elements.


14. What happens if findElements fails to find an element?

  • It will return an empty list.


15. Which is correct and which one is incorrect

  • WebDriver driver = new WebDriver() - Incorrect

  • WebDriver driver = new ChromeDriver() - Correct

  • ChromeDriver driver = new ChromeDriver() - Correct

          WebDriver is an interface and we cannot create instances of an interface.


16. What is the Super Interface of WebDriver?

  • SearchContext


17. Example of sendKeys() / clear() / submit() / click()

import org.openqa.selenium.By;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.chrome.ChromeDriver;

import org.openqa.selenium.*;


public class Form {

    public static void main(String[] args) {

        System.setProperty("webdriver.chrome.driver","G:\\chromedriver.exe");

        WebDriver driver = new ChromeDriver();

        String baseUrl = "http://demo.test.com/login.html";

        driver.get(baseUrl);


        WebElement email = driver.findElement(By.id("email"));

        WebElement password = driver.findElement(By.name("pass"));

        WebElement login = driver.findElement(By.id("SubmitLogin"));

        

        // Insert values in email and password field - sendKeys()

        email.sendKeys("abc@gmail.com");

        password.sendKeys("test@1234");

        

    // Deleting values in the text box - clear()

       email.clear();

       password.clear(); 

        

        // Using click method to submit form - click()

        email.sendKeys("abc@gmail.com");

        password.sendKeys("test@1234");

        login.click();


        // To submit the form, use the submit method.

driver.get(baseUrl);

        driver.findElement(By.id("email")).sendKeys("abc@gmail.com");

driver.findElement(By.name("pass")).sendKeys("test@1234");

        driver.findElement(By.id("SubmitLogin")).submit();

        driver.close();

    }

}


18. Handle CheckBox and Radio Buttons

Selenium WebDriver provides some methods that can validate the states of Radio Buttons and Checkboxes. Few of these methods are:
  • isSelected() :  Checks whether a radio button is selected or not.

  • isDisplayed(): Checks whether a radio button is displayed on the web page or not.

  • isEnabled() :   Checks whether a radio button is enabled or not.

// Validate Radio button using isSelected() method

WebElement radioElement = driver.findElement(By.id("maleRadio"));

boolean selectState = radioElement.isSelected();

if(selectState == false) {

radioElement.click();

}


// Validate Checkbox using isDisplayed() and click

WebElement checkBoxElement = driver.findElement(By.id("check_india"));

boolean isDisplayed = checkBoxElement.isDisplayed();

if (isDisplayed == true) {

checkBoxElement.click();

}


// Validate Checkbox using isEnabled() and then click

WebElement checkBoxElement = driver.findElement(By.cssSelector("label[for='country-checkbox-1']"));

boolean isEnabled = chckBxEnable.isEnabled();

if (isEnabled == true) {

checkBoxElement.click();

}


19. How to clear text using selenium?

  • clear() method is used to clear text from the text area.



20. How to input text in textbox without calling sendKeys() using selenium

  • Using JavaScriptExecutor Interface:

         JavaScriptExecutor js  = (JavaScriptExecuter) driver;

    js.executeScript("document.getElementById('ID').value='TEXT'");


21. Handle DropDown in Selenium

  • In HTML, the dropdowns are generally implemented either using the <select> tag or the <input> tag.

  • To perform certain operations on the dropdowns, which are declared using the <select> HTML tag, Selenium WebDrivers provides a class called "Select " class.

  • "org.openqa.selenium.support.ui" package provides the "Select" class.

  • You can build a Select object by supplying an object of the "WebElement" class, which reveals the object returned by the WebElement's related locator.

  • Syntax: Select select = new Select(WebElement webelement);

selectByIndex: selectByIndex: This method uses the dropdown option's index number to select it.

Select s = new Select(driver.findElement(By.xpath("//*[@id='oldSelectMenu']")));

s.selectByIndex(3);


selectByValue: This function selects the dropdown choice based on its value.

Select s = new Select(driver.findElement(By.xpath("//*[@id='oldSelectMenu']")));

s.selectByValue("6");


selectByVisibleText: Using this approach, you can choose one choice from a dropdown or a multi-select dropdown based on the text in the dropdown.

Select s = new Select(driver.findElement(By.xpath("//*[@id='oldSelectMenu']")));

s.selectByVisibleText("White");


isMultiple(): "isMultiple()" method determines whether the web element supports multiple selections. It returns a boolean value without taking any argument. It looks for the attribute'multiple' in the web element's HTML code.

Select sel = new Select(driver.findElement(By.xpath(//*[@id='cars']);

if(sel.isMultiple()){

//Selecting multiple values by index

sel.selectByIndex(1);

sel.selectByIndex(2);

}


We can deselect values in the same way we choose them in a DropDown & Multi-Select. However, the deselect approach only works with Multi-Select. The various deselect techniques can be used to deselect pre-selected options from a Multi-select element.


deselectAll: This method clears all of the dropdown's selected entries.

Select select = new Select(driver.findElement(By.id("oldSelectMenu")));

select.deselectAll();


deselectByIndex: Similar to the selectByIndex() method, the Select class also includes the deselectByIndex() method for deselecting a dropdown item.

Select select = new Select(driver.findElement(By.id("oldSelectMenu")));

select.deselectByIndex(1);


deselectByValue: Similar to the selectByValue() method, the Select class also has the deselectByValue() method for deselecting a dropdown item.

Select select = new Select(driver.findElement(By.id("oldSelectMenu")));

select.deselectByValue("6");


deselectByVisibleText: Similar to the selectByVisibleText() method, the Select class provides the deselectByVisibleText() method for deselecting a dropdown item.

Select select = new Select(driver.findElement(By.id("oldSelectMenu")));

select.deselectByVisibleText("White");


getFirstSelectedOption(): This function returns the dropdown's first picked option. This function will return the selected value of the dropdown if it is a single-select dropdown, and the first selected value of the dropdown if it is a multi-select dropdown.

Select select = new Select(driver.findElement(By.id("oldSelectMenu")));

WebElement firstSelectedOption = select.getFirstSelectedOption();


getAllSelectedOptions(): This method returns the dropdown's selected options. This function will return the only selected value of the dropdown if it is a single-select dropdown, and all selected values of the dropdown if it is a multi-select dropdown.

Select select = new Select(driver.findElement(By.id("oldSelectMenu")));

List<WebElement> selectedOptions = select.getAllSelectedOptions();


getOptions: You may need to get all of the options in a dropdown or multi-select box at times. This is where the Select class's getOptions() method comes in handy.

Select select = new Select(driver.findElement(By.id("oldSelectMenu")));

List<WebElement> options = select.getOptions();


22. Browser and Navigation Commands 

get(String arg): This method Load a new web page in the current browser window.

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

String url= "https://www.test.com";

driver.get(url);


getTitle(): This method fetches the Title of the current page.

String Title = driver.getTitle();


getCurrentUrl(): This function returns the string that represents the current URL in the browser.

String CurrentUrl = driver.getCurrentUrl();


getPageSource(): This method returns the Source Code of the page.

String PageSource = driver.getPageSource();


close(): This method only closes the window that the WebDriver is currently in control of.

driver.close();


quit(): This method closes all of the WebDriver's windows.

driver.quit();


driver.navigate().to(): It does exactly the same thing as the driver.get(appUrl) method. The website address to load is appUrl. A fully qualified URL is the best option.

driver.navigate().to("https://www.Test.com");


driver.navigate().forward(): This method performs the same function as hitting the browser's Forward Button. It neither accepts nor returns anything.

driver.navigate().forward();


driver.navigate().back(): This method performs the same function as a browser's Back Button.

driver.navigate().back();


driver.navigate().refresh(): This method Refresh the current page. It neither accepts nor returns anything.

driver.navigate().refresh();


23. Difference Between driver.get() and driver.navigate().to()

driver.get()

driver.navigate().to()

The get() method does not provide capability to access browser history.

We may traverse the browser's history using.back() and.forward(), which allows us to access the history one item at a time.

The get() method is in charge of loading the page and waits for it to finish.

navigate() method is responsible for redirecting the page and then returning immediately.

24. Difference Between driver.close() and driver.quit()

driver.close()

driver.quit()

driver.close() method will close the browser which is in focus.

While the driver.quit() method closes all the browsers.

driver.close() method closes the active WebDriver instance.

While driver.quit() closes all WebDriver instances.

25. How to perform back, forward and refresh action in selenium ?

  • driver.navigate().forward()

  • driver.navigate().back()

  • driver.navigate().refresh()


26. How to get the current URL, title and page source?

  • driver.getCurrentUrl()

  • driver.getTitle()

  • driver.getPageSource()


27. Refresh Browser in Different Ways:

  • driver.navigate().refresh();

  • driver.get("SAME URL");

  • driver.get(driver.getCurrentUrl());

  • driver.navigate().to(driver.getCurrentUrl());

  • driver.findElement(By.Id("SearchBox")).sendKeys(Keys.F5);

  • driver.findElement(By.Id("SearchBox")).sendKeys("\uE035"); - ASCII


28. PopUps and Alerts in Selenium

  • Alerts are little popup windows that display messages or notifications and may ask for permission to perform particular actions.

  • Web/Javascript/browser-based alerts and Windows/OS-based alerts are the two forms of Selenium alerts. Simple alerts (Click OK), prompt alerts (Input Text in Alert), and confirmation alerts (Yes/No) are the three types of web-based alerts.

  • We have Alert interface in Selenium (It is not a class.We can switch the control from the main browser window to the alert window using command: driver.switchTo().alert();

  1. driver.switchTo().alert().accept(): This method clicks on the 'OK' button of the alert box.

  2. driver.switchTo().alert().dismiss(): We use this method when the 'Cancel' button clicks in the alert box.

  3. driver.switchTo().alert().getText(): The message from the alert box is captured using this way.

  4. driver.switchTo().alert().sendKeys("Text"): Data is sent to the alert box using this way.


29. Using Webdriver to handle Selenium Pop-up windows

Driver.getWindowHandle():

  • When the site first loads, the primary window must be handled by the driver. getWindowHandle().

  • This will deal with the current window, which is unique within this driver instance.

  • Its return type is String.

Driver.getWindowHandles();

  • We can use "Driver.getWindowHandles()" to manage all opened windows by the web driver, and then switch from one window to another in a web application.

  • Its return type is Iterator<String>.

Example:

import java.util.Iterator;

import java.util.Set;

import org.openqa.selenium.By;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.firefox.FirefoxDriver;


public class WindowHandle_Demo {

    public static void main(String[] args) {

    WebDriver driver = new FirefoxDriver();

    driver.get("http://demo.Testing.com/Test");

    driver.manage().window().maximize();

                

    driver.findElement(By.xpath("//*[contains(@href,'popup.php')]")).click(); 

    String MainWindow=driver.getWindowHandle();

        

    // To handle all newly opened windows.

    Set<String> s1 = driver.getWindowHandles();

    Iterator<String> i1 = s1.iterator();

    

    while(i1.hasNext())

        {

            String ChildWindow=i1.next();

            if(!MainWindow.equalsIgnoreCase(ChildWindow))

            {                 

                // Switching to Child window

                driver.switchTo().window(ChildWindow);           

                driver.findElement(By.name("emailid")).sendKeys("test@gmail.com");      

                driver.findElement(By.name("btnLogin")).click();

                                 

// Closing the Child Window.

                driver.close();

            }

        }

        // Changing to the Parent window (Main Window)

           driver.switchTo().window(MainWindow);

    }


30. List methods used for alert and window operations
  • driver.switchTo().alert().accept();
  • driver.switchTo().alert().dismiss();
  • driver.switchTo().alert().getText();
  • driver.switchTo().alert().sendKeys("Text");
  • driver.manage().window().maximize();
  • driver.manage().window().getSize();
  • driver.manage().window().setSize();

31. How to switch from one window to another window?

  • driver.switchTo().window(<Window-Handle>);


32. How to handle iframes?

  • An iframe is an HTML document that is contained within another HTML document.

  • Iframes are frequently used to embed material from other websites, such as advertisements, onto a web page.

  • The frame is defined with <iframe> tag.

  • There are different ways to handle iframes:

  1. By Index

  2. By ID or Name

  3. By WebElement

Example:

driver.switchTo().frame(0);

driver.switchTo().frame("iframe_name");

driver.switchTo().frame(element);


33. How to switch back to the parent frame?

  • driver.switchTo().parentFrame();

  • driver.switchTo().defaultContent();


34. Cookies in Selenium

getCookies(): To get all the Cookies in the current domain.

Set<Cookie> cookiesForCurrentURL = driver.manage().getCookies();

for (Cookie cookie : cookiesForCurrentURL) {

    System.out.println(" Cookie Name - " + cookie.getName() + " Cookie Value - "  + cookie.getValue()));

}


getCookieNamed(String cookieName): To get a specific Cookie by name,

System.out.println(driver.manage().getCookieNamed(cookieName).getValue());


addCookie(Cookie cookie): In Selenium WebDriver, you can add a specific Cookie.

Cookie cookie = new Cookie("cookieName", "cookieValue");

driver.manage().addCookie(cookie);


deleteCookieNamed(String cookieName): Deletes a specific Cookie based on its name.

driver.manage().deleteCookieNamed(cookieName);


deleteCookie(Cookie cookie): To delete a particular Cookie.

driver.manage().deleteCookie(cookie);


deleteAllCookies(): To delete all the Cookies.

driver.manage().deleteAllCookies();


35. HTMLUnitDriver

  • HTMLUnitDriver is the lightest and fastest headless browser implementation.

  • It is similar to chrome, IE, FireFox/gecko drivers but does not have GUI, so one cannot see execution on the screen.

Example:

import org.openqa.selenium.htmlunit.*;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.*;


public class Test{

        public static void main(String[] args){

                WebDriver driver = new HTMLUnitDriver();

                driver.get("http://demo.Testing.com/Test");

                System.out.println("Page title is:" + driver.getTitle());

                driver.quit();

        }

}


        


Next: Selenium With Java Interview Questions - (36-70)


Greetings, reader! Your input is highly important to us. Please share your thoughts in the comments section below.


Contact:

Email:  piyushagrawal.automation@gmail.com

Follow on LinkedIn: Piyush Agrawal - LinkedIn

Follow on YouTube: Piyush Agrawal - YouTube

Happy to Help You !!

No comments:

Post a Comment