Selenium Material
Selenium Material
1. Selenium IDE
1.1 Introduction
1.4 Advantages
1.5 Disadvantages
1.6 Recording
2.1 HTML
2.2 Java
3. Web Driver
4. Selenium WebDriver
4.8 Pop-Ups:
4.9 Actions Class (or) Working with menu dropdowns (or) Mouse and
Keyboard Actions:
4.13 Iframes
5. Software Testing
5.1 What is mean by Testing?
5.3 Automation
5.4 Advantages
pg. 3
1. SELENIUM IDE:
1.1 INTRODUCTION:
The selenium IDE is the tool you use to develop your selenium test cases by using
record and play back.
1.2 HISTORY OF SELENIUM:
In 2004 invented by Jason Huggins and team
Originally name is JavaScript Functional Tester (JSFT)
Open-source browser-based integration framework built originally by
Thought Works.
100% JavaScript and HTML
Web Testing Tool
That supports testing web 2.0 applications.
Supports for cross –Browser testing (On Multiple browsers)
Supports multiple operating systems.
1.3 SELENIUM COMPONENTS:
Selenium IDE (Integrated Development Environment) - Record & Play back
Selenium Core –Runs the test suits on the web server where the web
application is deployed.
Selenium RC 1.0 – Server /Client (Selenium. Start /Selenium. Stop)
Selenium Grid – Performance Tool
Selenium 2.0 (Known as selenium Web Driver)
1.4 ADVANTAGES:
It is an easy –to-use.
It is just Firefox plug in and is generally the most efficient way to develop test
cases.
Very useful tool for beginners
Firefox extension which allows record/Play testing paradigm.
Creates the simplest possible locator based on Selene’s.
Look at various possible commands in the dropdown.
Records a test at HTML file.
We can export the test as Java /Ruby etc...
1.5 DISADVANTAGES:
Selenium-IDE does not directly support:
Condition statements
Iteration or looping
Logging and reporting of test results.
Error handling, particularly unexpected errors
Database testing
Test case grouping
Re-execution of failed tests
Test case dependency
Capture screenshots on test failures.
pg. 4
Results Report generations
1.6 RECORDING:
2.1 HTML:
To start automating any web application it is required to have a web application. This topic
explains how to create a small webpage in our own machine.
Let is create a web page which has the following elements in it.
pg. 5
The page should appear as follows.
This is the required web page. The HTML code should be as follows.
<html>
<head>
<title>Welcome to html</title>
</head>
<body>
<table >
<tr>
</tr>
</table>
<table >
pg. 6
<tr>
</tr>
</table>
<table >
<tr>
<td><img src="mobile.jpg"/></td>
</tr>
<tr>
<img src="flip.jpg"/></a></td>
</tr>
</table>
<table>
<tr>
<td><select name="city">
<option value="1">Bangalore</option>
<option value="2">Chennai</option>
<option value="3">Kolkatta</option>
<option value="4">Delhi</option>
</select></td>
<option value="1">Bangalore</option>
<option value="2">Chennai</option>
<option value="3">Kolkatta</option>
<option value="4">Delhi</option>
</select></td>
</tr>
</table>
pg. 7
<table >
<tr>
<td><textarea name="description"></textarea></td>
</tr>
</table>
</body>
</html>
Write the above code in Note pad and save as filename.html. Double click on the file where
it is saved. The required html is obtained.
Mandatory Additional
Sl.no Element HTML Tag Property Value property Value
1 Text box Input Type Text Name/ID User defined
2.2 JAVA:
package demopack;
pg. 8
o1.bangalore();
o1.chennai();
Two t1=new Two();
t1.pune();
t1.delhi();
}
}
class One{
public void bangalore() {
System.out.println("This is Bangalore");
}
public void chennai() {
System.out.println("This is Chennai");
}
}
class Two{
public void pune() {
System.out.println("This is Pune");
}
public void delhi() {
System.out.println("This is Delhi");
}
}
Output:
This is Beginning.
This is Bangalore.
This is Chennai.
This is Pune.
This is Delhi.
package demopack;
}
class Three{
public void add(int a, int b) {
int c=a+b;
System.out.println(c);
}
public void bangalore() {
System.out.println("This is Bangalore");
}
}
pg. 9
Output:
This is Beginning.
30
This is Bangalore.
package demopack;
}
class Four{
public static void bangalore() {
System.out.println("This is Bangalore");
}
public static void chennai() {
System.out.println("This is Chennai");
}
public void pune() {
System.out.println("This is Pune");
}
}
Output:
This is Beginning.
This is Bangalore.
This is Chennai.
This is Pune.
package demopack;
pg. 10
f1.pune();
}
class Five{
public int add(int a, int b) {
int c=a+b;
return c;
}
public void pune() {
System.out.println("This is Pune");
}
public int multiplication(int a, int b) {
int d=a*b;
return d;
}
}
Output:
This is Beginning.
30
50
50
This is Pune.
Properties of Constructor:
package demopack;
}
class Six{
Six(){
System.out.println("This is Six");
}
public void pune() {
System.out.println("This is Pune");
}
}
pg. 11
Output:
This is Beginning.
This is Six.
This is Pune.
Method Overloading:
package demopack;
}
class Seven{
public void add(int a, int b) {
int c=a+b;
System.out.println(c);
}
public void add(int a, int b, int c) {
int d=a+b+c;
System.out.println(d);
}
public void add(int a, int b, String message) {
int e=a+b;
System.out.println(message+e);
}
public void pune() {
System.out.println("This is Pune");
}
}
Output:
This is Beginning.
30
70
This is addition50.
This is Pune.
package demopack;
pg. 12
System.out.println("This is Beginning ");
Eight.add(10, 20);
Eight.add(10, 20, 30);
Eight.add(10, 20, "This is addition");
Eight e1=new Eight();
e1.bangalore();
}
}
class Eight{
public static void add(int a, int b) {
int c=a+b;
System.out.println(c);
}
public static void add(int a, int b, int c) {
int d=a+b+c;
System.out.println(d);
}
public static void add(int a, int b, String message) {
int e=a+b;
System.out.println(message+e);
}
public void bangalore() {
System.out.println("This is Bangalore");
}
}
Output:
This is Beginning.
30
60
This is addition30.
This is Bangalore.
package demopack;
}
class Nine {
Nine(){
System.out.println("This is Nine");
}
Nine(int a, int b){
int c=a+b;
System.out.println(c);
pg. 13
}
Nine(int a, int b, int c){
int d=a+b+c;
System.out.println(d);
}
public void pune() {
System.out.println("This is Pune");
}
}
Output:
This is Beginning.
This is Nine.
30
60
This is Pune.
package demopack1;
import demopack2.*;
}
class One{
public void bangalore() {
System.out.println("This is Bangalore");
}
public void chennai() {
System.out.println("This is Chennai");
}
}
package demopack1;
pg. 14
}
public void Tirupathi() {
System.out.println("This is Tirupati");
}
}
package demopack2;
package demopack2;
Output:
This is Beginning.
This is Bangalore.
This is Chennai.
This is Mumbai.
This is Tirupati.
This is Delhi.
This is Pune.
This is Agra.
Single Inheritance:
package demopack2;
}
class Five extends Six{
pg. 15
public void bangalore() {
System.out.println("This is Bangalore");
}
public void chennai() {
System.out.println("This is Chennai");
}
}
class Six{
public void pune() {
System.out.println("This is Pune");
}
public void delhi() {
System.out.println("This is Delhi");
}
}
Output:
This is Beginning.
This is Bangalore.
This is Chennai.
This is Delhi.
This is Pune.
This is Delhi.
This is Pune.
Multilevel Inheritance:
package demopack2;
}
class Seven extends Eight{
public void bangalore() {
System.out.println("This is Bangalore");
}
public void chennai() {
pg. 16
System.out.println("This is Chennai");
}
}
class Eight extends Nine{
public void pune() {
System.out.println("This is Pune");
}
public void delhi() {
System.out.println("This is Delhi");
}
}
class Nine{
public void agra() {
System.out.println("This is Agra");
}
public void mumbai() {
System.out.println("This is Mumbai");
}
}
Output:
This is Beginning.
This is Bangalore.
This is Chennai.
This is Delhi.
This is Pune.
This is Agra.
This is Mumbai.
This is Delhi.
This is Pune.
This is Mumbai.
This is Agra.
This is Agra.
This is Mumbai.
package demopack2;
char arr[]=actual.toCharArray();
int si=actual.length();
pg. 17
Output:
gniniarT muineleS
package demopack1;
}
interface Itest{
public void display();
}
class Three implements Itest {
public void display() {
System.out.println("This is Display");
}
Output
This is Beginning.
This is Display.
3. WEB DRIVER :
8 Element Locators:
Id
Name
Link Text
X-Path
Css Selector
Class name
Tag Name
Partial Link Text
If any element has name or id property, we can use the value of id or name property to
identify the element. If the element is a link, we can use the link text to identify it. If the
pg. 18
element does not have id or name property and if it is not a link, then we need to write
either Css selector or X-path expression.
Elements are generally identified by its html tag, its properties and values. To identify an
element, we should be able to inspect the html source of the element. By default, each
browser provides an inspector tool.
Syntax: htmltag[attribute=’value’]
Ex: input[id=’uname’]
input[id=’rem’]
a[class=’myclass’]
select[id=’city’]
a[class=’myclass’] if any element has class attribute then we can use the
Syntax: htmltag.classvalue
Ex: a.myclass
input [id=’female’] if any element has id attribute then we can use the
Syntax: html#idvalue
Ex: input#female
To identify elements in the web page, we can use X-path expression. There are two
categories of X-path. They are X-path-position and X-path attributes.
pg. 19
3.3.1 X-PATH POSITION (ABSOLUTE XPATH):
To identify an element by its position in html hierarchy we can use X-path position.
To identify the x-path open the application in the chrome browser right click on the target
element inspect element click on the tag name and press ctrl+f.
Example: For the above html page if we want to find out the X-path for username text box.
Then the X-path will be.
html/body/input [1]
X-path position is nothing but finding out the exact position of the element in the html page.
This is applicable for small web pages which are constant.
<html>
<Body>
<table>
<tbody>
<tr>
<td>
<input>
pg. 20
</td>
</tr>
</tbody>
</table>
</body>
</html>
Html/body/table/tbody/tr/td/input
a) Using Attributes:
Identifying an element using its set of attributes and values is called X-path attributes.
The Syntax is
//html tag[@attribute=’value’]
Example 1:
Example 2:
Identification of:
Link //a
Image img
Table//table
pg. 21
Finding an element by its text using text()
Syntax:
//html tag[text()=’Value’]
//a[text()=’Google’]
//a[text()=’Big brother’]
Note: text() is an exact match function and it will not be able to match an element, if the text of the element
has spaces on either side.
c) Using Contains(text()):
Contains text is the pattern matching function which can be used to match an element with
any text in the pattern.
Syntax:
//html tag[contains(text(),’value’)
Example:
//a[contains(text(),’Google’)]
Note:
d) Using Contains(attribute):
To find a link with its part of attribute value we use contains attribute.
Syntax:
//html tag[contains(@attribute,’value’)]
Example:
//input[contains(@id,’fema’)]
To find the child elements of html tag we can use the syntax
Example:
pg. 22
To find the parent of a child we can use the syntax
Example:
//a[img] output is a
To identify dynamic elements using X-path we can take the help of dependent and
independent concepts.
Independent elements generally will be unique elements based on which all the action are
performed.
Note: Dependent element is the target element and independent is the element on which
your target element is dependent.
Note: Right click on the independent element inspect element and identifying the X-path for
independent element.
Ex: //a[text()=’Bing’]
Note: The concept used here will be moving from child note to parent note.
Syntax: (/..)
Ex: //a[text()=’Bing’]/../..
Note: The concept used here will be moving from parent tag to child tag.
Syntax: (/)
Ex: //a[text()=’Bing’]/../../td[3]/input
//div[text()=’Android Calibrations’]/../../../../../td[1]/div/div
pg. 23
//a[contains(text(),’Dynamo’)]/../../../../div[2]/div/div[2]
X-path:
//a[contains(text(),’Dynamo’)]/../../../..//div[text()=’Remove’]
//div[text=’Android Calibrations’]/../../../..//div[@class=’img’]
//a[text()=’Bing’]/../..//input[@type=’checkbox’]
1. By using Last();
Ex: (//input[@type=’checkbox’])[last()]
2. By using Count();
Ex: (//input[@type=’checkbox’])[count(//input[@type=’checkbox’])]
3. Following – Siblings:
Ex: //a[text()=’Bing’]/../../following-sibling::tr[1]//input
4. Preceding – Sibling:
Checkboxes: //input[@type=’checkbox’]
Textboxes: //input[@type=’text’]
Radio buttons: //input[@type=’radio’]
Links: //a
Images: //Img
Select drop down: //select.
Multi Select drop down: //select[@multiple=’true’]
Checkboxes: input[@type=’checkbox’]
Textboxes: input[@type=’text’]
Radio buttons: input[@type=’radio’]
Images: Img
Select drop down: select.
pg. 24
4. SELENIUM WEB DRIVER - INSTALLATION AND BASICS:
Web driver is an automation tool which can be used to automate web applications.
3.To convert the java project into a web driver project download the selenium standalone
server and configure the selenium standalone server to the java project.
5.Copy the selenium standalone server from the downloads folder and paste it into the
project folder.
6.To configure right click on the java project Build path Configure build path Libraries
tab Add external jars select the selenium standalone server jar Apply and close.
To import:
2.Control + Shift + O
3.While typing program get it from the help menu. Use control + space.
pg. 25
Note: Stop the update of Firefox browser.
In Firefox browser go to tools Options Advanced Update tab Never check for updates
(not recommended: security risk).
The browser opened by the webdriver is a light weighted browser and it does not hold any
history and add-ons.
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
pg. 26
To launch application the code is
package Basics;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
driver.get("http://www.gmail.com");
driver.quit();
To identify the element webdriver provide a method called findelement() which takes an
argument of By class which has eight element locators.
WebElement un=driver.findElement(By.id("username"));
un.sendKeys("admin");
OR
driver.findElement(By.id("username")).sendKeys("admin");
driver.findElement(By.name("pwd")).sendKeys("manager");
driver.findElement(By.id("loginButton")).click();
Thread.sleep(3000);
driver.findElement(By.id("logoutLink")).click();
pg. 27
How to Clear Textbox in Selenium:
driver.findElement(By.id("username")).sendKeys("prathap");
Thread.sleep(3000);
driver.findElement(By.id("username")).clear();
Thread.sleep(3000);
driver.findElement(By.id("username")).sendKeys("admin");
driver.findElement(By.name("pwd")).sendKeys("manager");
driver.findElement(By.id("loginButton")).click();
Every single point under the expected column in manual test case should be present as a
checkpoint in the automation test script. Selenium recommends 4 different checkpoints.
1) Title
2) Text
3) URL
4) Element
1.Title checkpoints:
Comparing the expected title with the actual title from the application. To get the actual
title we can use driver.getTitle().
driver.get("http://demo.actitime.com");
String actualTitle=driver.getTitle();
//System.out.println(expectedTitle);
if (actualTitle.equals(expectedTitle)) {
System.out.println("Pass");
}else{
System.out.println("fail");
Output:
pg. 28
Pass
2) Text checkpoint:
Text checkpoint can be used to compare any text on the application page.
Text will generally be inside an html tag (span, td, div, p, b). To get the text we have to find
the element and use the method getText();
driver.get("http://demo.actitime.com");
driver.findElement(By.id("username")).sendKeys("admin");
driver.findElement(By.name("pwd")).sendKeys("manager");
driver.findElement(By.linkText("Login")).click();
Thread.sleep(10000);
//System.out.println(expectedText);
if (expectedText.equals(actualText)) {
System.out.println("Pass");
}else{
System.out.println("fail");
Output:
Pass
3. URL:
driver.findElement(By.id("username")).sendKeys("admin");
driver.findElement(By.name("pwd")).sendKeys("manager");
driver.findElement(By.id("loginButton")).click();
Thread.sleep(3000);
String expectedURL="https://demo.actitime.com/user/submit_tt.do";
String actualURL=driver.getCurrentUrl();
if (actualURL.equals(expectedURL)) {
System.out.println("Pass");
pg. 29
} else {
System.out.println("Fail");
}
Output:
Pass
We can use the driverfindElement() to find the checkbox and use the method isselected()
which will return a Boolean, if true checkbox is selected and false if checkbox is unselected.
boolean chkboxStatus=driver.findElement(By.id("rem")).isSelected();
System.out.println(chkboxStatus);
driver.findElement(By.id("rem")).click();
boolean chkboxStatus1=driver.findElement(By.id("rem")).isSelected();
System.out.println(chkboxStatus1);
driver.findElement(By.id("rem")).click();
boolean chkboxStatus2=driver.findElement(By.id("rem")).isSelected();
System.out.println(chkboxStatus2);
}
Output:
false
true
false
We can use the driverfind() element to find the radio button and use the method
isselected() which will return a Boolean, if true radio button is selected and false if radio
button is unselected.
boolean radioStatus=driver.findElement(By.id("male")).isSelected();
System.out.println(radioStatus);
driver.findElement(By.id("male")).click();
pg. 30
boolean radioStatus1=driver.findElement(By.id("male")).isSelected();
System.out.println(radioStatus1);
driver.findElement(By.id("male")).click();
boolean radioStatus2=driver.findElement(By.id("male")).isSelected();
System.out.println(radioStatus2);
}
Output:
false
true
true
boolean logoStatus=driver.findElement
(By.xpath("//div[@class='atLogoImg']")).isDisplayed();
System.out.println(logoStatus);
}
Output:
True
If Statement:
if (status) {
System.out.println("Pass");
} else {
System.out.println("Fail");
}
}
}
Output:
Pass
pg. 31
4.2 WORKING WITH DIFFERENT BROWSERS:
Requirements:
Depending on the operating system (32 bit or 64 bit) Download the respective browser
driver i.e., IEDriverServer.exe
IE Settings:
1) Tools Internet options Security Tab make sure all the four zones i.e., internet,
local intranet, trusted sites and restricted sites have enabled protected mode check box.
2) Make sure browser zoom level is set to 100%. Press ctrl+0 to set Zoom level to 100%.
System.setProperty("webdriver.ie.driver", "D:\\Seleniumprogs\\workspace\\Batch10web\\
IEDriverServer.exe");
Requirements:
Go to section – Third party browser driver, click on download page against chrome.
Download chromedriver.exe. In eclipse write the following code.
System.setProperty("webdriver.chrome.driver", "D:\\Seleniumprogs\\workspace\\
Batch10web\\chromedriver.exe");
Synchronization refers to matching the speed of script execution with the speed of
application. In web driver we can use implicitlyWait() to achieve the synchronization
pg. 32
element is found within the duration, it will try to perform the action and if the element is
not found within the duration it will throw an exception NoSuchElementException.
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
In selenium "Waits" play an important role in executing tests. In this tutorial, you will
learn various aspects of both "Implicit" and "Explicit" waits in Selenium.
Most of the web applications are developed using Ajax and Javascript. When a page is
loaded by the browser the elements which we want to interact with may load at different
time intervals.
Not only it makes this difficult to identify the element but also if the element is not located
it will throw an "ElementNotVisibleException" exception. Using Waits, we can resolve this
problem.
Let's consider a scenario where we have to use both implicit and explicit waits in our test.
Assume that implicit wait time is set to 20 seconds and explicit wait time is set to 10
seconds.
Suppose we are trying to find an element which has some "ExpectedConditions "(Explicit
Wait), If the element is not located within the time frame defined by the Explicit wait(10
Seconds), It will use the time frame defined by implicit wait(20 seconds) before throwing an
"ElementNotVisibleException".
1. Implicit Wait
2. Explicit Wait
Implicit Wait:
Selenium Web Driver has borrowed the idea of implicit waits from Watir.
The implicit wait will tell the web driver to wait for certain amount of time before it throws
a "No Such Element Exception". The default setting is 0. Once we set the time, web driver
will wait for that time before throwing an exception.
Explicit Wait:
pg. 33
The explicit wait is used to tell the Web Driver to wait for certain conditions (Expected
Conditions) or the maximum time exceeded before throwing an
"ElementNotVisibleException" exception.
The explicit wait is an intelligent kind of wait, but it can be applied only for specified
elements. Explicit wait gives better options than that of an implicit wait as it will wait for
dynamically loaded Ajax elements.
Once we declare explicit wait we have to use "ExpectedCondtions" or we can configure how
frequently we want to check the condition using Fluent Wait. These days while
implementing we are using Thread.Sleep() generally it is not recommended to use.
Fluent Wait:
The fluent wait is used to tell the web driver to wait for a condition, as well as the frequency
with which we want to check the condition before throwing an
"ElementNotVisibleException" exception.
Frequency: Setting up a repeat cycle with the time frame to verify/check the condition at
the regular interval of time
Let's consider a scenario where an element is loaded at different intervals of time. The
element might load within 10 seconds, 20 seconds or even more then that if we declare an
explicit wait of 20 seconds. It will wait till the specified time before throwing an exception.
In such scenarios, the fluent wait is the ideal wait to use as this will try to find the element
at different frequency until it finds it or the final timer runs out.
pg. 34
WebDriver driver=new FirefoxDriver();
driver.manage().window().maximize();
driver.get("https://demo.actitime.com/login.do");
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
driver.findElement(By.id("username")).sendKeys("admin");
driver.findElement(By.name("pwd")).sendKeys("manager");
driver.findElement(By.id("loginButton")).click();
//Thread.sleep(10000);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("logoutLink")));
driver.findElement(By.id("logoutLink")).click();
driver.findElement(By.id("username")).sendKeys("admin");
driver.findElement(By.name("pwd")).sendKeys("manager");
driver.findElement(By.id("loginButton")).click();
Wait<WebDriver>WaitFluent=new FluentWait<WebDriver>(driver)
.withTimeout(30, TimeUnit.SECONDS)
.pollingEvery(5, TimeUnit.SECONDS)
.ignoring((NoSuchElementException.class));
WaitFluent.until(ExpectedConditions.visibilityOfElementLocated(By.id("logoutLink")
));
driver.findElement(By.id("logoutLink")).click();
pg. 35
4.4 WORKING WITH SELECT DROP DOWNS:
To work with select html tag elements (single select combo box or multi select list box). We
need to use select class.
1. To select an option from single, select combo box or to select multiple options from
list box select class provides 3 different methods.
1. selectByindex()
2. selectByValue()
3. selectByVisibleText()
1) Select by index takes an integer argument which is zero based index of the option to
be selected. By default, each option tag will have an index starting from zero.
2) Select by value takes a string argument which is value of the attributes of the option
tag.
3) Select by visible text takes a string argument which is text of option tag to select.
In multi select list box the same method will be used however, if we write select methods
multiple times in the code, it will select multiple options from the list box.
driver.get("https://krninformatix.com/sample.html");
WebElement singleSelect=driver.findElement(By.id("city"));
//pass the WebElement city as an argument to the constructor of the Select class
dd.selectByIndex(2);
Thread.sleep(5000);
pg. 36
dd.selectByValue("4");
Thread.sleep(5000);
dd.selectByVisibleText("Chennai");
Multi select:
driver.get("https://krninformatix.com/sample.html");
WebElement multiSelect=driver.findElement(By.id("cities"));
dd.selectByIndex(2);
Thread.sleep(5000);
dd.selectByValue("4");
Thread.sleep(5000);
dd.selectByVisibleText("Chennai");
deselectByIndex(),
deselectByValue() or
deselectByVisibleText().
driver.manage().window().maximize();
driver.get("https://krninformatix.com/sample.html");
WebElement multiSelect=driver.findElement(By.id("cities"));
dd.selectByIndex(3);
Thread.sleep(3000);
dd.selectByValue("3");
Thread.sleep(3000);
dd.selectByVisibleText("Chennai");
pg. 37
Thread.sleep(3000);
/*dd.deselectByIndex(3);
Thread.sleep(3000);
dd.deselectByValue("3");
Thread.sleep(3000);
dd.deselectByVisibleText("Chennai");*/
dd.deselectAll();
3. To get all available options select class provides a method getOptions() which returns
a collection of all the options in the select dropdown. This collection is represented as a list
of webElement. Using a for loop we can iterate the list, get each element from the
List<WebElement> print the text of each element (Text of the option tag or visible text).
driver.get("https://krninformatix.com/sample.html");
WebElement singleSelect=driver.findElement(By.id("city"));
//pass the WebElement city as an argument to the constructor of the Select class
dd.selectByIndex(2);
Thread.sleep(5000);
dd.selectByValue("4");
Thread.sleep(5000);
dd.selectByVisibleText("Chennai");
List<WebElement> allOptions=dd.getOptions();
int k=allOptions.size();
System.out.println(k);
WebElement option=allOptions.get(i);
pg. 38
String text=option.getText();
System.out.println(text);
4. To get all the selected options from a multi select list box, we can use the method
getAllSelectedOptions() which returns a list of web element (Collection of all the select
options). We can use a for loop and get each selected option and print the text of each
element.
driver.get("https://krninformatix.com/sample.html");
WebElement multiSelect=driver.findElement(By.id("cities"));
dd.selectByIndex(2);
Thread.sleep(5000);
dd.selectByValue("4");
Thread.sleep(5000);
dd.selectByVisibleText("Chennai");
Thread.sleep(5000);
//dd.deselectAll();
List<WebElement> allOptions=dd.getAllSelectedOptions();
int k=allOptions.size();
System.out.println(k);
WebElement option=allOptions.get(i);
String text=option.getText();
System.out.println(text);
pg. 39
Web driver provides a method findelements() which can be used to find multiple elements
based on the element locater.
driver.get("https://krninformatix.com/");
List<WebElement> allLinks=driver.findElements(By.xpath("//a"));
int si=allLinks.size();
System.out.println(k);
WebElement link=allLinks.get(i);
String text=link.getText();
System.out.println(text);
Find number of check boxes in a page and check all check boxes.
To find number of checkboxes in a page we can use driver.findelements() and the elements
locater either xpath or css selection
driver.get("http://www.gsmarena.com/samsung-phones-9.php");
List<WebElement> allCheck=driver.findElements(By.xpath("//input[@type='Checkbox']"));
int l=allCheck.size();
System.out.println(l);
To check all checkboxes, we can use loop through the list of using for loop. Get each
element from the list using get () which will return a web element and use click() to check
the checkbox.
WebElement check=allCheck.get(i);
check.click();
pg. 40
driver.manage().window().maximize();
//driver.get("https://krninformatix.com/");
// alternate to driver.get()
driver.navigate().to("https://krninformatix.com/");
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
driver.findElement(By.xpath("//a[text()='About us']")).click();
//simulate browser back button action
driver.navigate().back();
Thread.sleep(5000);
//simulate browser forward button action
driver.navigate().forward();
Thread.sleep(5000);
//simulate browser refresh button action
driver.navigate().refresh();
driver.close();
We can use driver.findElement() to find element and use the method getAttribute() and
pass the attribute name as an argument which will return the value of the attribute.
String allValue=driver.findElement
(By.xpath("//a[text()='Google']")).getAttribute("href");
System.out.println(allValue);
Output:
https://www.google.com/
4.8 POP-UPS:
5. File upload
pg. 41
6. File download.
If the tool tips coming from the title attribute, we can find the element and use
getAttribute() to get tool tip text.
If the tool tips coming from div pop up we can find div using driver.findElement() and use
getText() to get text from the division
String toolTip=driver.findElement
(By.xpath("//img[contains(@src,'a32')]")).getAttribute("title");
System.out.println(toolTip);
Output:
Samsung Galaxy A32 Android smartphone. Announced Feb 2021. Features 6.4? display,
Helio G80 chipset, 5000 mAh battery, 128 GB storage, 8 GB RAM, Corning Gorilla
Glass 5.
//Thread.sleep(20000);
JavascriptExecutor jse=(JavascriptExecutor)driver;
jse.executeScript("window.scrollBy(0,250)", "");
pg. 42
driver.findElement(By.xpath("(//span[@class='question'])[1]")).click();
String text=driver.findElement
(By.xpath("//div[@class='_2JH8X1']")).getText();
System.out.println(text);
Output:
Shipping charges are calculated based on the number of units, distance and delivery date.
For Plus as well as Non-Plus customers, Seller will decide shipping charges for all non-FAssured items.
Shipping charges are calculated based on the number of units, distance and delivery date.
For non-Plus customers, if the total value of FAssured items is more than Rs.500, shipping charges are free. If
the total value of FAssured items is less than Rs.500, shipping charges = Rs.40 per unit
2. CALENDAR POP-UPS:
b. Which allows you to select the date from the calendar pop up.
If the calendar allows to type the date use driver.findElement() and sendKeys().
If it is a pop up then click on the calendar icon to make the calendar icon visible. Use an
Xpath to find the date and click on it.
Note: Calendar pop up will generally be in a table structure. Web driver cannot identify the
hidden elements.
driver.findElement(By.xpath("//span[contains(@class,'fl icon-
calendar')]")).click();
Thread.sleep(3000);
driver.findElement(By.xpath("//td[text()='20']")).click();
pg. 43
Alert – has only one button i.e., ok
Confirmation pop-up is generated from confirm () method of javascript and has two buttons,
ok and cancel and based on the input’s execution happens.
To handle javascript alert or confirmation pop-up, we need to first switch to the pop-up
using driver.switchTo().alert() which will return on object of alert. Using this object, we can
driver.findElement(By.xpath("(//button[text()='Click me!'])
[1]")).click();
Thread.sleep(2000);
driver.switchTo().alert().accept();
Thread.sleep(2000);
driver.findElement(By.xpath("(//button[text()='Click me!'])
[1]")).click();
Thread.sleep(2000);
String altText=driver.switchTo().alert().getText();
System.out.println(altText);
driver.switchTo().alert().accept();
Output:
pg. 44
I am an alert box!
driver.findElement(By.xpath("(//button[text()='Click me!'])
[2]")).click();
Thread.sleep(2000);
Alert alt=driver.switchTo().alert();
alt.dismiss();
Thread.sleep(2000);
driver.findElement(By.xpath("(//button[text()='Click me!'])
[2]")).click();
Thread.sleep(2000);
String confirmText=alt.getText();
System.out.println(confirmText);
Thread.sleep(2000);
alt.accept();
Output:
Press a button!
By default, selenium cannot handle page on load authentication pop-up. To overcome the
problem, we can pass the username and password in the URL with the following syntax.
http://username:password@ipaddress/domainname
pg. 45
WebDriver driver=new FirefoxDriver();
driver.manage().window().maximize();
driver.get("https://admin:[email protected]");
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
We can use driver.findElement() to find the element and use sendKeys() and pass the full
path of the file as an argument to the sendkeys.
driver.findElement(By.id("brow")).sendKeys("C:\\Users\\Desktop\\
Automation\\home.jpg");
To save a file to disk automatically without the pop-up, we can take help of Firefox
preferences by using Firefox profile.
Case 1:
To save the file to the downloads folder, we can use the preference
browser.helperApps.neverAsk.saveToDisk and provide the file MIME type as a value for the
preference i.e., application/zip. If there are multiple files types to be download, we can
provide (,) separated list of MIME types of all the files.
prof.setPreference("browser.helperApps.neverAsk.saveToDisk", "application/zip");
Case 2:
prof.setPreference("browser.helperApps.neverAsk.saveToDisk", "application/zip");
prof.setPreference("browser.download.folderList", 0);
pg. 46
Case 3:
prof.setPreference("browser.helperApps.neverAsk.saveToDisk", "application/zip");
prof.setPreference("browser.download.folderList", 2);
prof.setPreference("browser.download.dir","D:\\Docs");
Note: Don’t forget to set the preference in Firefox class which is done in common for each
case.
driver.findElement(By.xpath("(//a[text()='Download'])[2]")).click();
Problem:
By default, webdriver does not understand the elements in the browser pop ups. The
control of the webdriver will be in the parent window and when we say
driver.findElement(), it tries to find the element in the parent window(). Webdriver does not
transfer the control to the new browser automatically.
Solution:
pg. 47
We have to transfer the control to the browser pop up using driver.switchTo().window().
Window () accepts a string argument which is the window handle of the browser to switch
to. We can get the window handles of all the browsers that was opened during that
execution by using the method driver.getWindowHandles(). getWindowHandles() returns a
Set<String> which contains all the window handles. We can use an iterator and get each
window handle by using the next ().
The first time next () is used it gets first element in the set, the second time the next method
is used it gets second element in the set and so on. We can store this window handle in the
String reference and pass it as an argument to driver.switchTo().window().
After performing action on the browser pop up, if we want to close the popup, we can use
driver.close(). This method will close the current browser where control is present. If the
browser is closed control does not transfer to the parent browser automatically. We have to
use driver.switchTo().window() to transfer the control.
When we click on the link which opens in a new tab, webdriver will open it in a new
window.
driver.findElement(By.xpath("//a[text()='Tour Packages']")).click();
Set<String> allWindows=driver.getWindowHandles();
Iterator<String> it=allWindows.iterator();
String irctc=it.next();
String tourPackages=it.next();
//System.out.println(irctc);
//System.out.println(tourPackages);
driver.switchTo().window(tourPackages);
driver.findElement(By.xpath("//a[text()='Login']")).click();
driver.close();
driver.switchTo().window(irctc);
driver.findElement(By.id("stationFrom")).sendKeys("Bengaluru");
4.9 ACTIONS CLASS (OR) WORKING WITH MENU DROPDOWNS (OR) MOUSE AND KEYBOARD
ACTIONS:
If we want to click on a sub-menu item which will be visible when we move the mouse on to
parent menu, we can use Actions class. Actions class provides methods to perform mouse
and keyboard related actions.
Sub-menu items or link will not be visible until we move the mouse on parent menu item or
link. If the element is not visible, web driver cannot perform the action. Hence, we need to
pg. 48
stimulate moving to parent menu item so that drop down with sub-menu links is visible and
web driver can find the sub menu items.
We can use moveToElement() and pass parent menu as an argument which will stimulate
the drop down menu.
The right click menu is called context menu. We can use the Actions class ContextClick() to
perform right click.
We can use sendKeys() of Actions class to send any key. We can also use sendkeys() for Web
Element to send any key. Keys enumerator provides all the keys of the key board and can be
used to sendKeys() like tab, control, alt, shift, etc...
WebElement coursesOffered=driver.findElement
(By.xpath("//span[text()='Courses Offered']"));
//act.sendKeys("T").perform();
//Combinations of keys/morethan one keys
//act.sendKeys(Keys.ALT).build();
//act.sendKeys(Keys.CONTROL).build();
//act.sendKeys(Keys.DELETE).perform();
We can use the dragAndDrop() of Action class which takes two arguments source and
target.
Identifying Source:
pg. 49
When we move the mouse type to the element if the curser type changes to move that part
can be used to drag. The part which can be dragged will generally have a class property with
the value drag or class name will have the drag.
WebDriver driver=new FirefoxDriver();
driver.manage().window().maximize();
driver.get("http://www.dhtmlgoodies.com/submitted-scripts/i-google-like-
drag-drop/index.html");
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
WebElement source=driver.findElement(By.xpath("//div[@id='block-1']/h1"));
WebElement target=driver.findElement(By.xpath("//div[@id='block-3']"));
We can use java script to scroll down the page in selenium. The java script to scroll down
the page in selenium is window.scrollby(0,250). To execute the java script inside the java
program we can take help of executeScript() which is available in JavaScriptExecutor
interface.
JavascriptExecutor jse=(JavascriptExecutor)driver;
jse.executeScript("window.scrollBy(0,800)", "");
//Reverse Order
Thread.sleep(5000);
jse.executeScript("window.scrollBy(0,-250)", "");
File src=
((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(src, new File("C:\\Users\\Desktop\\Automation\\
Error.png"));
Problem:
Web driver cannot understand the element present inside an iframe by default. It
cannot search for any element which is present in the iframe DOM.
pg. 50
Solution:
Transfer the control of web driver to the DOM of the iframe using
driver.switchTo.frame(). Frame() is an overloaded method with
frame(int arg)
frame(String arg)
frame(WebElement arg)
If the page has one or two iframes we can use this method by-passing zero-based index of
the frame.
Eg.
driver.switchTo().frame(0);
driver.switchTo().frame(1);
If an iframe has id or name property we can use the value of the id or the name property to
find the iframe.
Eg.
driver.switchTo().frame(“secondframe”);
If we have multiple iframes on the page the frames do not have ID or name property, we
can use the Web Element arg and find the iframe.
Eg.
WebElement frm=driver.findElement(By.xpath(“//frame[@src=’third.html’]”));
driver.switchTo().frame(frm);
After performing the action on an element inside iframe. If we want to come out of
the iframe, we can use
driver.switchTo().defaultContent();
Driver.switchTo().parentFrame();
pg. 51
How to identify the element inside a frame?
Right click on the element in Firefox in the context menu, if it shows This
frame which means the element is inside the frame.
driver.switchTo().frame(1);
driver.findElement(By.name("name1")).sendKeys("Lakshmi");
//driver.switchTo().frame("secondframe");
//driver.findElement(By.name("rep")).click();
//driver.switchTo().defaultContent();
driver.switchTo().parentFrame();
WebElement
frm=driver.findElement(By.xpath("//frame[@src='third.html']"));
driver.switchTo().frame(frm);
driver.findElement(By.name("check")).click();
Excel Library:
Requirements:
Apache poi
Go to the binary distribution section click on the link poi-bin-3.9.20122013.zip which will
navigate to a page with the links called download. Click on the first link to download apache
poi.
2. Convert the excel file to a workbook (Get the workbook object or create the
workbook object) from the Excel file.
3. Go to a particular sheet of the Excel (Get the sheet object from the workbook).
4. Go to a particular row in the sheet (Get the row object from the sheet).
5. Go to a particular cell in the row (Get the cell object from the row).
6. Get the data from the cell depending on the type of data.
pg. 52
The jar files required to work with Excel is
poi-ooxml-3.9-20121203.jar
poi-ooxml-schemas-3.9-20121203.jar
dom4j-1.6.1.jar
xmlbeans-2.3.0.jar
Program-1:
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import org.apache.poi.EncryptedDocumentException;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (EncryptedDocumentException e) {
pg. 53
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return retVal ;
}
public int getLastRowNumber(String sheetname) {
int retVal=0;
try {
FileInputStream fis=new FileInputStream("C:\\Users\\gaden\\
Desktop\\Automation\\Data.xlsx");
Workbook wb=WorkbookFactory.create(fis);
Sheet s=wb.getSheet(sheetname);
retVal=s.getLastRowNum();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (EncryptedDocumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return retVal ;
}
}
Program-2:
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
int lastRow=xlib.getLastRowNumber("Sheet1");
pg. 54
Thread.sleep(10000);
driver.findElement(By.id("logoutLink")).click();
Thread.sleep(10000);
}
4.15 TESTNG(TESTNEXTGENERATION:
TestNG (test next generation) is created by Cedric Beust and is a testing framework which
can be used for white box testing and black box testing. TestNG provides features like
multiple test execution, assertions, results and execution control. These features are
essential part of automation and we can use testNG with selenium to achieve robust
automation.
Installation of TestNG:
Open Eclipse Goto Help Eclipse Market Place Search for testNG. click on Install, Next,
Next and install now. Half through the installation you will get a pop up which says content
is unsigned do you wish to continue. Click on OK and restart eclipse.
Every testNG class should have @test annotation which will ensure the class can be
executed. There can be multiple methods in a testNG class, but each test method should
have @test annotation. By default, all the test methods of testNG class will get executed in
alphabetical order.
Output:
Create Customer
Delete Customer
Edit Customer
If there are either pre-condition or post condition for the test, we can code them in different
methods with @BeforeMethod and @AfterMethod annotation. If there are multiple test
methods @BeforeMethod and @AfterMethod will get execute for each test in that class.
pg. 55
If there are pre and post condition for entire class, we can put them under two different
methods with @BeforeClass and @AfterClass class annotation.
import org.testng.annotations.AfterClass;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
Output:
Open Browser
Login
Create Customer
Logout
Login
Delete Customer
Logout
Login
Edit Customer
Logout
Close Browser
pg. 56
1) Using Priority:
@Test annotation can be given priority and whichever the annotation has the least priority
will get executed first. Execution will follow ascending order of priority.
Output:
Create Customer
Edit Customer
Modify Customer
Delete Customer
@Test(enabled=false)
public void testEditCustomer() {
System.out.println("Executing Edit customer");
}
public class Customerfalse {
@Test(priority=0)
public void createCustomer() {
System.out.println("Create Customer");
}
@Test(priority=1)
public void editCustomer() {
System.out.println("Edit Customer");
}
@Test(enabled=false)
public void modifyCustomer() {
System.out.println("Modify Customer");
}
@Test(priority=9)
public void deleteCustomer() {
System.out.println("Delete Customer");
pg. 57
}
}
Output:
Create Customer
Edit Customer
Delete Customer
}
Output:
Create User
Edit User
Modify User
Delete User
4) Assertions:
We can use Assert class of TestNG which has list of static assertEquals()(overloaded static
methods) for comparing the actual and expected (Checkpoints). If the assertion passes the
test will be marked as pass and if assertion fails, the test will be marked as FAIL. If there is
any statement after the assert, it will not get executed if assertion fails.
If we set a test method to depend on another test method and if the assertion fails, the
dependant test method will be skipped.
@Test
pg. 58
public class UsersA {
public void createUser() {
System.out.println("Create User");
}
@Test
public void editUser() {
String actual="ABC";
String expected="ABC123";
Assert.assertEquals(actual, expected);
System.out.println("Edit User");
}
@Test(dependsOnMethods= {"editUser"})
public void deleteUser() {
System.out.println("Delete User");
}
}
Output:
Create User
PASSED: createUser
FAILED: editUser
PROJECT: FRAMEWORK
Create a folder called framework. Create a folder called jars inside the framework folder.
pg. 59
Copy selenium standalone server, apache server and poi jars into the Jars folder.
Launch eclipse and set the framework folder as workspace.’
Create a Java project and in the java settings. Go to libraries tab Click on Add External Jars
and select all the jar file folder. Click on Add Library and select TestNG library and click on
finish.
Each Module in the package is created as package in the project and the scenario related to
that module will be created as TestNG classes under the respective classes.
Each scenario will be one TestNG class and one test method to test the functionality. Each
module will have separate xml which can be used to execute scenarios of that module.
The common functionalities which is Pre and Post condition like launching browser, opening
URL, Login, Logout and quitting the browser will be created before and after method and
before and after class in a separate TestNG class called base class. Each automation scenario
will extend this base class which will ensure pre and post conditions are executed.
Base Class.java
package com.mindq.actitime.testbase;
import org.testng.annotations.AfterClass;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.BeforeMethod;
CreateCustomers.java
package com.mindq.actitime.tasks;
import org.testng.annotations.Test;
DeleteCustomers.java
package com.mindq.actitime.tasks;
pg. 60
import org.testng.annotations.Test;
CreateReport.Java
package com.mindq.actitime.reports;
import org.testng.annotations.Test;
DeleteReport.java
package com.mindq.actitime.reports;
import org.testng.annotations.Test;
5.SOFTWARE TESTING:
pg. 61
For every release you must rerun the same set of tests which can be time
consuming.
Requires heavy investment.
Requires a greater number of human resources.
5.3 AUTOMATION:
Automation Testing: Testing which is done by any other third-party tool.
Test automation is the use of software to control the execution of tests, the comparison of
actual outcomes to predicted outcomes, the setting up of test preconditions, and other test
control and test reporting functions. Commonly, test automation involves automating a
manual process already in place that uses a formalized testing process.
5.4 ADVANTAGES:
Reliable: Tests perform precisely the same operations each time they are run,
thereby eliminating human error
Repeatable: You can test how the software reacts under repeated execution of the
same operations. Programmable: You can program sophisticated tests that bring
out hidden information from the application.
Comprehensive: You can build a suite of tests that covers every feature in your
application.
Reusable: You can reuse tests on different versions of an application, even if the
user interfaces changes.
Better Quality Software: Because you can run more tests in less time with fewer
resources.
Fast: Automated Tools run tests significantly faster than human users.
Cost Reduction: As the number of resources for regression test are reduced.
Reporting: Customized reporting of application defects.
5.5 DISADVANTAGES OF AUTOMATION TESTING:
Proficiency is required to write the automation test scripts.
Debugging the test script is major issue. If any error is present in the test script,
sometimes it may lead to deadly consequences.
Test maintenance is costly in case of playback methods. Even though a minor
change occurs in the GUI, the test script must be rerecorded or replaced by a new
test script.
Maintenance of test data files is difficult if the test script tests more screens.
5.6 FUNCTIONAL TESTING TOOLS:
pg. 62
Functional Testing Tools
Open Source Commercial
Selenium-1.0 QTP
Web driver 2.0 Test Partner
Sahi Test complete
Bad Boy RFT
Ruby Silk
Watir
Selenium QTP
Open source Paid tool
Works on all OS (Windows, OS X, Linux, Works on Windows
Solaris)
Tests only Web applications Tests web and desktop applications
Works on almost all browsers (IE, Firefox, Works on Firefox 3.5.x and IE
Safari, Opera)
Code can be made in any one of languages VB Script
such as Java, C#, Ruby, Python, pearl, php
etc
Html ID, Xpath, CSS, DOM, Link text Object properties, Repository objects
There is no option, can record script in GUI Spy
Selenium IDE, can spy objects using IE
developer tool bar, Firebug and also using
http://saucelabs.com/builder
IDE sometimes does not record some Recording is a little reliable
events
Set of Libraries, around 20MB (Need to Around 1.5GB
include other supporting software)
Saucelabs.com, Element34 , Commercial From HP
Support
pg. 63
pg. 64