Automation Testing with Selenium Webdriver (Java)

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.

What are the benefits of Automation Testing?

Benefits of Automation testing are:

  • Supports execution of repeated test cases
  • Aids in testing a large test matrix
  • Enables parallel execution
  • Encourages unattended execution
  • Improves accuracy thereby reducing human-generated errors
  • Saves time and money

What is a framework?

A 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.

What are the advantages of the Automation framework?

Advantages of Test Automation framework:

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

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 a number of logical and isolated modules. For each module, we create a separate and independent test script. Thus, when these test scripts have 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 an easily readable and understandable format to Business Analysts, Developers, Testers, etc.

Why should Selenium be selected as a test tool?

Advantages of Selenium:
  • is free and open source
  • has a large user base and helping communities
  • has cross Browser compatibility (Firefox, Chrome, Internet Explorer, Safari etc.)
  • has great platform compatibility (Windows, Mac OS, Linux etc.)
  • supports multiple programming languages (Java, C#, Ruby, Python, Pearl etc.)
  • has fresh and regular repository developments
  • supports distributed testing

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 Integrated Development Environment (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 users 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.

What are the testing types that can be supported by Selenium?

Selenium supports the following types of testing:

  • Functional Testing
  • Regression Testing

What are the limitations of Selenium?

  • Selenium supports testing of only web-based applications
  • Mobile applications cannot be tested using Selenium
  • Captcha and Bar code 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.
  • User is expected to possess prior programming language knowledge.

What is the difference between Selenium IDE, Selenium RC, and WebDriver?

FeatureSelenium IDESelenium RCWebDriver
Browser
Compatibility
Selenium IDE comes as a Firefox plugin, thus it supports only FirefoxSelenium RC supports a varied range of versions of Mozilla Firefox, Google Chrome, Internet Explorer and OperaWebDriver supports a varied range of versions of Mozilla Firefox, Google Chrome, Internet Explorer and Opera. Also supports HtmlUnitDriver which is a GUI less or headless browser.
Record and PlaybackSelenium IDE supports record and playback featureSelenium RC doesn’t support record and playback featureWebDriver doesn’t support record and playback feature
Server RequirementSelenium IDE doesn’t require any server to be started before executing the test scriptsSelenium RC requires a server to be started before executing the test scriptsWebDriver doesn’t require any server to be started before executing the test scripts
ArchitectureSelenium IDE is a Javascript based frameworkSelenium RC is a JavaScript-based FrameworkWebDriver uses the browser’s native compatibility to automation
Object OrientedSelenium IDE is not an object-oriented toolSelenium RC is semi object-oriented toolWebDriver is a purely object-oriented tool
Dynamic Finders (for locating web elements on a webpage)Selenium IDE doesn’t support dynamic findersSelenium RC doesn’t support dynamic findersWebDriver supports dynamic finders
Handling Alerts, Navigations, DropdownsSelenium IDE doesn’t explicitly provides aids to handle alerts, navigations, dropdownsSelenium RC doesn’t explicitly provides aids to handle alerts, navigations, dropdownsWebDriver offers a wide range of utilities and classes that help in handling alerts, navigations, and dropdowns efficiently and effectively
WAP (iPhone/Android) TestingSelenium IDE doesn’t support testing of iPhone/Android applicationsSelenium RC doesn’t support testing of iPhone/Andriod applicationsWebDriver is designed in a way to efficiently support testing of iPhone/Andriod applications. The tool comes with a large range of drivers for WAP based testing. For example, AndroidDriver, iPhoneDriver
Listener SupportSelenium IDE doesn’t support listenersSelenium RC doesn’t support listenersWebDriver supports the implementation of Listeners
SpeedSelenium IDE is fast as it is plugged in with the web-browser that launches the test. Thus, the IDE and browser communicates directlySelenium RC is slower than WebDriver as it doesn’t communicate directly with the browser; rather it sends selenese commands over to Selenium Core which in turn communicates with the browserWebDriver communicates directly with web browsers. Thus making it much faster.

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 make it exceptionally easy to learn with minimal acquaintances to any programming language. Selenium IDE is an ideal tool for a naïve user.

What is Selenese?

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

What are the different types of locators in Selenium?

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

Which locator is the fastest one to identify an element?

Name Locator

What difference is 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.

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.

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.

What is the 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. In order to handle the same origin policy, Selenium Remote Control was introduced.

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.

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 to as Selenium 1.

Which is the latest Selenium tool?

WebDriver

How do I launch the browser using WebDriver?

The following syntax can be used to launch the Browser:

WebDriver driver = new FirefoxDriver();
WebDriver driver = new ChromeDriver();
WebDriver driver = new InternetExplorerDriver();

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

What are the different types of waits available in WebDriver?

There are two types of waits available in WebDriver:

  • 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.

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(“username”);

How can you find if an element is 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.

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();

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();

How to select a value in a dropdown?

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

Syntax:

  • selectByValue:

    Select selectByValue = new Select(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 = new Select(driver.findElement(By.id(“SelectID_Three”)));selectByIndex.selectByIndex(2);

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.

Example:

driver.navigate().to(“https://Yahoo.com”);

driver.findElement(By.linkText(“Yahoo”)).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(“Yah”)).click();

The above command finds 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.

How to handle frame in WebDriver?

An inline frame acronym as iframe is used to insert another document within 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();

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 note that only the 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 the specified locator value. Take note that all the matching elements would
be fetched and stored in the list of WebElements.

Syntax:

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

How to find more than one web element in the list?

At times, we may come across elements of the 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 <WebElement> 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();
}

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

quit(): Unlike a 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 it return any value.

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 it return any value.

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

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();

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.

How to assert the 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”));

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:

// Instantiating Action Interface
Actions actions=new Actions(driver);

// howering on the dropdownactions.moveToElement(driver.findElement(By.id(“id of the dropdown”))).perform();

// Clicking on one of the items in the list optionsWebElement subLinkOption=driver.findElement(By.id(“id of the sub link”));subLinkOption.click();

How to retrieve the 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”);

How to capture screenshot in WebDriver?

Syntax:

EventFiringWebDriver eDriver=new EventFiringWebDriver(driver); File srcFile = eDriver.getScreenshotAs(OutputType.FILE); FileUtils.copyFile(srcFile, new File(imgPath));

How can I read test data from excels?

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

What is the difference between POI and jxl jar?

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

What is the difference between Selenium and QTP?

FeatureSeleniumQuick Test Professional (QTP)
Browse CompatibilitySelenium supports almost all the popular browsers like Firefox, Chrome,  Safari, Internet Explorer, Opera etcQTP supports Internet Explorer, Firefox and Chrome. QTP only supports Windows Operating System
DistributionSelenium is distributed as an open source tool and is freely availableQTP is distributed as a licensed tool and is commercialized
Application under TestSelenium supports testing of only web-based applicationsQTP supports testing of both the web-based application and windows based application
Object RepositoryObject Repository needs to be created as a separate entityQTP automatically creates and maintains Object Repository
Language SupportSelenium supports multiple programming languages like Java, C#, Ruby, Python, Perl etcQTP supports only VB Script
Vendor SupportAs Selenium is a free tool, the user would not get the vendor’s support in troubleshooting issuesUsers can easily get the vendor’s support in case of any issues

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.

Can captcha be automated?

No, captcha and bar code reader cannot be automated.

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.

What is Selenium server and how does it differ from Selenium hub?

Selenium server is a standalone application for using a single server as a test node. Selenium hub acts as a proxy in front of one or more Selenium node instances. A hub + node(s) is called a Selenium grid. Running Selenium server is similar to creating a Selenium grid from a hub and a single node on the same host

How do you connect to Database from selenium?

We can use the Connection object for the following things:

  • It creates the Statement, PreparedStatement and CallableStatement objects for executing the SQL statements.
  • It helps us to Commit or roll back a JDBC transaction.
  • If you want to know about the database or data source to which you are connected then the Connection object gathers information about the database or data source by the use of DatabaseMetaData.
  • It helps us to close the data source. The Connection.isClosed() method returns true only if the Connection.close() has been called. This method is used to close all the connection.

Firstly we need to establish a connection with the database. This is done by using the method DriverManager.getConnection(). This method takes a string containing a URL. The DriverManager class attempts to locate a driver that can connect to the database represented by the string URL. Whenever the getConnection() method is called the DriverManager class checks the list of all registered Driver classes that can connect to the database specified in the URL.

Syntax:

Selenium database connection example
String url = “jdbc: odbc: makeConnection”;
Connection con = DriverManager.getConnection(url, “userID”, “password”);

How do you verify an object present on multiple pages?

Check on each page assertTrue(selenium.isElementPresent(locator));

What is the difference between a single and double slash used in XPath?

If XPath starts selection from the document node, it’ll allow you to create ‘absolute’ path expressions.

e.g. “/HTML/body/p” matches all the paragraph elements

If XPath starts selection matching anywhere in the document, then it’ll allow you to create ‘relative’ path expressions.

e.g. “//p” matches all the paragraph elements

How will you write a User Extension for Selenium IDE/RC?

User extensions are stored in a separate file that Selenium IDE or Selenium RC uses to activate the extensions. It comprises of function definitions which are written in JavaScript. Because Selenium’s core is developed in JavaScript, creating an extension follows the similar standard rules for prototypal languages. To create an extension, we have to write a function in the following design format.

Selenium.prototype.doFunctionName = function(){}

How do you verify the presence of an element after the successful page loading?

The “do” in front of the function name tells Selenium that this function can be called as a command for a step instead of an internal or private function.

It can be achieved with the following code. Just mention some time value to check the element (in seconds) like:

public void waitForElementPresent(String element, int timeout)
throws Exception {
for (int second = 0;; second++)
{
if (second >= timeout)
fail(“Timeout. Unable to find the Specified
element” + element);
try {
if (selenium.isElementPresent(element))
break;
} catch (Exception e) {
}
Thread.sleep(1000);
}
}

What do you know about Selenium Grid? What capabilities does it provide?

Selenium Grid is a tool that dramatically speeds up functional testing of web-apps by leveraging your existing computing infrastructure. It allows you to easily run multiple tests in parallel, on multiple machines, in a heterogeneous environment.

Based on the excellent Selenium web testing tool, Selenium Grid allows you to run multiple instances of Selenium Remote Control in parallel. Even better, it makes all these Selenium Remote Controls appear as a single one, so your tests do not have to worry about the actual infrastructure. Selenium Grid cuts down on the time required to run a Selenium test suite to a fraction of the time that a single instance of Selenium instance would take to run.

How will you start the selenium server from your Java class?

Selenium server sample

try {
seleniumServer = new SeleniumServer();
seleniumServer.start();
} catch (Exception e) {
e.printStackTrace();
}

What are the verification points available in Selenium?

  • Check for the page title
  • Check for certain text
  • Check for a certain element (text box, drop down, table etc.)

What is XPath? When should you use XPath in Selenium?

XPath is a way to navigate in an HTML/XML document and this can be used to identify elements in a web page. You may have to use XPath when there is no name/id associated with an element on the page or only a partial part of name/id is constant.

  • Direct child (Absolute) is denoted with – /
  • Relative child (Relative) is denoted with – //
  • Id, class, names can also be used with XPath –
    • //input[@name=’q’]
    • //input[@id=’lst-ib’]
    • //input[@class=’ lst’]

If only part of id/name/class is constant than “contains” can be used as –

    • //input[contains(@id,’lst-ib’)]

What is CSS locator strategy in Selenium? Explain with example.

CSS location strategy can be used with Selenium to locate elements, it works using cascade
style sheet location methods in which –

  • A direct child is denoted with – (A space symbol)
  • A relative child is denoted with – >
  • Id, class, names can also be used with XPath –
    • css=input[name=’q’]
    • css=input[id=’lst-ib’] or input#lst-ib
    • css=input[class=’lst’] or input.lst

If only part of id/name/class is constant than “contains” can be used as –

    • css=input[id*=’lst-ib’)]

Element location strategy using inner text

    • css = a:contains(‘log out’)

There are many locators like id, name, XPath, CSS locator, which one should I use?

If there are unique names or identifier available then they should be used instead of XPath and CSS locators. If not then CSS locators should be given preference as their evaluation is faster than XPath in most modern browsers.

What is the mechanism to handle multiple popups in selenium?

  • Multiple popups can be handled by using the command getWindowHandles().
  • Then store all the window names into Set<String> variable and transform it into an array.
  • Next, by using the array index, you can navigate to a specific window by using
    driver.switchTo().window(ArrayIndex);

How do you handle Ajax controls using selenium?

Let’s consider an example. Say the google test box which is an ajax control and when we enter some text into it, then it displays the auto-suggested values.

To work with such controls, you need to capture all the suggested values in a string after entering the value in the text box. Then, just split the string and take the values.

What are the advantages of Selenium Web driver over Selenium RC?

Selenium RC’s architecture is quite complicated while WebDriver’s architecture is simpler than Selenium RC’s.

Though Selenium RC is slower since it uses an additional JavaScript program called Selenium Core. On the contrary, WebDriver is faster than Selenium RC since it speaks directly to the browser and uses the browser’s own engine to control it.

Selenium Core, just like other JavaScript codes, can access disabled elements. Web Driver interacts with page elements in a more realistic way.

Selenium RC’s API set is already evolved but contains redundancies and often confusing commands. WebDriver APIs are simpler and do not contain any redundant or confusing commands.

Selenium RC cannot support the headless HtmlUnit browser. It needs a real, visible browser to operate on. Web Driver can support the headless HtmlUnit browser.

Selenium RC has built-in test result generator and it automatically generates an HTML file of test results. Web Driver has no built-in command that automatically generates a Test Results File.

State any difference between “GET” and “NAVIGATE”?

Get method will get a page to load or get page source or get the text that’s all. Whereas navigate will guide through the history like refresh, back, forward. For example, if we want to move forward and do some functionality and back to the home page. This can be achieved through navigate() method only. driver.get() will wait till the whole page gets loaded and driver.navigate() will just redirect to that page and will not wait.

How is the implicit Wait different from Explicit wait?

Implicit Wait sets internally a timeout that will be used for all consecutive Web Element searches. It will try lookup the element again and again for the specified amount of time before throwing a NoSuchElementException if the element could not have been found. It does only this and can’t be forced into anything else – it waits for elements to show up.

Explicit Wait or just Wait is a one-timer used by you for a particular search. It is more extensible in the means that you can set it up to wait for any condition you might like. Usually, you can use some of the prebuilt Expected Conditions to wait for elements to become clickable, visible, invisible, etc., or just write your own condition that suits your needs.

How to Handle Alerts/Popups in Selenium WebDriver?

There are two types of alerts which are commonly referred–

  • Windows-based alert pop-ups
  • Web-based alert pop-ups

Web-based alert pop-ups.

  1. WebDriver offers the users with a very efficient way to handle these pop-ups using Alert interface.
  2. void dismiss() – The dismiss() method clicks on the “Cancel” button as soon as the popup window appears.
  3. void accept() – The accept() method clicks on the “Ok” button as soon as the popup window appears.
  4. String getText() – The getText() method returns the text displayed on the alert box.
  5. void sendKeys(String stringToSend) – The sendKeys() method enters the specified string pattern into the alert box.

Windows-based alert pop-ups.

Handling window based pop-ups have always been a little tricky as we know Selenium is an automation testing tool which supports only web application testing, that means, it doesn’t support windows based applications and window alert is one of them.

  1. Robot class is a java based utility which emulates the keyboard and mouse actions and can be effectively used to handling window based pop up with the help of keyboard events.
  2. The keyPress and keyRelease methods simulate the user pressing and releasing a certain key on the keyboard respectively

How to take a screenshot with Selenium WebDriver?

Selenium capture screenshot:

Import org.apache.commons.io.FileUtils;
WebDriver driver = new FirefoxDriver();
driver.get(“http://www.google.com/”);
File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
// Now you can do whatever you need to do with it, for example copy somewhere
FileUtils.copyFile(scrFile, new File(“c:\\tmp\\screenshot.png”))

How can I address the SSL Certificate issue in Firefox with WebDriver (or) how to manage the secured connection error in HTTPS?

FirefoxProfile profile = new FirefoxProfile();
profile.setAcceptUntrustedCertificates(true);
profile.setAssumeUntrustedCertificateIssuer(false);
driver=new FirefoxDriver(profile);

How can I fix the SSL certification issue in IE?

Handle the SSL certification issue in IE

<strong>driver.navigate().to(“javascript:document.getElementById(‘overridelink’).click()”);</strong>

What are the available locators in Selenium WebDriver?

  1. ID,
  2. Name,
  3. CSS,
  4. XPath,
  5. Classname,
  6. TagName,
  7. LinkText, and
  8. Partial Link Text.

How can I handle AJAX controls in WebDriver?

AJAX stands for Asynchronous JavaScript and XML. It does not rely on the extra overhead of opening and closing tags that are needed to create valid XML. Most of the time WebDriver automatically handle the Ajax controls and calls/ In case if it is not able to handle, you can follow the below way to handle.

WebElement AjaxElement = (new WebDriverWait(driver,
10)).until(ExpectedConditions.presenceOfElementLocated(By.
&lt;locatorType&gt;(“&lt;locator Value&gt;”)));

How to perform Mouse over action on the submenu item of a header menu?

With the actions object you should first move the menu title, and then move to the popup menu item and click it. Don’t forget to call actions.perform() at the end. Here’s some sample Java code:

Actions actions = new Actions(driver);
WebElement menuHoverLink = driver.findElement(By.linkText(“Menu heading”));
actions.moveToElement(menuHoverLink);
WebElement subLink = driver.findElement(By.cssSelector(“#headerMenu .subLink”));
actions.moveToElement(subLink);
actions.click();
actions.perform();

Can you broadly classify and compare the TDD, BDD and DDD frameworks?

TDD – Test Driven Development.

It’s also called test-driven design, is a method of software development in which unit testing is repeatedly done on the source code. Write your tests watch it fails and then refactor it. The concept is we write these tests to check if the code we wrote works fine. After each test, refactoring is done and then the same or a similar test is performed again. The process is iterated as many times as necessary until each unit is functionally working as expected. TDD was introduced first by XP. I believe I have explained enough in simple terms.

BDD – Behavior Driven Development.

The behavior-driven development combines the general techniques and principles of TDD with ideas from domain-driven design. Its purpose is to help the folks devising the system (i.e. the developer) identify appropriate tests to write–that is, tests that reflect the behavior desired by the stakeholders.

What is a Data-driven framework & how is it different from the Keyword Driven framework?

Data-driven framework.

In this framework, test case logic resides in test Scripts. Test Data is separated and kept outside the Test Scripts. Test Data is read from the external files (Excel File) and are loaded into the variables inside the Test Script. Variables are used both for Input values and for Verification values.

Keyword Driven.

The keyword/table driven framework requires the development of data tables and keywords. They are independent of the test automation tool used to execute them. Tests can be designed with or without the Application. In a keyword-driven test, the functionality of the Application-under-test is documented in a table as well as in step-by-step instructions for each test.

Explain the advantages of using TestNG over JUnit framework?

Advantages of TestNG over Junit.

  • In JUnit, we have to declare @BeforeClass and @AfterClass. It is a constraint in JUnit whereas in TestNG there is no constraint like this.
  • Additional Levels of setUp/tearDown level are available in TestNG.
    • @ Before/AfterSuite
    • @Before/AfterTest and
    • @Before/AfterGroup
  • There is no need to extend any class in TestNG.
  • There is no method name constraint in TestNG as in JUnit.
  • In TestNG, we can tell the test that one method is dependent on another method whereas in JUnit this is not possible.
  • Grouping of test cases is available in TestNG whereas the same is not available in JUnit. Execution can be done based on Groups. For example, if you have defined many cases and segregated them by defining 2 groups as Sanity and Regression. And if you only want to execute the “Sanity” cases then just tell TestNG to execute the “Sanity”. TestNG will automatically execute the cases belonging to the “Sanity” group.
  • Also, TestNG supports parallel test case execution.

In TestNG, Parameters are keywords that modify the annotation’s function. You can read more about the parameters from the TestNG in the tutorials section.

Can we run a group of test cases using TestNG?

Yes, the TestNG framework supports to execute multiple test cases with the help of test groups.

It provides the following options to run test cases from a specific group.

If you want to execute the test cases based on one of the groups like regression test or
smoke test-

@Test(groups = {“regression-tests”, “smoke-tests”})

Which WebDriver implementation claims to be the fastest and why?

The fastest and leaner implementation of WebDriver is HTMLUnitDriver.

The simple reason is that the HTMLUnitDriver does not execute tests in the browser. Instead, it uses a plain HTTP request-response mechanism for running test cases.

This approach is far quicker than launching a browser for test execution.

How do I use Selenium Grid while using Java, .Net or Ruby?

  • With Java, you can take advantage of parallel testing capabilities of TestNG to drive your Selenium grid tests.
  • With .Net, you can use “Gallio” to execute your tests in parallel.
  • With Ruby, you can use “DeepTest” to distribute your tests.

What is Junit? What are Junit annotations?

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

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 methods.
  • @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 methods.
  • @AfterClass: Method annotated as @AfterClass lets the system know that this method shall be executed once after any of the test methods.
  • @Ignore: Method annotated as @Ignore lets the system know that this method shall not be executed.

What is TestNG and how is it better than Junit?

TestNG is an advanced framework designed in a way to leverage the benefits by both the developers and testers. With the commencement of the frameworks, JUnit gained 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 stakeholders 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

Was this article helpful?