Selenium

Selenium Interview QuestionsSelenium Interview Questions..

Here are some of the frequently asked Selenium Interview Questions…

If you are interested to learn more about Selenium, visit  Selenium Tutorial

Are you interested in taking up for Selenium Training? Enroll for Free Demo on Selenium Training.

Q #1) What is Automation Testing?

Automation testing or Test Automation is a process of automating the manual process to test the application/system under test. Automation testing involves use to a separate testing tool which lets you create test scripts which can be executed repeatedly and doesn’t require any manual intervention.

Q #2) What are the benefits of Automation Testing?

Benefits of Automation testing are:

  1. Supports execution of repeated test cases
  2. Aids in testing a large test matrix
  3. Enables parallel execution
  4. Encourages unattended execution
  5. Improves accuracy thereby reducing human-generated errors
  6. Saves time and money

Q #3) Why should Selenium be selected as a test tool?

Selenium

  1. is free and open source
  2. have a large user base and helping communities
  3. have cross Browser compatibility (Firefox, Chrome, Internet Explorer, Safari etc.)
  4. have great platform compatibility (Windows, Mac OS, Linux etc.)
  5. supports multiple programming languages (Java, C#, Ruby, Python, Pearl etc.)
  6. has fresh and regular repository developments
  7. supports distributed testing

Q #4) What is Selenium? What are the different Selenium components?

Selenium is one of the most popular automated testing suites. Selenium is designed in a way to support and encourage automation testing of functional aspects of web-based applications and a wide range of browsers and platforms. Due to its existence in the open source community, it has become one of the most accepted tools amongst the testing professionals.

Selenium is not just a single tool or a utility, rather a package of several testing tools and for the same reason, it is referred to as a Suite. Each of these tools is designed to cater different testing and test environment requirements.

The suite package constitutes of the following sets of tools:

  • Selenium IDE – Selenium IDE is a record and playback tool. It is distributed as a Firefox Plugin.
  • Selenium Remote Control (RC) – Selenium RC is a server that allows a user to create test scripts in the desired programming language. It also allows executing test scripts within the large spectrum of browsers.
  • Selenium Webdriver – WebDriver is a different tool altogether that has various advantages over Selenium RC. WebDriver directly communicates with the web browser and uses its native compatibility to automate.
  • Selenium Grid– Selenium Grid is used to distribute your test execution on multiple platforms and environments concurrently.

Q #5) What are the testing types that can be supported by Selenium?

Selenium supports the following types of testing:

  1. Functional Testing
  2. Regression Testing

Q #6) What are the limitations of Selenium?

Following are the limitations of Selenium:

  • Selenium supports testing of only web-based applications
  • Mobile applications cannot be tested using Selenium
  • Captcha and Barcode readers cannot be tested using Selenium
  • Reports can only be generated using third-party tools like TestNG or JUnit.
  • As Selenium is a free tool, thus there is no ready vendor support though the user can find numerous helping communities.
  • The user is expected to possess prior programming language knowledge.

Q #7) What is the difference between Selenium IDE, Selenium RC and WebDriver?

Continue reading Selenium Interview Questions….

Q #8) When should I use Selenium IDE?

Selenium IDE is the simplest and easiest of all the tools within the Selenium Package. Its record and playback feature makes it exceptionally easy to learn with minimal acquaintances to any programming language. Selenium IDE is an ideal tool for a naïve user.

Q #9) What is Selenese?

Selenese is the language which is used to write test scripts in Selenium IDE.

Q #10) What are the different types of locators in Selenium?

The locator can be termed as an address that identifies a web element uniquely within the webpage. Thus, to identify web elements accurately and precisely we have different types of locators in Selenium:

  • ID
  • ClassName
  • Name
  • TagName
  • LinkText
  • PartialLinkText
  • Xpath
  • CSS Selector
  • DOM

Q #11) What is the difference between assert and verify commands?

Assert: Assert command checks whether the given condition is true or false. Let’s say we assert whether the given element is present on the web page or not. If the condition is true then the program control will execute the next test step but if the condition is false, the execution would stop and no further test would be executed.

Verify: Verify command also checks whether the given condition is true or false. Irrespective of the condition being true or false, the program execution doesn’t halt i.e. any failure during verification would not stop the execution and all the test steps would be executed.

Q #12) What is an XPath?

Xpath is used to locate a web element based on its XML path. XML stands for Extensible Markup Language and is used to store, organize and transport arbitrary data. It stores data in a key-value pair which is very much similar to HTML tags. Both being markup languages and since they fall under the same umbrella, XPath can be used to locate HTML elements.

The fundamental behind locating elements using XPath is the traversing between various elements across the entire page and thus enabling a user to find an element with the reference of another element.

Q #13) What is the difference between “/” and “//” in Xpath?

Single Slash “/” – Single slash is used to create Xpath with absolute path i.e. the xpath would be created to start selection from the document node/start node.

Double Slash “//” – Double slash is used to create Xpath with relative path i.e. the xpath would be created to start selection from anywhere within the document.

Q #14) What is Same origin policy and how it can be handled?

The problem of same origin policy disallows to access the DOM of a document from an origin that is different from the origin we are trying to access the document.

Origin is a sequential combination of scheme, host and port of the URL. For example, for a URL http://www.Techtutorialz.com/resources/, the origin is a combination of http, Techtutorialz.com, 80 correspondingly.

Thus the Selenium Core (JavaScript Program) cannot access the elements from an origin that is different from where it was launched. For Example, if I have launched the JavaScript Program from “http://www.Techtutorialz.com”, then I would be able to access the pages within the same domain such as “http://www.Techtutorialz.com/resources” or “http://www.Techtutorialz.com/istqb-free-updates/”. The other domains like google.com, seleniumhq.org would no more be accessible.

So, In order to handle same origin policy, Selenium Remote Control was introduced.

Q #15) When should I use Selenium Grid?

Selenium Grid can be used to execute same or different test scripts on multiple platforms and browsers concurrently so as to achieve distributed test execution, testing under different environments and saving execution time remarkably.

Q #16) What do we mean by Selenium 1 and Selenium 2?

Selenium RC and WebDriver, in a combination are popularly known as Selenium 2. Selenium RC alone is also referred as Selenium 1.

Q #17) Which is the latest Selenium tool?

WebDriver

Q #18) How do I launch the browser using WebDriver?

The following syntax can be used to launch Browser:
WebDriver driver = new FirefoxDriver();
WebDriver driver = new ChromeDriver();
WebDriver driver = new InternetExplorerDriver();

Q #19) What are the different types of Drivers available in WebDriver?

The different drivers available in WebDriver are:

  • FirefoxDriver
  • InternetExplorerDriver
  • ChromeDriver
  • SafariDriver
  • OperaDriver
  • AndroidDriver
  • IPhoneDriver
  • HtmlUnitDriver

Q #20) What are the different types of waits available in WebDriver?

There are two types of waits available in Webdriver:

  1. Implicit Wait
  2. Explicit Wait

Implicit Wait: Implicit waits are used to provide a default waiting time (say 30 seconds) between each consecutive test step/command across the entire test script. Thus, subsequent test step would only execute when the 30 seconds have elapsed after executing the previous test step/command.

Explicit Wait: Explicit waits are used to halt the execution till the time a particular condition is met or the maximum time has elapsed. Unlike Implicit waits, explicit waits are applied for a particular instance only.

Continue reading Selenium Interview Questions..

 

Q #21) How to type in a textbox using Selenium?

User can use sendKeys(“String to be entered”) to enter the string in the textbox.

Syntax:
WebElement username = drv.findElement(By.id(“Email”));
// entering username
username.sendKeys(“sth”);

Q #22) How can you find if an element in displayed on the screen?

WebDriver facilitates the user with the following methods to check the visibility of the web elements. These web elements can be buttons, drop boxes, checkboxes, radio buttons, labels etc.

  1. isDisplayed()
  2. isSelected()
  3. isEnabled()

Syntax:

isDisplayed():
boolean buttonPresence = driver.findElement(By.id(“gbqfba”)).isDisplayed();

isSelected():
boolean buttonSelected = driver.findElement(By.id(“gbqfba”)).isDisplayed();

isEnabled():
boolean searchIconEnabled = driver.findElement(By.id(“gbqfb”)).isEnabled();

Q #23) How can we get a text of a web element?

Get command is used to retrieve the inner text of the specified web element. The command doesn’t require any parameter but returns a string value. It is also one of the extensively used commands for verification of messages, labels, errors etc displayed on the web pages.

Syntax:
String Text = driver.findElement(By.id(“Text”)).getText();

Q #24) How to select value in a dropdown?

Value in the drop down can be selected using WebDriver’s Select class.

Syntax:

selectByValue:
Select selectByValue = newSelect(driver.findElement(By.id(“SelectID_One”)));
selectByValue.selectByValue(“greenvalue”);

selectByVisibleText:
Select selectByVisibleText = new Select (driver.findElement(By.id(“SelectID_Two”)));
selectByVisibleText.selectByVisibleText(“Lime”);

selectByIndex:
Select selectByIndex = newSelect(driver.findElement(By.id(“SelectID_Three”)));
selectByIndex.selectByIndex(2);

Q #25) What are the different types of navigation commands?

Following are the navigation Commands.
navigate().back() – The above command requires no parameters and takes back the user to the previous webpage in the web browser’s history.

Sample code:
driver.navigate().back();

navigate().forward() – This command lets the user to navigate to the next web page with reference to the browser’s history.

Sample code:
driver.navigate().forward();

navigate().refresh() – This command lets the user to refresh the current web page there by reloading all the web elements.

Sample code:
driver.navigate().refresh();

navigate().to() – This command lets the user to launch a new web browser window and navigate to the specified URL.

Sample code:
driver.navigate().to(“https://google.com”);

Q #26) How to click on a hyper link using linkText?

driver.findElement(By.linkText(“Google”)).click();

The command finds the element using link text and then click on that element and thus the user would be re-directed to the corresponding page.

The above mentioned link can also be accessed by using the following command.

driver.findElement(By.partialLinkText(“Goo”)).click();

The above command find the element based on the substring of the link provided in the parenthesis and thus partialLinkText() finds the web element with the specified substring and then clicks on it.

Q #27) How to handle frame using WebDriver?

An inline frame acronym as iframe is used to insert another document with in the current HTML document or simply a web page into a web page by enabling nesting.

 

Select iframe by id
driver.switchTo().frame(ID of the frame);

Locating iframe using tagName
driver.switchTo().frame(driver.findElements(By.tagName(“iframe”).get(0));

Locating iframe using index

frame(index)
driver.switchTo().frame(0);

frame(Name of Frame)
driver.switchTo().frame(“name of the frame”);

frame(WebElement element)
Select Parent Window
driver.switchTo().defaultContent();

Q #28) When do we use findElement() and findElements()?

findElement(): findElement() is used to find the first element in the current web page matching to the specified locator value. Take a note that only first matching element would be fetched.

Syntax:

WebElement element = driver.findElements(By.xpath(“//div[@id=’example’]//ul//li”));
findElements(): findElements() is used to find all the elements in the current web page matching to the specified locator value. Take a note that all the matching elements would be fetched and stored in the list of WebElements.

Syntax:
List elementList = driver.findElements(By.xpath(“//div[@id=’example’]//ul//li”));

Continue reading Selenium Interview Questions..

Q #29) How to find more than one web element in the list?

At times, we may come across elements of same type like multiple hyperlinks, images etc arranged in an ordered or unordered list. Thus, it makes absolute sense to deal with such elements by a single piece of code and this can be done using WebElement List.

Sample Code

// Storing the list
List elementList = driver.findElements(By.xpath("//div[@id='example']//ul//li"));
// Fetching the size of the list
int listSize = elementList.size();
for (int i=0; i<listSize; i++)
{
// Clicking on each service provider link
serviceProviderLinks.get(i).click();
// Navigating back to the previous page that stores link to service providers
driver.navigate().back();
}

Q #30) What is the difference between driver.close() and driver.quit command?

close(): WebDriver’s close() method closes the web browser window that the user is currently working on or we can also say the window that is being currently accessed by the WebDriver. The command neither requires any parameter nor does is return any value.

quit(): Unlike close() method, quit() method closes down all the windows that the program has opened. Same as close() method, the command neither requires any parameter nor does is return any value.

Q #31) Can Selenium handle windows based pop up?

Selenium is an automation testing tool which supports only web application testing. Therefore, windows pop up cannot be handled using Selenium.

Q #32) How can we handle web based pop up?

WebDriver offers the users with a very efficient way to handle these pop ups using Alert Interface. There are the four methods that we would be using along with the Alert interface.

  • void dismiss() – The accept() method clicks on the “Cancel” button as soon as the pop up window appears.
  • void accept() – The accept() method clicks on the “Ok” button as soon as the pop up window appears.
  • String getText() – The getText() method returns the text displayed on the alert box.
  • void sendKeys(String stringToSend) – The sendKeys() method enters the specified string pattern into the alert box.

Syntax:
// accepting javascript alert 
                Alert alert = driver.switchTo().alert();
alert.accept();

Q #33) How can we handle windows based pop up?

Selenium is an automation testing tool which supports only web application testing, that means, it doesn’t support testing of windows based applications. However Selenium alone can’t help the situation but along with some third party intervention, this problem can be overcome. There are several third party tools available for handling window based pop ups along with the selenium like AutoIT, Robot class etc.

Q #34) How to assert title of the web page?

//verify the title of the web page
assertTrue(“The title of the window is incorrect.”,driver.getTitle().equals(“Title of the page”));

Q #35) How to mouse hover on a web element using WebDriver?

WebDriver offers a wide range of interaction utilities that the user can exploit to automate mouse and keyboard events. Action Interface is one such utility which simulates the single user interactions.

Thus, In the following scenario, we have used Action Interface to mouse hover on a drop down which then opens a list of options.

Sample Code:

1 // Instantiating Action Interface
2 Actions actions=new Actions(driver);
3 // howering on the dropdown
4 actions.moveToElement(driver.findElement(By.id("id of the dropdown"))).perform();
5 // Clicking on one of the items in the list options
6 WebElement subLinkOption=driver.findElement(By.id("id of the sub link"));
7 subLinkOption.click();

Q #36) How to retrieve css properties of an element?

The values of the css properties can be retrieved using a get() method:

Syntax:
driver.findElement(By.id(“id“)).getCssValue(“name of css attribute”);
driver.findElement(By.id(“id“)).getCssValue(“font-size”);

Q #37) How to capture screenshot in WebDriver?

1 import org.junit.After;
2 import org.junit.Before;
3 import org.junit.Test;
4 import java.io.File;
5 import java.io.IOException;
6 import org.apache.commons.io.FileUtils;
7 import org.openqa.selenium.OutputType;
8 import org.openqa.selenium.TakesScreenshot;
9 import org.openqa.selenium.WebDriver;
10 import org.openqa.selenium.firefox.FirefoxDriver;
11
12 public class CaptureScreenshot {
13 &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; WebDriver driver;
14 &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; @Before
15 &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; public voidsetUp() throws Exception {
16 &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; driver = new FirefoxDriver();
17  &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; driver.get("https://google.com");
18 &nbsp;&nbsp;&nbsp;&nbsp; }
19 &nbsp;&nbsp;&nbsp;&nbsp; @After
20 &nbsp;&nbsp;&nbsp;&nbsp; public void tearDown() throws Exception {
21 &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; driver.quit();
22 &nbsp;&nbsp;&nbsp;&nbsp; }
23
24 &nbsp;&nbsp;&nbsp;&nbsp; @Test
25 &nbsp;&nbsp;&nbsp;&nbsp; public void test() throwsIOException {
26 &nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; // Code to capture the screenshot
27 File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
28 &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; // Code to copy the screenshot in the desired location
29 FileUtils.copyFile(scrFile, newFile("C:\\CaptureScreenshot\\google.jpg"));&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;  &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;
30 &nbsp;&nbsp;&nbsp;&nbsp; }
31 }

Q #38) What is Junit?

Junit is a unit testing framework introduced by Apache. Junit is based on Java.

Q #39) What are Junit annotations?

Following are the Junit Annotations:

  • @Test: Annotation lets the system know that the method annotated as @Test is a test method. There can be multiple test methods in a single test script.
  • @Before: Method annotated as @Before lets the system know that this method shall be executed every time before each of the test method.
  • @After: Method annotated as @After lets the system know that this method shall be executed every time after each of the test method.
  • @BeforeClass: Method annotated as @BeforeClass lets the system know that this method shall be executed once before any of the test method.
  • @AfterClass: Method annotated as @AfterClass lets the system know that this method shall be executed once after any of the test method.
  • @Ignore: Method annotated as @Ignore lets the system know that this method shall not be executed.

Q #40) What is TestNG and how is it better than Junit?

TestNG  is an advance framework designed in a way to leverage the benefits by both the developers and testers. With the commencement of the frameworks, JUnit gained an enormous popularity across the Java applications, Java developers and Java testers with remarkably increasing the code quality. Despite being easy to use and straightforward, JUnit has its own limitations which give rise to the need of bringing TestNG into the picture. TestNG is an open source framework which is distributed under the Apache software License and is readily available for download.

TestNG with WebDriver provides an efficient and effective test result format that can in turn be shared with the stake holders to have a glimpse on the product’s/application’s health thereby eliminating the drawback of WebDriver’s incapability to generate test reports. TestNG has an inbuilt exception handling mechanism which lets the program to run without terminating unexpectedly.

There are various advantages that make TestNG superior to JUnit. Some of them are:

  • Added advance and easy annotations
  • Execution patterns can set
  • Concurrent execution of test scripts
  • Test case dependencies can be set

Q #41) How to set test case priority in TestNG?

Setting Priority in TestNG

Code Snippet

1 package TestNG;
2 import org.testng.annotations.*;
3 public class SettingPriority {
4  &nbsp;&nbsp;&nbsp;&nbsp; @Test(priority=0)
5  &nbsp;&nbsp;&nbsp;&nbsp; public void method1() { &nbsp;&nbsp;
6  &nbsp;&nbsp;&nbsp;&nbsp; }
7  &nbsp;&nbsp;&nbsp;&nbsp; @Test(priority=1)
8  &nbsp;&nbsp;&nbsp;&nbsp; public void method2() { &nbsp;
9  &nbsp;&nbsp;&nbsp;&nbsp; }
10  &nbsp;&nbsp;&nbsp;&nbsp; @Test(priority=2)
11  &nbsp;&nbsp;&nbsp;&nbsp; public void method3() { &nbsp;&nbsp;
12  &nbsp;&nbsp;&nbsp;&nbsp; }
13 }

Test Execution Sequence:

  1. Method1
  2. Method2
  3. Method3

Q #42) What is a framework?

Framework is a constructive blend of various guidelines, coding standards, concepts, processes, practices, project hierarchies, modularity, reporting mechanism, test data injections etc. to pillar automation testing.

Q #43) What are the advantages of Automation framework?

Advantage of Test automation framework.

  • Reusability of code
  • Maximum coverage
  • Recovery scenario
  • Low cost maintenance
  • Minimal manual intervention
  • Easy Reporting

Q #44) What are the different types of frameworks?

Below are the different types of frameworks:

  1. Module Based Testing Framework: The framework divides the entire “Application Under Test” into number of logical and isolated modules. For each module, we create a separate and independent test script. Thus, when these test scripts taken together builds a larger test script representing more than one module.
  2. Library Architecture Testing Framework: The basic fundamental behind the framework is to determine the common steps and group them into functions under a library and call those functions in the test scripts whenever required.
  3. Data Driven Testing Framework: Data Driven Testing Framework helps the user segregate the test script logic and the test data from each other. It lets the user store the test data into an external database. The data is conventionally stored in “Key-Value” pairs. Thus, the key can be used to access and populate the data within the test scripts.
  4. Keyword Driven Testing Framework: The Keyword driven testing framework is an extension to Data driven Testing Framework in a sense that it not only segregates the test data from the scripts, it also keeps the certain set of code belonging to the test script into an external data file.
  5. Hybrid Testing Framework: Hybrid Testing Framework is a combination of more than one above mentioned frameworks. The best thing about such a setup is that it leverages the benefits of all kinds of associated frameworks.
  6. Behavior Driven Development Framework: Behavior Driven Development framework allows automation of functional validations in easily readable and understandable format to Business Analysts, Developers, Testers, etc.

Q #45) How can I read test data from excels?

Test data can efficiently be read from excel using JXL or POI API.

Continue reading Selenium Interview Questions..

Q #46) What is the difference between POI and jxl jar?

# JXL jar POI jar
1 JXL supports “.xls” format i.e. binary based format. JXL doesn’t support Excel 2007 and “.xlsx” format i.e. XML based format POI jar supports all of these formats
2 JXL API was last updated in the year 2009 POI is regularly updated and released
3 The JXL documentation is not as comprehensive as that of POI POI has a well prepared and highly comprehensive documentation
4 JXL API doesn’t support rich text formatting POI API supports rich text formatting
5 JXL API is faster than POI API POI API is slower than JXL API

Q #47) What is the difference between Selenium and QTP?

Feature Selenium Quick Test Professional (QTP)
Browser Compatibility Selenium supports almost all the popular browsers like Firefox, Chrome, Safari, Internet Explorer, Opera etc QTP supports Internet Explorer, Firefox and Chrome. QTP only supports Windows Operating System
Distribution Selenium is distributed as an open source tool and is freely available QTP is distributed as a licensed tool and is commercialized
Application under Test Selenium supports testing of only web based applications QTP supports testing of both the web based application and windows based application
Object Repository Object Repository needs to be created as a separate entity QTP automatically creates and maintains Object Repository
Language Support Selenium supports multiple programming languages like Java, C#, Ruby, Python, Perl etc QTP supports only VB Script
Vendor Support As Selenium is a free tool, user would not get the vendor’s support in troubleshooting issues Users can easily get the vendor’s support in case of any issue

Q #48) Can WebDriver test Mobile applications?

WebDriver cannot test Mobile applications. WebDriver is a web based testing tool, therefore applications on the mobile browsers can be tested.

Q #49) Can captcha be automated?

No, captcha and bar code reader cannot be automated.

Q #50) What is Object Repository? How can we create Object Repository in Selenium?

Object Repository is a term used to refer to the collection of web elements belonging to Application Under Test (AUT) along with their locator values. Thus, whenever the element is required within the script, the locator value can be populated from the Object Repository. Object Repository is used to store locators in a centralized location instead of hard coding them within the scripts.

In Selenium, objects can be stored in an excel sheet which can be populated inside the script whenever required.

51.What are the advantages of Selenium Grid?

1.It allows running test cases in parallel thereby saving test execution time.
2.It allows multi-browser testing
3.It allows us to execute test cases on multi-platform

52. What is a hub in Selenium Grid?

A hub is a server or a central point that controls the test executions on different machines.

53. What is a node in Selenium Grid?

Node is the machine which is attached to the hub. There can be multiple nodes in Selenium Grid.

54.Which WebDriver implementation claims to be the fastest?

The fastest implementation of WebDriver is the HTMLUnitDriver. It is because the HTMLUnitDriver does not execute tests in the browser.

55.What are the Operating Systems supported by Selenium WebDriver?

  • Windows
  • Linux
  • Apple
  • 56.What are Soft Assert and Hard Assert in Selenium?
  • Soft Assert: Soft Assert collects errors during @TestSoft Assert does not throw an exception when an assert fails and would continue with the next step after the assert statement.
  • Hard Assert: Hard Assert throws an AssertExceptionimmediately when an assert statement fails and test suite continues with next @Test
  • 57.What are the different exceptions you have faced in Selenium WebDriver?

Some of the exceptions I have faced in my current project are

  1. ElementNotVisibleException
  2. StaleElementReferenceException

Element Not visible Exception:

This exception will be thrown when you are trying to locate a particular element on webpage that is not currently visible eventhough it is present in the DOM. Also sometimes, if you are trying to locate an element with the xpath which associates with two or more element.

Stale Element Reference Exception:

A stale element reference exception is thrown in one of two cases, the first being more common than the second.

The two reasons for Stale element reference are

  1. The element has been deleted entirely.
  2. The element is no longer attached to the DOM.

We face this stale element reference exception when the element we are interacting is destroyed and then recreated again. When this happens the reference of the element in the DOM becomes stale. Hence we are not able to get the reference to the element.

Some other exceptions we usually face are as follows:

  • WebDriverException
  • IllegalStateException
  • TimeoutException
  • NoAlertPresentException
  • NoSuchWindowException
  • NoSuchElementException
  1. What are the types of waits available in Selenium WebDriver?

In Selenium we could see three types of waits such as Implicit Waits, Explicit Waits and Fluent Waits.

  • Implicit Waits
  • Explicit Waits
  • Fluent Waits
  1. What is Implicit Wait In Selenium WebDriver?

Implicit waits tell to the WebDriver to wait for a certain amount of time before it throws an exception. Once we set the time, WebDriver will wait for the element based on the time we set before it throws an exception. The default setting is 0 (zero). We need to set some wait time to make WebDriver to wait for the required time.

  1. What is WebDriver Wait In Selenium WebDriver?

WebDriverWait is applied on a certain element with defined expected condition and time. This wait is only applied to the specified element. This wait can also throw an exception when an element is not found.

  1. What is Fluent Wait In Selenium WebDriver?

FluentWait can define the maximum amount of time to wait for a specific condition and frequency with which to check the condition before throwing an “ElementNotVisibleException” exception.

 

  1. How to input text in the text box without calling the sendKeys()?
1

2

3

4

5

6

// To initialize js object

JavascriptExecutor JS = (JavascriptExecutor)webdriver;

// To enter username

JS.executeScript(“document.getElementById(‘User’).value=’Techtutorialz.com'”);

// To enter password

JS.executeScript(“document.getElementById(‘Pass’).value=’tester'”);

 

  1. How to get an attribute value using Selenium WebDriver?

By using getAttribute(value);

It returns the value of the attribute passed as a parameter.

HTML:

1 <input name=”nameSelenium” value=”valueSelenium”>TechTutorialz</input>

Selenium Code:

1

2

3

String attributeValue = driver.findElement(By.name(“nameSelenium”)).getAttribute(“value”);

System.out.println(“Available attribute value is :”+attributeValue);

Output: valueSelenium

 

  1. How to submit a form using Selenium WebDriver?

We use “submit” method on element to submit a form

1 driver.findElement(By.id(“form_1”)).submit();

Alternatively, you can use click method on the element which does form submission

  1. How to press ENTER key on text box In Selenium WebDriver?

To press ENTER key using Selenium WebDriver, We need to use Selenium Enum Keys with its constant ENTER.

1 driver.findElement(By.xpath(“xpath”)).sendKeys(Keys.ENTER);
  1. What happens if I run this command. driver.get(“www.TechTutorialz.com”) ;

An exception is thrown. We need to pass HTTP protocol within driver.get() method.

1 driver.get(“https://www.TechTutorialz.com“);
  1. What is the alternative to driver.get()method to open an URL using Selenium WebDriver?

Alternative method to driver.get(“url”) method is driver.navigate.to(“url”)

  1. What is the difference between driver.get() anddriver.navigate.to(“url”)?

driver.get(): To open an URL and it will wait till the whole page gets loaded
driver.navigate.to(): To navigate to an URL and It will not wait till the whole page gets loaded

  1. Can I navigate back and forth in a browser in Selenium WebDriver?

We use Navigate interface to do navigate back and forth in a browser. It has methods to move back, forward as well as to refresh a page.

driver.navigate().forward(); – to navigate to the next web page with reference to the browser’s history
driver.navigate().back(); – takes back to the previous webpage with reference to the browser’s history
driver.navigate().refresh(); – to refresh the current web page thereby reloading all the web elements
driver.navigate().to(“url”); – to launch a new web browser window and navigate to the specified URL

  1. How to fetch the current page URL in Selenium?

To fetch the current page URL, we use getCurrentURL()

1 driver.getCurrentUrl();
  1. How can we maximize browser window in Selenium?

To maximize browser window in selenium we use maximize() method. This method maximizes the current window if it is not already maximized

1 driver.manage().window().maximize();
  1. How to delete cookies in Selenium?

To delete cookies we use deleteAllCookies() method

1 driver.manage().deleteAllCookies();
  1. What are the ways to refresh a browser using Selenium WebDriver?

There are multiple ways to refresh a page in selenium

  • Using navigate().refresh()command as mentioned in the question 45
  • Using driver.get(“URL”) on the current URL or using getCurrentUrl()
  • Using driver.navigate().to(“URL”) on the current URL or navigate().to(driver.getCurrentUrl());
  • Using sendKeys(Keys.F5)on any textbox on the webpage
  • Continue reading Selenium Interview Questions..
  1. What is the difference between driver.getWindowHandle() and driver.getWindowHandles() in Selenium WebDriver?

driver.getWindowHandle() – It returns a handle of the current page (a unique identifier)
driver.getWindowHandles() – It returns a set of handles of the all the pages available.

  1. How can we handle windows based pop up?

Selenium doesn’t support windows based applications. It is an automation testing tool which supports only web application testing. We could handle windows based popups in Selenium using some third party tools such as AutoIT, Robot class etc.

  1. How to handle hidden elements in Selenium WebDriver?

It is one of the most important selenium interview questions.

We can handle hidden elements by using javaScript executor

1 (JavascriptExecutor(driver)).executeScript(“document.getElementsByClassName(ElementLocator
  1. How to read a JavaScript variable in Selenium WebDriver?

By using JavascriptExecutor

1

2

3

4

5

// To initialize the JS object.

JavascriptExecutor JS = (JavascriptExecutor) webdriver;

// To get the site title.

String title = (String)JS.executeScript(“return document.title”);

System.out.println(“Title of the webpage : ” + title);

  1. What is JavaScriptExecutor and in which cases JavaScriptExecutor will help in Selenium automation?

In general, we click on an element using click() method in Selenium.

For example:

1 driver.findElement(By.id(“Id Value”)).click();

Sometimes web controls don’t react well against selenium commands and we may face issues with the above statement (click()). To overcome such kind of situation, we use JavaScriptExecutor interface.

It provides a mechanism to execute Javascript through Selenium driver. It provides “executescript” & “executeAsyncScript” methods, to run JavaScript in the context of the currently selected frame or window.

There is no need to write a separate script to execute JavaScript within the browser using Selenium WebDriver script. Just we use predefined interface named ‘Java Script Executor’. We need to import the JavascriptExecutor package in the script.

Package:

1 import org.openqa.selenium.JavascriptExecutor;

Syntax:

1

2

JavascriptExecutor js = (JavascriptExecutor) driver;

js.executeScript(Script,Arguments);

Script – The JavaScript to execute
Arguments – The arguments to the script(Optional). May be empty.
Returns – One of Boolean, Long, String, List, WebElement, or null.

Let’s see some scenarios we could handle using this Interface:

  1. To type Text in Selenium WebDriver without using sendKeys() method
    2. To click a Button in Selenium WebDriver using JavaScript
    3. To handle Checkbox
    4. To generate Alert Pop window in selenium
    5. To refresh browser window using Javascript
    6. To get innertext of the entire webpage in Selenium
    7. To get the Title of our webpage
    8. To get the domain
    9. To get the URL of a webpage
    10. To perform Scroll on an application using  Selenium
    11. To click on a SubMenu which is only visible on mouse hover on Menu
    12. To navigate to different page using Javascript
  1. List some scenarios which we cannot automate using Selenium WebDriver?
  2. Bitmap comparison is not possible using Selenium WebDriver
    2. Automating Captcha is not possible using Selenium WebDriver
    3. We cannot read bar code using Selenium WebDriver
  3. What is Page Object Model in Selenium?

Page Object Model is a Design Pattern which has become popular in Selenium Test Automation. It is widely used design pattern in Selenium for enhancing test maintenance and reducing code duplication. Page object model (POM) can be used in any kind of framework such as modular, data-driven, keyword driven, hybrid framework etc.  A page object is an object-oriented class that serves as an interface to a page of your Application Under Test(AUT). The tests then use the methods of this page object class whenever they need to interact with the User Interface (UI) of that page. The benefit is that if the UI changes for the page, the tests themselves don’t need to change, only the code within the page object needs to change. Subsequently, all changes to support that new UI is located in one place.

  1. What is Page Factory? 

We have seen that ‘Page Object Model’ is a way of representing an application in a test framework. For every ‘page’ in the application, we create a Page Object to reference the ‘page’ whereas a ‘Page Factory’ is one way of implementing the ‘Page Object Model’.

  1. What is the difference between Page Object Model (POM) and Page Factory?

Page Object is a class that represents a web page and hold the functionality and members.
Page Factory is a way to initialize the web elements you want to interact with within the page object when you create an instance of it.

  1. What are the advantages of Page Object Model Framework?

Code reusability – We could achieve code reusability by writing the code once and use it in different tests.

Code maintainability – There is a clean separation between test code and page specific code such as locators and layout which becomes very easy to maintain code. Code changes only on Page Object Classes when a UI change occurs. It enhances test maintenance and reduces code duplication.

Object Repository – Each page will be defined as a java class. All the fields in the page will be defined in an interface as members. The class will then implement the interface.

Readability – Improves readability due to clean separation between test code and page specific code

84.What are WebDriver waits? What is the difference between implicit wait, explicit wait and fluent wait in WebDriver? More specifically, what is the relation between WebDriverWait and FluentWait?

Here are examples of using each wait method in WebDriver with Java.

Implicit Wait

An implicit wait is to tell WebDriver to poll the DOM for a certain amount of time when trying to find an element or elements if they are not immediately available. The default setting is 0. Once set, the implicit wait is set for the life of the WebDriver object instance.

  • Example of using implicit wait

WebDriver driver = new FirefoxDriver();driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);driver.get(“http://somedomain/slow_loading_url”);

WebElement dynamicElement = driver.findElement(By.id(“dynamicElement”));

Continue reading Selenium Interview Questions..

  1. When should we use implicit waits?

Normally, it is not recommended to use implicit waits, when we can use explicit waits or fluent waits.

Explicit Wait

An explicit wait is a code that you define to wait for a certain condition to occur before proceeding further in the code. WebDriverWait by default calls the ExpectedCondition every 500 milliseconds until it returns successfully.

Example of using explicit wait

WebDriver driver = new FirefoxDriver();driver.get(“http://somedomain/someurl”);

WebElement dynamicElement = (new WebDriverWait(driver, 10)).until(ExpectedConditions.presenceOfElementLocated(By.id(“dynamicElement”)));

When should we use explicit waits?

We would normally use explicit wait if an element takes a long time to load. We also used explicit wait to check CSS property of an element (presence, clickability. etc) which can change in Ajax applications.

Fluent Wait

When using the FluentWait instance, we can specify:

  • The frequency with which FluentWait has to check the conditions defined.
  • Ignore specific types of exception waiting such as NoSuchElementExceptions while searching for an element on the page.
  • The maximum amount of time to wait for a condition

Example of using FluentWait

// Waiting 30 seconds for an element to be present on the page, checking// for its presence once every 5 seconds.Wait<WebDriver> wait = new FluentWait<WebDriver>(driver)    .withTimeout(30, SECONDS)    .pollingEvery(5, SECONDS)    .ignoring(NoSuchElementException.class); WebElement foo = wait.until(new Function<WebDriver, WebElement>() {  public WebElement apply(WebDriver driver) {  return driver.findElement(By.id(“foo”));}});

When should we use FluentWait?

When you try to test the presence of an element that may appear after every x seconds/minutes.

  1. Difference Between WebDriverWait and FluentWait

WebDriverWait is a subclass of FluentWait. In FluentWait you have more options to configure, along with maximum wait time, like polling interval, exceptions to ignore etc.

So, instead of waiting and then using findElement:

WebDriverWait wait = new WebDriverWait(driver,18);

wait.until(ExpectedConditions.elementToBeClickable(By.linkText(“Account”)));

WebElement element = driver.findElement(By.linkText(“Account”));

element.sendKeys(Keys.CONTROL);element.click();

we can use: WebElement element = wait.until(ExpectedConditions.elementToBeClickable(By.linkText(“Account”)));

Visit other interview questions..

Manual Testing Interview Questions
Performance Testing Interview Questions
Appium Interview Questions
Mobile Applications Testing Interview Questions
Test Manager Interview Questions

 

Subscribe now

Receive weekly newsletter with educational materials, new courses, most popular posts, popular books and much more!