0% found this document useful (0 votes)
59 views

PDF Selenium Notes Compress

This document provides an overview of Selenium, including: 1. The history of Selenium and how to download the Selenium standalone server file and driver executable files. 2. The different flavors of Selenium including Selenium Core, IDE, RC, and WebDriver. 3. How to configure the downloaded Selenium files in Eclipse. 4. The architecture of Selenium including how the client bindings communicate with the Selenium server and drivers to perform actions in browsers.

Uploaded by

Crazy Hacker
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
59 views

PDF Selenium Notes Compress

This document provides an overview of Selenium, including: 1. The history of Selenium and how to download the Selenium standalone server file and driver executable files. 2. The different flavors of Selenium including Selenium Core, IDE, RC, and WebDriver. 3. How to configure the downloaded Selenium files in Eclipse. 4. The architecture of Selenium including how the client bindings communicate with the Selenium server and drivers to perform actions in browsers.

Uploaded by

Crazy Hacker
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 88

 

SELENIUM

History

Locators

Web elements

Handling dropdown

Handling popup
Synchronization

Java Script Executor

Take screenshot

Data Driven Testing

Test NG

POM

Framework

Github

Maven

Selenium Grids

Jenkins
 

 
  History of Selenium
Selenium was invented by Jason in the year 2004. It is a free and open source web
based automation tool.

Selenium can be downloaded from the following website


o  URL
URL – –  www.seleniumhq.org/download/
www.seleniumhq.org/download/  
o  File
File –
 – Selenium
 Selenium stand alone server (click on download link inline with

section 
‘Java’ under ‘Selenium client and WebDriver language bindings’ section 

  Flavors of Selenium

1.  Selenium Core

2.  Selenium IDE

3.  Selenium RC (Remote control)

-  Supports non-secured websites (http://)


(http://)  

4.  Selenium WebDriver

-  Supports both secured and non-secured websites (http and https) 


https) 

For mobile based application

1.  Selandroid
Selandroid –
 – For
 For android applications

2.  Appium
Appium –
 – For
 For IOS, Windows and android applications

  Advantages

  Free and open source 


source 

languages 
  Supports 13 languages 
  Supports for multiple browsers

  Disadvantages

  Supports only for web based application 


application 

  Does not support for client server and stand alone applications 
applications 

By: Harish Korgal  Page | 2


 

 
  Difference between Selenium and QTP

Selenium QTP

1.  Free version 1.  Paid version

2.  Supports 13 languages 2.  Supports only 1 language i.e. VB

3.  Open source tool scripting

4.  Supports multiple browsers 3.  Not an open source tool


4.  Supports limited browsers

  Required Software’s
 Software’s  

  JDK 1.8 
1.8 
  Eclipse (Any versions Oxygen) 
versions : Neon, Mars or Oxygen) 
  Driver executable files 
files 
  Selenium stand alone source file 
file 

Downloads:
   Selenium stand alone source file
1.  https://www.seleniumhq.org/download/
https://www.seleniumhq.org/download/  

2.  Click on download


download link
 link inline with ‘Java’ under ‘Selenium client and WebDriver

language bindings’ section 


section 

Note:  jar
Note:  jar file will
file will be downloaded

 –
 –   It is a compiled and compressed file consist of set of methods to perform action

on the browsers

   Driver Executable files


1.  https://www.seleniumhq.org/download/
https://www.seleniumhq.org/download/  
2.  Navigate to ‘Third Party Drivers, Binding and Plugins’ section 
section 
3.  Click on version no (0.20.0) 
(0.20.0) inline with “Mozilla Gecko Driver”
Driver”  
4.  Select which file to be download (win32 or win64) 
win64) 

Note: zip file will
Note:  file will be downloaded
1.  Zip file consist of .exe file for Mozilla Firefox Browser 
Browser 
2.  To download for Chrome Browser click on the version number inline with “Google
Driver” 
Chrome Driver” 

By: Harish Korgal  Page | 3


 

 
  Steps to configure the downloaded files to Eclipse

1.  Open Eclipse


2.  Click on FileNewOther (OR crtl + N)

3.  Select Java Project and click on ‘Next’ button 


button 

By: Harish Korgal  Page | 4


 

 
4.  Enter the Project name 
name click on ‘Finish’ button 
button 
5.  Right click on the newly created project folder  New  Folder (To create one folder in
the newly created project folder)

6.  Enter the folder name as Software and click on ‘Finish’ button 
button 

By: Harish Korgal  Page | 5


 

 
7.  Copy paste the downloaded files i.e. Driver executable file (.exe file) and stand alone
server file (jar file) 
file)  

8.  Right click on ‘Selenium-server-standalone’ jar file  Build Path  click on ‘Add to Build
‘Selenium-server-standalone’
path’  
path’

By: Harish Korgal  Page | 6


 

 
9.  ‘Referenced Libraries’ 
Libraries’  will be created as below which consist of set of methods to
perform action on browsers

10. Right click on src folder  New  click on package


package  

By: Harish Korgal  Page | 7


 

 
11. Enter a package name (in lower case) and click on ‘Finish’ button 
button  

12. Right click on the newly created package  click on ‘Class


‘Class’’ 

By: Harish Korgal  Page | 8


 

 
13. Enter class name (First letter capital) and click on ‘Finish’ button 
button 

14. Successfully created a java project. You can write the script in the class body

By: Harish Korgal  Page | 9


 

 
  Selenium Architecture 

Client/lang Bindings Server Drivers Browsers


Java
Selenium Gecko driver Firefox
C#
Web Chrome driver Chrome
Ruby  
Ruby
Driver  
Driver driver 
IE driver  explore 
IE explore 

1.  Selenium supports for multiple languages i.e. Java, C#, Ruby etc… these languages are

called as Client/language bindings

2.  These client bindings will communicate to server and it will perform action on browsers

with the help of Drivers i.e. Gecko driver, chrome drive


driverr etc… 
etc… 

3.  Drivers acts as a translator between Server and the Browser

4.  While communicating between server and browser uses protocol called as

JSON (Java Script Object Notation) wire


Notation) wire protocol

5.  To specify the path of driver we use System.setProperty();


System.setProperty();  
Where, System  Concrete class and setProperty  Static method

  WAP to launch empty Firefox Browser


class Lauch

public static void main(String[] args)

key="webdriver.gecko.driver";
String key="webdriver.gecko .driver";
value="./software/
String value=". geckodriver.exe";
/software/geckodriver .exe";

System.setProperty (key,value);
(key,value);

FirefoxDriver driver = new FirefoxDriver();

By: Harish Korgal  Page | 10


 

 
  WAP to launch empty Google Chrome Browser

class Lauch

public static void main(String[] args)

key="webdriver.chrome.driver";
String key="webdriver.chrome .driver";

value="./software/
String value=". chromedriver.exe";
/software/chromedriver .exe";

System.setProperty (key,value);
(key,value);

ChromeDriver driver = new ChromeDriver();

Note:

1.  To specify path we use System.setProperty()

2.  System
System is
 is a concrete class

3.  setProperty()
setProperty() is
 is static method of System class

4.  setProperty() takes 2 arguments

a.  key  specific type of browser (whether Firefox or chrome browsers)

b.  value  path of driver executable file (path .exe


.exe file
 file the browsers)

5.  Dot (.) 


(.)  represents current java project

6.  / from parent to child folder


traverse from 

7.  If key or value are


value are invalid  throws  IllegalStateExeception (java run time exception)

  WAP to launch empty Firefox Browser and close the


 th e browser

class Lauch
{
public static void main(String[] args)
{
key="webdriver.gecko.driver";
String key="webdriver.gecko .driver";

value="./software/
String value=". geckodriver.exe";
/software/geckodriver.exe";

System.setProperty (key,value);
(key,value);

By: Harish Korgal  Page | 11


 

 
FirefoxDriver driver = new FirefoxDriver(); //To launch the browser
browser  

driver.close(); //To close specific tab

driver.quit(); //To close browser


browser  

 Selenium Java Architecture 


Has 2 abstract method I  SearchContext

Has 11+2=13 abstract methods   I WebDriver

Has 13 concrete classes ©  RemoteWebDriver

© Firefox © Google Chrome © Inter explorer

1.  Search context is the super most interface which has 2 abstract methods

2.  WebDriver is an interface


interface which
 which consist of 13 abstract methods (11 of webdriver and 2

of search context)

3.  Remote web driver is an implantation class which consist of 13 concrete methods

4.  As per industry standards, we always up-cast


up- cast browser to WebDriver interface

5.  All the browsers will extends from RemoteWebDriver class

By: Harish Korgal  Page | 12


 

 
Example for Run time polymorphism:
WebDriver driver = new FirefoxDriver();

Where,

WebDriver   Is an interface

driver   It is a reference variable



=   Assignment operator
new   Keyword & operator which creates random memory space in heap

memory block

FirefoxDriver   It is a constructor used to launch empty firefox driver and initialize all

the non static members

  WAP to launch empty Firefox Browser and enter the URL


class Lauch

public static void main(String[] args)


{

key="webdriver.gecko.driver";
String key="webdriver.gecko.driver";

value="./software/
String value=". geckodriver.exe";
/software/geckodriver.exe";

System.setProperty (key,value);
(key,value);

WebDriver driver = new FirefoxDriver(); //To launch the browser


browser  

driver.get(“https://www.google.com”);
driver.get (“https://www.google.com”); //To enter the URL

Advantage of get() method

   It is used to enter URL


   It waits until the page loads completely
   In get() method, protocol (https://) is compulsory

By: Harish Korgal  Page | 13


 

 
  WAP to print title of the application

class Lauch
{
public static void main(String[] args)
{
key="webdriver.gecko.driver";
String key="webdriver.gecko .driver";
value="./software/
String value=". geckodriver.exe";
/software/geckodriver .exe";
System.setProperty (key,value);
(key,value);

WebDriver driver = new FirefoxDriver(); //To launch the browser


browser  
driver.get(“https://www.google.com”);
driver.get (“https://www.google.com”); //To enter the URL
driver.getTitle();
String title = driver.getTitle(); // this method used to get the title of the tab
System.out.println(title);
}

  Methods of ‘Search Context’ interface


In this interface we have 2 abstract methods

1.  findElement(By.args())

Return type of findElement is  WebElement


WebElement   – WebDriver
– WebDriver

2.  findElements(By.args())

Return type of findElements is  List<WebElement>


List<WebElement>   – WebDriver
– WebDriver

  Methods of ‘WebDriver’ interface


In this interface we have 13 abstract methods

1.  close()

2.  findElement(By.args())

3.  findElements(By.args())

4.  get(String args())

5.  getCurrentUrl()

6.  getPageSource ()

7.  getTitle()

8.  getWindowHandle()

9.  getWindowHandles()

By: Harish Korgal  Page | 14


 

 
10. manage()

11. navigate()

12. quit()

13. swtichTo()

LOCATORS


  In selenium before performing any action first we need to inspect the element.
  To inspect elements we use Locators.

   Locators are static method of ‘By’


‘By’ class. ‘By’ class is a abstract class
class  

Locators are classified into 8 types

1.  tagName()

2.  id()

3.  name()

4.  className()

5.  linkText()
6.  partialLinkText()

7.  cssSelector()

8.  xpath()

Ex: Refer the below source code to develop hyperlink


Type the below code in notepad and save the page with filename.html extension
<html>

<body>

<a id
id== “a1” name
name  = “n1” class
class=
= “c1” href= https://www.google.com>Google</a>
https://www.google.com>Google</a>

</body>

</html>

  Write a script to click on link by using tagName() locator


class Sample
{
public static void main(String[] args)
{
key="webdriver.gecko.driver";
String key="webdriver.gecko .driver";
value="./software/
String value=". geckodriver.exe";
/software/geckodriver .exe";

By: Harish Korgal  Page | 15


 

 
System.setProperty (key,value);
(key,value);

Firef oxDriver(); //To launch the browser


WebDriver driver = new FirefoxDriver(); browser  

driver.get(“https://www.google.com”);
driver.get (“https://www.google.com”); //To enter the URL

WebElement ele = driver.findElement(By.tagName("a"));


driver.findElement(By.tagName("a")); //find element by tagname
tagname  

element/link  
ele.click(); //To click the element/link
}

Note:

1.  Return type of findElement


findElement is
 is WebElement
WebElement  

2.  WebElement is a interface


interface  

3.  findElement will point to the first matching, in case of multiple webelements

4.  if the specified locator is not matching with any elements,


e lements, then it will throw

‘NoSuchElementException’ (selenium run time exception)


5.  How to explain the below statement?

driver.findElement(By.tagName("a")).
driver.findElement(By.tagName click();
("a")).click ();

In the browser find the element with tagName as ‘a’ and perform click action 
action  

  Write a script to click on link by using id() locator


class Sample
{
public static void main(String[] args)
{
System.setProperty ("webdriver.gecko.driver"
"webdriver.gecko.driver",,"./software/geckodriver.exe"
/software/geckodriver );
.exe");

WebDriver driver = new FirefoxDriver();


Firef oxDriver();

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

driver.findElement(By.id("a1")).click();
driver.findElement(By.id("a1")).click();
//find element by id and perform click action
//find
}

By: Harish Korgal  Page | 16


 

 
  Write a script to click on link by using name() locator

class Sample
{
public static void main(String[] args)
{
System.setProperty ("webdriver. gecko.driver"
"webdriver.gecko .driver",,"./software/geckodriver.exe"
/software/geckodriver );
.exe");

WebDriver driver = new FirefoxDriver();


Firef oxDriver();

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

driver.findElement(By.name("n1")).click();
driver.findElement(By.name ("n1")).click();
//find element by name and perform click action
//find
}

  Write a script to click on link by using className() locator


class Sample
{
public static void main(String[] args)
{
System.setProperty ("webdriver. gecko.driver"
"webdriver.gecko .driver",,"./software/geckodriver.exe"
/software/geckodriver );
.exe");
WebDriver driver = new FirefoxDriver();
Firef oxDriver();
driver.get(“https://www.google.com”);

driver.findElement(By.className("c1")).click();
driver.findElement(By.className ("c1")).click();
//find element by className and perform click action
//find
}

  Write a script to click on link by using linkText() locator


class Sample
{
public static void main(String[] args)
{
System.setProperty ("webdriver. gecko.driver"
"webdriver.gecko .driver",,"./software/geckodriver.exe"
/software/geckodriver );
.exe");
WebDriver driver = new FirefoxDriver();
Firef oxDriver();
driver.get(“https://www.google.com”);

driver.findElement(By.linkText("Google")).click();
driver.findElement(By.linkText ("Google")).click();
//find element by linkText and perform click action
//find
}

By: Harish Korgal  Page | 17


 

 
  Write a script to click on link by using partialLinkText() locator

class Sample
{
public static void main(String[] args)
{
System.setProperty ("webdriver. gecko.driver"
"webdriver.gecko .driver",,"./software/geckodriver.exe"
/software/geckodriver );
.exe");
WebDriver driver = new FirefoxDriver();
Firef oxDriver();

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

driver.findElement(By.partialLinkText("Goo")).click();
driver.findElement(By.partialLinkText ("Goo")).click();
//find element by partialLinkText and perform click action
//find
}

Note:

  linkText and partialLinkText are case sensitive


  These 2 locators are used only in case of hyperlinks

  CSS Selector

It is a locator
l ocator and it is an expression

Syntax:
tag[Attribute_Name= ‘Attribute_Value
Attribute_Value’’]
Example:
a[id=‘a1’]  
a[id=‘a1’]

where,
a  tag name

id  attribute name
a1  attribute value

  To verify css expression in Firefox browser we use Firepath


Firepath  
  To verify css expression in Chrome browser we use Developer tool bar 
bar 

Steps to download Firebug and Firepath


1.  Open Firefox browser

2.  Click Tools  click ‘Add-


‘Add-ons’
ons’  

3.  In the ‘Search all add-


add -ons’ text box enter Firebug
Firebug  

4.  Install the Firebug

By: Harish Korgal  Page | 18


 

 
5.  In the ‘Search all add-
add -ons’ text box enter Firepath
Firepath  

6.  Install the Firepath

Steps to verify css expressions in Fire fox


1.  Open page in fire fox browser

2.  Click on Firebug OR click F12

3.  Click on ‘Firepath’  select ‘css’ in dropdown 


dropdown 
4.  Type css expression (a[id=’a1’]) and click enter 
enter 

5.  Notice that it will display source code and matching element will be highlighted

Steps to verify css expressions in chrome browser

1.  Open page in chrome browser

2.  Click on F12

3.  Press Ctrl+F and type css expression (a[id=’a1’]) and click enter 
enter  

4.  Notice that it will display source code only


5.  Mouseover the source code it will highlight the element

Note:

In css expression # represents id and Dot ( . ) represents class

Example: a#a1, a.c1

  Write a script to click on link by using css selector() locator


class Sample
{
public static void main(String[] args)
{
System.setProperty ("webdriver. gecko.driver"
"webdriver.gecko .driver",,"./software/geckodriver.exe"
/software/geckodriver );
.exe");

WebDriver driver = new FirefoxDriver();


Firef oxDriver();

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

driver.findElement(By.cssSelector("a[id=’a1’]")).click();
driver.findElement(By.cssSelector("a[id=’a1’]")).click();

// find element by css selector and perform


//find p erform click action

By: Harish Korgal  Page | 19


 

 
}
}

X-path
X-path is a path of the element in HTML tree structure. In x-path we have 2 types,

1.  Absolute x-path / x-path by position

2.  Relative x-path / x-path by attributes

  Absolute x-path 
 x-path 

In this we use single slash ‘/’


‘/’ to
 to traverse from parent to immediate
i mmediate child element

Example: consider the below source code

<html>
<body>
<div>
<input type= “text” value= “A”> 
“A”>  
<input type= “text” value= “B”> 
“B”> 
</div>
<div>
<input type= “text” value= “C”> 
“C”>  
<input type= “text” 
“text” value= “D”> 
“D”> 
</div>
</body>

</html>

In x-path index starts from 1 

1 html

1 body

1 div

1 input A

2 input B

2 div

By: Harish Korgal  Page | 20


 

 
1 input C

2 input D

Traverse to the element X-Path

A html/body/div[1]/input[1]

B html/body/div[1]/input[2]

C html/body/div[2]/input[1]

D html/body/div[2]/input[2]

AB html/body/div[1]/input

CD html/body/div[2]/input

AC html/body/div/input[1]

BD html/body/div/input[2]

ABCD html/body/div/input

AD html/body/div[1]/input[1] | html/body/div[2]/input[2]
html/body/div[2]/input[2]  

BC html/body/div[1]/input[2] | html/body/div[2]/input[1]
html/body/div[2]/input[1]  

Note:

 
1. To combine multiple x-path we use pipeline (|) operator
2.  For n number of x-path we use n-1
n- 1 pipeline operator

  Relative X-path 
 X-path 

In order to reduce the length of x-path expression we use relative x-path.

In relative x-path “ //”” to traverse from parent to any child


x-path we use double slash “//

element. Where ‘//’ indicates traverse form parent to any child or immediate child. 
child. 

By: Harish Korgal  Page | 21


 

 
Traverse to the element X-Path

A //div[1]/input[1]

D //div[2]/input[2]

ABCD //div

AD //div[1]/input[1] | //div[2]/input[2]

Note: 
Note: 

1.  To find number of elements in any web page we use the below tag for x-path

For images  //img

For dropdowns  //select

For tables  //table

For links and images  //a | //img

2.  //a
//a   all the matching links and //a[1]
//a[1]   all the links which has index as 1

  X-path by attributes

In X-path we can use attribute in both absolute and relative x-path.


x -path.

Syntax:

tag[@Attribute_Name=
tag[@Attribute_Name= ‘Attribute_Value’]
‘Attribute_Value’] 

Example:

//a[@id= ‘a1’] 
‘a1’] 

@ it will inspect the element in all the direction within the same time

  Using multiple attributes in X-path


To combine multiple attributes we use and operator

Syntax:
_Name= ‘Attribute_Value’ and @Attribute_Na
tag[@Attribute_Name=
tag[@Attribute @Attribute_Name=
me= ‘Attribute_Value’] 
‘Attribute_Value’] 
Example:
//a[@id= ‘a1’ and @value= ‘text’] 
‘text’] 

  X-path by text() function 


 function 

By: Harish Korgal  Page | 22


 

 
When we don’t have attributes we use text() function. 
function. 

Syntax:

tag[text() = ‘Text_Value’] 
‘Text_Value’] 

Example:

Source code - <div>Login</div>

X-path -
X-path - //div[text()= ‘Login’] 
‘Login’] 
Source code - <td>Java</td>

X-path - //td[text()=
X-path - //td[text()= ‘Java’] 
‘Java’] 

Note: text() function can be replaced with . (Dot) in X-path


X-p ath

Ex: //td[
//td[.. = ‘Java’] 
‘Java’] 

When do we go for text() function


  When there is no attributes

  If attribute is matching with multiple web elements

  Handling partially dynamic elements


To handle partially dynamic element we use contains() function

Syntax:

tag[contains (text() , ‘text_value’)]


‘text_value’)]

Example: Inbox in Gmail application (Inbox 4,934) 


4,934) 

X-path = //a[contains ( . , ‘Inbox’)] 


‘Inbox’)] 

  Handling non breakable space 


 space 

Space can be of 2 ways

a.  Space bar / tab

b.  Using ‘&nbsp’ (non breakable space) 


space) 

X-path doesn’t supports for &nbsp


X-path &nbsp.. To handle &nbsp we use contains() function

Example: source code to develop space between text

<span>India **</span>

<span>Asia&nbsp**</span>

By: Harish Korgal  Page | 23


 

 
X-path

//span[contains(( . , ‘India’)] OR
//span[contains OR //span[
 //span[ . = ‘India’]
‘India’]  

//span[contains(( . , ‘Asia’)] 
//span[contains ‘Asia’)] 

How to verify whether text contains &nbsp or not

1.  Verify by using text() function

2.  If it return ‘No matching nodes’ then text contains &nbsp


&nbsp
When do we go for contains() function

1.  To handle partially dynamic elements

2.  To handle non breakable space

  Handling completely dynamic elements


To handle completely dynamic element we


element we use Independent-Dependent X-path OR
X-path by traversing

Source code:
<html>
<body>
<table border= “1”> 
“1”> 
<tbody>
<td>1</td> <td>Pizza</td> <td>550</td>
<td>2</td> <td>Burger</td> <td>350</td>
<td>3</td> <td>Cake</td> <td>250</td>
</tbody>
</table>
</body>
</html>

Output of the source code


1 Pizza 550
2 Burger 350
3 Cake 250

  X-path by traversing

Navigating from one element to another element is called as traversing. It is classified


into 2 types
1.  Forward traversing
2.  Backward traversing

By: Harish Korgal  Page | 24


 

Forward traversing –
traversing –  Navigating from parent to child element by using / or // 
// 
Backward traversing –
traversing –  Navigating from child element to parent element by using /..

Steps to inspect completely dynamic elements


1.  Inspect the static element
2.  Traverse from static element to common parent element i.e.
i.e. it
 it should highlight both
static and dynamic element
In the example Pizza, Burger and Coke are the static element and
element and 550, 350 and 250 are the
completely dynamic elements

1 Pizza 550
2 Burger 350
3 Cake 250
Example 1: Inspect the price of pizza
Pizza  static and independent element
550  dynamic and dependent element
X-path - //td[.= ‘Pizza’] /.. /td[3] 
/td[3] 

Example 2: Inspect the price of Burger


Burger  static and independent element
350  dynamic and dependent element
X-path - //td[.= ‘Burger’] /.. /td[3] 
/td[3] 

Example 3: Inspect the price of Cake


Cake static and independent element
250  dynamic and dependent element
X-path - //td[.= ‘Cake’] /.. /td[3] 
/td[3] 

  Siblings function 
 function 
Navigating from one child element to another child element is called as siblings
functions. It is classified into 2 types,
1.  Following sibling
2.  Preceding sibling

  Following sibling –
sibling –  It will highlight element below/after the current element

Syntax: /following-sibling :: tag
Syntax: /following-sibling

Example: Box office collection of Bahubali movie

A 1 Bahubali 999 B

2 1 1 2

By: Harish Korgal  Page | 25


 

 
Preceding Sibling Following Sibling

X-path - //td[.= ‘Bahubali’]/following-sibling


‘Bahubali’]/following-sibling :: td[1]


  Preceding sibling –
sibling –  It will highlight element above/before the current element
Syntax: /preceding-sibling :: tag
Syntax: /preceding-sibling

Example: To inspect element A

A 1 Bahubali 999 B

2 1 1 2
Preceding Sibling Following Sibling

X-path - //td[.= ‘Bahubali’]/preceding


‘Bahubali’]/preceding-sibling
-sibling :: td[2]

ele ment we use ancestor tag


To traverse from child to any parent element
Syntax:: /ancestor :: tag
Syntax
Example:: /ancestor :: a
Example
Note:
/   Traverse from parent to immediate child
//   Traverse from parent to any child
/..   Traverse from child to immediate parent
Sibling functions   Traverse from one child to another child
/ancestor   Traverse from child to any parent element

  X-path by group index 


 index 
If we cannot inspect the element by using attributes, text() function, contains() function
and Independent-Dependent x-path then we go for X-path by group index

In this we specify x-path within parenthesis and we specify index outside parenthesis
Syntax:
(X-path)[Index]
Example:  
Example:

1 html

1 body

1 div

1 input A

By: Harish Korgal  Page | 26


 

 
2 input B

2 div

1 input C

2 input D

//input ABCD 4 matching


//input[1] AC 2 matching
(//input)[3] C 1 matching
(//input[1])[2] C 1 matching
(//input)[4] D 1 matching

(//input)[4] It will execute parenthesis part first i.e.


i.e. it
 it will create one x-path array and it will

store all matching element inside an array and it will specify index for individual component or

element and later it will execute the index part

  To develop 10 checkbox and below are the x-path


 x -path

<input type="checkbox"><br>
type="checkbox"><br>
<input type="checkbox"><br>
type="checkbox"><br>
<input type="checkbox"><br>
type="checkbox"><br>
<input type="checkbox"><br>
type="checkbox"><br>
<input type="checkbox"><br>
type="checkbox"><br>
<input type="checkbox"><br>
type="checkbox"><br>
<input type="checkbox"><br>
type="checkbox"><br>
<input type="checkbox"><br>
type="checkbox"><br>
<input type="checkbox"><br>
type="checkbox"><br>
<input type="checkbox"><br>
type="checkbox"><br>

X-path Matching element

//input 10 (1 to 10)

(//input)[1] 1 (1)

(//input)[7] 1 (7)

(//input)[last()] 1 (10)

(//input)[last()-1] 1 (9)

(//input)[last()+1] No matching element

By: Harish Korgal  Page | 27


 

 
(//input)[position()>3] 7 (4 to 10)

(//input)[position()>3 and position()<8] 4 (4 to 7)

(//input)[position() > last()-1] 1 (10)

(//input)[position() mod 2=0] 5 (even checkbox)

(//input)[position() mod 2=1] 5 (odd checkbox)

To inspect 1st and last checkbox

(//input)[1] | (//input)[last()]

To inspect 2nd and 8th checkbox

(//input)[2] | (//input)[last()-2]

Note:
Out of 8 Locators majorly we use,
1.  id
2.  name
3.  linkText
4.  Xpath
a.  By attributes
b.  By text() function
c.  contains() function
d.  Independent-Dependen
Independent-Dependentt xpath or siblings
e.  Group by index

WEBELEMENT
Webelement is an Interface and it consists of 17 abstract methods
1.  clear()

2.  click()
3.  findElement(By arg)

4.  findElements(By arg)

5.  getAttribute(String arg)

6.  getCssValue(String arg)

7.  getLocation()

8.  getRect()

9.  getScreenshotAs
getScreenshotAs(OutputType<X>
(OutputType<X> arg)

10. getSize()

By: Harish Korgal  Page | 28


 

 
11. getTagName()

12. getText()

13. isDisplayed()

14. isSelected()

15. sendKeys(CharSequence..arg)

 
16. submit()
17. isEnabled()

Script1 –
Script1  – To
 To verify text box is displayed in page or not
n ot

Source code <input type= “text” value= “abc”> 


“abc”> 

public class Lauch


{
public static void main(String[] args)
{
String key="webdriver.gecko.driver";
key="webdriver.gecko.driver";
String value="./software/geckodriver.exe";
value="./software/geckodriver.exe";
System.setProperty(key,value);

WebDriver driver = new FirefoxDriver();


driver.get("file:///C:/Users/Harish%20Korgal/Desktop/google.html");

WebElement ele = driver.findElement(By.xpath("//input[@value='abc']"))


driver.findElement(By.xpath("//input[@value='abc']"));;
if(ele. isDisplayed())
if(ele.isDisplayed ())
{
System.out.println("Element
System.out.println(" Element is displayed");
}else{
System.out.println("Element
System.out.println(" Element is not displayed");
}
}
}

Script2 –
Script2  – To
 To verify whether element is enabled or disabled

Source code <input type= “text” value= “abc” disabled>


“abc” disabled>

public class Lauch


{
public static void main(String[] args)
{
String key="webdriver.gecko.driver";
key="webdriver.gecko.driver";
String value="./software/geckodriver.exe";
value="./software/geckodriver.exe";

System.setProperty(key,value);
WebDriver driver = new FirefoxDriver();

By: Harish Korgal  Page | 29


 

 
driver.get("file:///C:/Users/Harish%20Korgal/Desktop/google.html");
WebElement ele = driver.findElement(By.xpath("//input[@value='abc']"))
driver.findElement(By.xpath("//input[@value='abc']"));;
if(ele. isEnabled())
if(ele.isEnabled ())
{
System.out.println("Element
System.out.println(" Element is enable");
}else{
System.out.println("Element
System.out.println(" Element is disable");
}
}
}

Script3 –
Script3  – To
 To verify whether checkbox is selected or not
n ot

Source code <input type= “checkbox” checked> 


checked> 

b=ele.isSelected()
boolean b=ele.isSelected()
System.out.println(b);

if(ele. isSelected ())
if(ele. isSelected ())
{
System.out.println("checkbox
System.out.println("checkbox is checked");
}else{
System.out.println("checkbox
System.out.println("checkbox is unchecked ");
}

Script4 –
Script4  – To
 To clear the default value in text box

clear()
ele.clear()
ele.

Script5 –
Script5  – To
 To clear the data in text box without using clear() method

ele.sendKeys(Keys.CONTROL+
ele.sendKeys( Keys.CONTROL+ “a”);
“a”);
sendKeys(Keys.DELETE);
ele.sendKeys(Keys.DELETE);
ele.

Script6 –
Script6  – To
 To click link without using click() method

sendKeys(Keys.ENTER);
ele.sendKeys(Keys.ENTER);
ele.

Script7 –
Script7  – To
 To copy data from 1 text box to another text box

WebElement ele1 = driver.findElement(By.id("t1"


driver.findElement(By.id("t1"));
));
ele1.sendKeys(Keys.CONTROL+"a");
ele1.sendKeys(Keys.CONTROL+"a" );
ele1.sendKeys(Keys.CONTROL+"c");
ele1.sendKeys(Keys.CONTROL+"c" );

WebElement ele2 = driver.findElement(By.id("t2"));


driver.findElement(By.id("t2"));
ele2.sendKeys(Keys.CONTROL+"v");
ele2.sendKeys(Keys.CONTROL+"v");

By: Harish Korgal  Page | 30


 

 
Note: we can write as “ele.sendKeys(Keys.CONTROL+"ac"
“ele.sendKeys(Keys.CONTROL+"ac");”
);”  

Script8 –
Script8  – To
 To print text of the element

WebElement ele = driver.findElement(By.xpath(“//a[.=


driver.findElement(By.xpath(“//a[.= ‘Actitime’]”)); 
‘Actitime’]”)); 
ele.getText();
String text = ele.getText();
System.out.println(text);

Script9 –
Script9  – To
 To print location of the element in webpage

WebElement ele = driver.findElement(By.xpath(“//a[.=


driver.findElement(By.xpath(“//a[.= ‘Actitime’]”)); 
‘Actitime’]”)); 
ele. getLocation();
Point p = ele.getLocation ();
System.out.println(p);

Output: (352, 261)  x and y axis of the element

HANDLING MULTIPLE ELEMENTS


  To handle multiple elements we use findElements()
findElements() method
 method

  Return type of findElements() is List<WebElement>


List<WebElement> (collection
 (collection of web elements)

  List is an interface
interface and
 and it is one of the collection type

  List should be imported from the package ‘import.java.util.List’;


‘import.java.util.List’;  

  If the specified locator is matching with multiple web elements


ele ments then findElements() will

return address of all the matching elements

  If the specified locator is not matching with any of the web elements then

findElements() will throw empty list or empty array 


array 

   To find number of links in facebook application


List<WebElement>  links = driver.findElements(By.tagName(“a”));
List<WebElement> driver.findElements(By.tagName(“a”));  

int count = links.size(); page  


//No of links in page

System.out.println(count); 
System.out.println(count); 

   To print the text of all the links in webpage

List<WebElement>  links = driver.findElements(By.tagName(“a”));
List<WebElement> driver.findElements(By.tagName(“a”));  
int count = links.size(); //No of links in page
page  

By: Harish Korgal  Page | 31


 

 
System.out.println(count);  
System.out.println(count);

for (int i=0; i<count; i++)


{
WebElement we=links.get(i);
String text = we.getText(); //get the title of links
links  
System.out.println(text);  
System.out.println(text);
}

Using Enhanced for loop

for(WebElement we : links)
{
String text = we.getText();
System.out.println(text);  
System.out.println(text);
}

  Handling auto suggestions 


 suggestions 
Scenario:
 
1.
2.  Open browser
Enter url https://www.google.com)) 
(https://www.google.com
3.  ‘Java’ in
Type ‘Java’  in search box
4.  Count number of auto suggestions
5.  Print text of all auto suggestions
6.  Select the last auto suggestion

Script:
public class Lauch
{
public static void main(String[] args) throws InterruptedException
{
String key="webdriver.gecko.driver";
key="webdriver.gecko.driver";
String value="./software/geckodriver.exe";
value="./software/geckodriver.exe";
System.setProperty(key,value);

WebDriver driver = new FirefoxDriver(); 1 


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

driver.findElement(By.id("//input[@id='lst-ib']")).sendKeys("Java");
driver.findElement(By.id("//input[@id='lst-ib']")).sendKeys("Java"); //step 3 

Thread.sleep(3000);

List<WebElement> auto =
driver.findElements(By.className("//div[@c
driver.findElements(By.className("//div[@class='sbqs_a']"));
lass='sbqs_a']"));
int count=auto.size();
count=auto.size(); //step 4 

By: Harish Korgal  Page | 32


 

 
System.out.println(count);

for(int i=0; i<count; i++)


{
WebElement we = auto.get(i);
String text=we.getText();
System.out.println(text); //step5  
//step5

auto.get(count-1).click(); //step6  
//step6
}
}

  Difference between findElement() and findElements() 


 findElements() 

findElement() findElements()

1. Return type is –


is –  WebElement 1. Return type is
is –
 – List
 List <WebElement>

2. If specified locator matching with multiple 2. If specified locator matching with multiple

element, it will return the 1st matching element, it will return all the matching

element elements

3. If specified locator
locator is not matching any
any 3. If specified locator
locator is not matching any

element it will return element it will return

‘NoSuchElementException’  
‘NoSuchElementException’ Empty list or Empty array 
array  

  Enter URL without using get() method 


 method  
To enter URL we use navigate() method

driver.navigate().to
driver.navigate().to((https://www.google.com
https://www.google.com)) 
where, navigate()
navigate() method
 method internally calls get()
get() method
 method

Note:
1.  driver.navigate().back()  to move previous page
2.  driver.navigate().forward()  to move next page
3.  driver.navigate().refresh()  to refresh the page

HANDLING FRAMES 

Developing page inside another webpage is called as nested webpage or embedded


webpage. To develop frame, developer use <iframe>
<iframe> tag
 tag

By: Harish Korgal  Page | 33


 

To perform action on the element which is present inside a frame, first we need to
switch control from page to frame by using below statement,
driver.switchTo().frame();

Frame method is overloaded i.e.


1.  frame (int arg);  using index
2.  frame(String arg)  using id
3.  frame(WebElement arg)  using address of the frame
frame
If we try to use multiple frame methods for a single frame it will throw
‘NoSuchElementException’ (Selenium run time exception)

To switch back the control from frame to page, we use below statement,
driver.switchTo().defaultContent();

Note: To
Note: To verify web element is in frame or not

1.  Right click on element

2.  If it display ‘This


‘This frame’ option
frame’ option the it is present in frame

a.  For Chrome browser  it display as ‘Frame source / Frame page source 
source  

b.  For IE browser  it display as ‘Frame element’ 


element’  

Source code:
For page3.html (frame)
t2 : <input id= “t3” type= “text”> 
“text”> 

For page2.html (frame)


t2 : <input id= “t2” type= “text”> 
“text”> 

<iframe id= “f2” src = “page3.html”>


“page3.html”>  
For page1.html
T1 : <input id= “t1” type= “text”> 
“text”> 
<iframe id= “f1” src = “page2.html”>
“page2.html”>  
Script

public class Lauch


{
public static void main(String[] args) throws InterruptedException
{
String key="webdriver.gecko.driver";
key="webdriver.gecko.driver";
String value="./software/geckodriver.exe";
value="./software/geckodriver.exe";

By: Harish Korgal  Page | 34


 

 
System.setProperty(key,value);

WebDriver driver = new FirefoxDriver();


driver.get("file:///C:/Users/Harish%20Korgal/Desktop/page1.html");

driver.findElement(By.id("t1")).sendKeys("acb"); //text box 1


1  

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


driver.switchTo().frame("f1"); //by id 
id 

WebElement text = driver.findElement(B


driver.findElement(By.xpath(".//*[@id='
y.xpath(".//*[@id='t2']"));
t2']"));
text);
driver.switchTo().frame(text
driver.switchTo().frame( element 
); //by address of the element 

driver.findElement(By.id("t2")).sendKeys("abc"); //text box 2


2  

page  
driver.switchTo().defaultContent(); //switch back to parent page 
driver.findElement(By.id("t1")).sendKeys("mno");//text
driver.findElement(By.id("t1")).sendKeys("mno"); 1 
//text box 1 

}
}

Note:

1.  driver.switchTo().frame()  page to frame

2.  driver.switchTo().defaultContent()  default page

3.  driver.switchTo().parentFrame();  switch to immediate parent frame

HANDLING DROPDOWNS 

Dropdwons can
can be classified into 2 types

1.  Single select dropdown

2.  Multiple select dropdown

o   To handle dropdown we don’t have specific method in ‘WebElement’ or ‘WebDriver’ 


‘WebDriver’ 

o   To handle dropdown we go for ‘Select’


‘Select’ class
 class

o   ‘Select’ class is a concrete class and should be imported from


import org.openqa.selenium.support.ui.Select;

class Select
{

{Select(WebElement ele
ele)) //ele is a address
address of
of the dropdown

By: Harish Korgal  Page | 35


 

}
}

Select(ele);
Select s = new Select(ele); //ele is a address
address of
of the dropdown

Source code to develop dropdown


<html>
<body>
<select id="MTR">
<option value="i">Idly</option>
<option value="d">Dosa</option>
value="d">Dosa</option>
<option value="u">Upma</option>
value="u">Upma</option>
<option value="p">Pongal</option>
value="p">Pongal</option>
<option value="d">Dosa</option>
value="d">Dosa</option>
</select><br><br><br><br>

<select id="Iyengar" multiple>


<option value="i">Idly</option>
<option value="d">Dosa</option>
value="d">Dosa</option>
<option value="u">Upma</option>
value="u">Upma</option>
<option value="p">Pongal</option>
value="p">Pongal</option>
<option value="d">Dosa</option>
value="d">Dosa</option>
</select>
</body>
</html>

To select an option we have list of methods in ‘Select’ class 


class  

a.  selectByIndex(int index);

b.  selectByValue(String value);

c.  selectByVisibleText(Stri
selectByVisibleText(String
ng text);

o  In dropdown index starts from 0


o  Value and visible text are case sensitive
o  ‘ NoSuchElementException’  
If the specified option is invalid the it will show ‘NoSuchElementException’
o  If the specified option is duplicate in single select dropdown, then it will select 1 st 
matching value
o  If the specified option is duplicate in multiple select dropdown, then it will select

all duplicate values


Note:

By: Harish Korgal  Page | 36


 

 
Select class consist of parameterized constructor
constructor which takes argument of WebElement (i.e. for

the address of the dropdown as argument inside Select class constructor)

  WAS to select specified option using select class 


 class  

public class Explict


{
public static void main(String[] args) throws InterruptedException
{
String key="webdriver.gecko.driver";
key="webdriver.gecko.driver";
String value="./software/geckodriver.exe";
value="./software/geckodriver.exe";
System.setProperty(key,value);

WebDriver driver = new FirefoxDriver();


driver.get("file:///C:/Users/Harish%20Korgal/Desk
driver.get("file:///C:/Users/Harish%20Korgal/Desktop/dropdown.h
top/dropdown.html");
tml");

WebElement eleele =
 = driver.findElement(By.id("Iyengar"));
driver.findElement(By.id("Iyengar"));
Select(ele);
Select s = new Select(ele );
s.selectByIndex(2);
s.selectByIndex (2);
s.selectByValue("d");
s.selectByValue ("d");
s.selectByVisibleText("Dosa");
s.selectByVisibleText ("Dosa");
}
}

To deselect an option in ‘Select’ class we have below list of methods, 


methods,  

a.  deselectAll();

b.  deselectByIndex(int index);

c.  deselectByValue(Stri
deselectByValue(String
ng value);

d.  deselectByVisibleText(S
deselectByVisibleText(String
tring text);

Note:

  If we try to use deselect methods on a single select dropdown it will throw


‘UnSupportedOperationException’  
‘UnSupportedOperationException’

By: Harish Korgal  Page | 37


 

 
  To verify whether dropdown is single/multiple select, we use ‘isMultiple()’
 ‘isMultiple()’ method
 method  

  WAS to select and deselect the values 


 values  

public class Explict


{
public static void main(String[] args) throws InterruptedException
{
String key="webdriver.gecko.driver";
key="webdriver.gecko.driver";
String value="./software/geckodriver.exe";
value="./software/geckodriver.exe";
System.setProperty(key,value);

WebDriver driver = new FirefoxDriver();


driver.get("file:///C:/Users/Harish%20Korgal/Deskto
driver.get("file:///C:/Users/Harish%20Korgal/Desktop/dropdown.html"
p/dropdown.html");
);

WebElement eleele =
 = driver.findElement(By.id("Iyengar"));
driver.findElement(By.id("Iyengar"));
Select(ele);
Select s = new Select(ele );
s.selectByIndex(2);
s.selectByValue("d");
s.selectByVisibleText("Dosa");

if(s.isMultiple())
if(s.isMultiple ())
{
s.deselectByIndex(2);
s.deselectByIndex (2);
s.deselectByValue("d");
s.deselectByValue ("d");
s.deselectByVisibleText("Dosa");
s.deselectByVisibleText ("Dosa");
}else{
System.out.println("Dropdown
System.out.println("Dropdown is a single select dorpdown");
}
}
}

  WAS to count number of values in dropdown 


 dropdown 

{
WebElement ele
ele  = driver.findElement(By.id("Iyengar"));

Select(ele);
Select s = new Select(ele);

By: Harish Korgal  Page | 38


 

 
List<WebElement> option = s.getOptions();

int count = option.size();

System.out.println(count);

  WAS to count number of values in dropdown, select all and deselect all
 all  

{
WebElement ele = driver.findElement(By.
driver.findElement(By.id("Iyengar"));
id("Iyengar"));
Select s = new Select(ele);
List<WebElement> option = s.getOptions();
int count = option.size(); //get size
size  
for(int i=0;i<count;i++)
{
s.selectByIndex(ii); //select all 
s.selectByIndex( all 
}
s.deselectAll();
s.deselectAll (); //deselect all
all  
}

  WAS to print all the values in dropdown 


 dropdown  
{
WebElement ele = driver.findElement(By.
driver.findElement(By.id("Iyengar"));
id("Iyengar"));
Select s = new Select(ele);
List<WebElement> option = s.getOptions();
size 
int count = option.size(); //get size 
for(WebElement we : option)
{
String text = we.getText();
we.getText();
System.out.println(text);

  WAS to print all the values in dropdown in ascending/descending order


 order  
{
WebElement ele = driver.findElement(By.
driver.findElement(By.id("Iyengar"));
id("Iyengar"));
Select s = new Select(ele);
List<WebElement> option = s.getOptions();
ArrayList<String> l = new ArrayList<String>();
for(WebElement we : option)

By: Harish Korgal  Page | 39


 

 
{
String text = we.getText();
we.getText();
l.add(text);
}
//sorting  
Collections.sort(l); //sorting
for(String t : l)
{
//printing  
System.out.println(t); //printing
}
}

  WAS to verify whether specified option is present in dropdown or not 


 not  
{
WebElement ele = driver.findElement(By.
driver.findElement(By.id("Iyengar"));
id("Iyengar"));
Select s = new Select(ele);
List<WebElement> option = s.getOptions();
ArrayList<String> l = new ArrayList<String>();
for(WebElement we : option)
{
String text = we.getText();
we.getText();
l.add(text);
}

if(l.contains("Idly"))
if(l.contains("Idly"))
{
System.out.println("Option
System.out.println("Option is present");
}else{
System.out.println("Option
System.out.println("Option is not present");
}
}

Note:
1.  ‘Select’ class methods will work only if the tag is SELECT 
SELECT 
2.  If we try to use ‘Select’ class method on different tag it will throw
‘NoSuchElementException’
‘NoSuchElementE xception’ or ‘UnExpectedTagName’
‘UnExpectedTagName’

HANDLING MOUSE OVER ACTIONS


  To handle mouse over action we go for ‘Action
‘Actionss’ class

  ‘Action’ class is a concrete class 


class 

  Action class should be imported from the package


import org.openqa.selenium.support.ui.Actions;

By: Harish Korgal  Page | 40


 

 
  Action class consist of parameterized constructor and it takes argument of address of
application

class Actions
{
Actions(WebDriver driver) //driver is a application control (or) address of the app 
{

}
}
Actions(driver);
Actions act = new Actions(driver );

Methods of ‘Actions
‘Actions’ class: 
class: 

1.  moveToElement()

2.  dragAndDrop()

3.  rightClick() / contextClick()

4.  doubleClick()

  WAS to mouse over of men and select option in flipkart 


 flipkart  

public class Sample


{
public static void main(String[] args) throws InterruptedException
{
String key="webdriver.gecko.driver";
key="webdriver.gecko.driver";
String value="./software/geckodriver.exe";
value="./software/geckodriver.exe";
System.setProperty(key,value);

WebDriver driver = new FirefoxDriver();


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

driver.findElement(By.xpath("//button[.='✕']")).click();

Thread.sleep(3000);

WebElement ele = driver.findElement(By.xpath("//span


driver.findElement(By.xpath("//span[.='Men']"));
[.='Men']"));

Actions(driver);
Actions act = new Actions(driver application  
); //address of the application

act. moveToElement(ele).perform();
act.moveToElement (ele).perform();

Thread.sleep(3000);

By: Harish Korgal  Page | 41


 

 
driver.findElement(By.xpath("//span
driver.findElement(By.xpath("//span[.='T-Shirts']")).click(
[.='T-Shirts']")).click();
);

}
}

Note:

  To perform mouse over action in Actions class we use ‘moveToElement()’ method 


method 

  In Action class by default we should call ‘perform()’


‘perform()’ method
 method

HANDLING DRAG AND DROP ACTION


  To handle drag and drop we use Actions
Actions class
 class

  In Actions class we use ‘dragAndDrop()


‘ dragAndDrop()’’ method 
method 

  It takes 2 arguments (source and target)



  In Actions class by default we should use ‘perform()’
‘perform()’ method
 method

Script:

WebElement b1 = driver.findElement(By.xpath("h1[.='Book1'"));
driver.findElement(By.xpath("h1[.='Book1'"));
WebElement b2 = driver.findElement(By.xpath("h1[.='Book3'"));
driver.findElement(By.xpath("h1[.='Book3'"));

Actions act = new Actions(driver);


act. dragAndDrop(b1,b2).perform();
act.dragAndDrop (b1,b2).perform();

}
HANDLING RIGHT CLICK OR CONTEXT CLICK ACTION
  To handle right click action we go for Actions
Actions class
 class

  In Actions class we use ‘contextClick()


‘ contextClick()’’ method 
method 

  In Actions class by default we should use ‘perform()’


‘perform()’ method
 method

Script:

public class Sample


{
public static void main(String[] args) throws InterruptedException, AWTException

By: Harish Korgal  Page | 42


 

 
{
String key="webdriver.gecko.driver";
key="webdriver.gecko.driver";
String value="./software/geckodriver.exe";
value="./software/geckodriver.exe";
System.setProperty(key,value);

WebDriver driver = new FirefoxDriver();


driver.get("https://www.seleniumhq.org/");

WebElement link = driver.findElement(By.xpath("//li[@id='men


driver.findElement(By.xpath("//li[@id='menu_download']"))
u_download']"));;

Actions act = new Actions(driver);


act. contextClick(link).perform();
act.contextClick (link).perform();

Robot r = new Robot();


r.keyPress(KeyEvent.VK_W);
r.keyPress (KeyEvent.VK_W);
r.keyRelease(KeyEvent.VK_W);
r.keyRelease (KeyEvent.VK_W);
}
}

Note: VK  virtual key and W  shortcut to click

1.  To handle keyboard functionality we use ‘Robot’


‘Robot’ class
 class

2.  Robot class is a concrete class

3.  All the keyboard functionality are static final variables

HANDLING DOUBLE CLICK ACTION


1.  To handle double click action, we use ‘Actions’ class

2.  In Actions class we use ‘doubleClick()’


‘doubleClick()’ method
 method

3.  In Actions class by default we should call perform() method

Script:

WebElement link = driver.findElement(By.xpath("//li[@id='m


driver.findElement(By.xpath("//li[@id='menu_download']")
enu_download']"));
);

Actions act = new Actions(driver);

Thread.sleep(3000);

act. doubleClick(link).perform();
act.doubleClick (link).perform();

HANDLING POP-UPS
In selenium pop-ups are classified into 6 types,

By: Harish Korgal  Page | 43


 

 
1.  Alert and confirmation popup

2.  Hidden division popup

3.  File upload popup

4.  File download popup

5.  Child browser popup

6.  Window popup

  Alert and confirmation popup (Java script popup) 


 popup) 

To handle this popup we use ‘Alert’


‘Alert’ interface
 interface

Characteristics:

1.  We cannot inspect the popup

2.  We cannot move the popup


3.  It consist of ‘Ok’ and ‘Cancel’ buttons 
buttons 

Note:

  To click ‘Ok’ button
‘Ok’ button we use  accept()
accept() method
 method

  To click ‘Cancel’ button we use  dismiss()


dismiss() method
 method

  To switch control from page to alert popup we use,


driver.switchTo().alert(); 
driver.switchTo().alert(); 


  To return the text inside the popup we use, .getText() (present in Alert interface)
  If we try to use both accept() and dismiss() method for single popup, it will throw

‘NoAlertPresentException’ 
‘NoAlertPresentException’ 

Script:

WebElement block = dirver.findElement(By.xpath(“//input[.=


dirver.findElement(By.xpath(“//input[.= ‘Men’]”));
‘Men’]”));

block.click();

Alert a = driver.switchTo().alert();
driver.switchTo().alert(); //switch control to alert popup

By: Harish Korgal  Page | 44


 

 
String text = a.getText();

System.out.println(text);

a.accept(); OR

a.dismiss()

  Hidden division popup 


 popup 

Initially the popup is hidden and if we perform action on the element then it will display

the popup and basically this popup was developed by using ‘div’
‘div’ tag.
 tag.

To handle this popup we use findElement()


findElement() method
 method

Characteristics:
1.  We can inspect the popup

2.  We cannot move the popup

Script to click on the date in the calendar

dirver.findElement(By.xpath(“//i[.=
dirver.findElement(By.xpath(“//i[.= ‘Cal’]”)).click(); 
‘Cal’]”)).click(); 

dirver.findElement(By.xpath(“//i[.=
dirver.findElement(By.xpath(“//i[.= ‘27’]”)).click(); 
‘27’]”)).click(); 

  File upload popup 


 popup 

To handle this popup we use ‘sendKeys()


‘sendKeys()’’ method. In this method we specify the path of file

which has to be selected.

Characteristics:

1.  We cannot inspect element

2.  We can name the popup

By: Harish Korgal  Page | 45


 

 
3.  It consist of 2 buttons ‘Open’ and ‘Cancel’ 
‘Cancel’  

Note: To copy file path we use (shift


( shift + right click on file copy as path
path))

Source code to develop browser button


<html>
<body>

<form>
Pick any file to upload: <input type= “file” name= “uploadfile” id= “upload”>
“upload”>  
</form>
</body>
</html>
Script to upload the file

driver.findElement(By.
driver.findElement(By.id(“upload”)).sendKeys
id(“upload”)).sendKeys (“C:\Users\Harish
(“C:\Users\Harish

Korgal\Desktop\dropdown.html”)
Korgal\Desktop\dropdown.html”);;

  File download popup 


 popup 

  In case of firefox browser, it will display the file download popup


  In case of chrome browser and IE browser it will not display popup
  To hand file download popup we use ‘Robot’
‘Robot’ class
 class

Characteristics:

1.  We cannot inspect the popup

2.  We can move the popup

3.  It consist of 2 radio buttons

a.  Open with

b.  Save file

4.  It consist of 2 buttons

a.  Ok

b.  Cancel

5.  To click ‘Ok’ button we use ‘ENTER’


‘ENTER’ command
 command

6.  To click ‘Cancel’ button we use ‘ESCAPE’ command

By: Harish Korgal  Page | 46


 

 
7.  To shift control from open with  to save file we use ‘Alt+S’
‘Alt+S’  

8.  To shift control from save file  open with we use ‘Alt+O’
‘Alt+O’  

Script to download a file in browser

public class FileDownload


{
public static void main(String[] args) throws InterruptedException, AWTException
{
String key="webdriver.gecko.driver";
key="webdriver.gecko.driver";
String value="./software/geckodriver.exe";
value="./software/geckodriver.exe";
System.setProperty(key,value);

WebDriver driver = new FirefoxDriver();


driver.get("https://www.seleniumhq.o
driver.get("https://www.seleniumhq.org/download/");
rg/download/");

WebElement ele = driver.findElement(By.xpath("//td


driver.findElement(By.xpath("//td[.='C#']/following-
[.='C#']/following-
sibling::td[3]"));

ele.sendKeys(Keys.ENTER);
Thread.sleep(3000);

Robot r = new Robot();


r.keyPress(KeyEvent.VK_ALT);
r.keyPress(KeyEvent.VK_S);

r.keyRelease(KeyEvent.VK_ALT);
r.keyRelease(KeyEvent.VK_S);

r.keyPress(KeyEvent.VK_ENTER);
r.keyRelease(KeyEvent.VK_ENTER);
}
}

  Child browser popup 


 popup 

popup  
The browser re-sized to look like a popup is called as child browser popup

By: Harish Korgal  Page | 47


 

 
Characteristics:

1.  We cannot inspect the popup

2.  We can move the popup

3.  We can minimize, maximize and close the popup

To handle child browser popup we use, getWindowHandle()


getWindowHandle() and
 and getWindowHandles()
getWindowHandles() method
 method
getWindowHandle()  retrieves only the id of the parent browser

getWindowHandles()  retrieves only the id of the parent browser and child browsers (all

browsers)

wndowHandle –
wndowHandle – it
 it is a unique alpha-numeric String of the browser

Script to print the id of the parent browser

public class Sample


{
public static void main(String[] args)
{
String key="webdriver.gecko.driver";
key="webdriver.gecko.driver";
String value="./software/geckodriver.exe";
value="./software/geckodriver.exe";
System.setProperty(key,value);

WebDriver driver = new FirefoxDriver();


driver. getWindowHandle();
String parent = driver.getWindowHandle ();
System.out.println(parent);
}
}

Script to print id of all browsers and count number of browsers

  Window popup 
 popup 

1.  To handle window popup we use ‘AutoIT’


‘AutoIT’ software
 software

2.  ‘AutoIT’ is a free automation tool which is mainly used to handle window popup/ stand

alone application

3.  AutoIT can be downloaded from - 


- https://www.
https://www.autoitscript.com/site
autoitscript.com/site/autoit/downloads
/autoit/downloads// 

Steps to fetch the title of window popup

By: Harish Korgal  Page | 48


 

 
1.  Start  All program  AutoIT V3  AutoIT window Infor(x64)

2.  Drag and drop finder tool on standalone application or window popup

3.  Finder tool will display the options like


li ke ‘Title’, ‘Class’, ‘Position’…
‘Position’…  

Steps to write VB script in AutoIT

1.  Launch (Start  AutoIT  SciTE script executor)


executor)
2.  Specify path of stand alone application (.exe
(.exe)) i.e. ("C:\Windows\System32\calc.exe")
("C:\Windows\System32\calc.exe")

3.  Open application

4.  Perform action on application

5.  Close the application

Write the below script in ‘SciTE


‘ SciTE script executor’
executor’ application to perform action on calculator 
calculator 

Run("C:\Windows\System32\calc.exe")

WinWaitActive("Calculator")
Sleep(3000)

Send("6")

Sleep(3000)

Send("-")

Sleep(3000)

Send("4")

Sleep(3000)

Send("=")
Sleep(3000)

WinClose("Calculator")

1.  Click on File  Save  file_name.au3

2.  Click Tools  compile (It generates .exe file)

Script:

import java.io.IOException;
import java.io.IOException;

By: Harish Korgal  Page | 49


 

 
public
public 
 class Sample
class Sample
{
public
public  static 
static  void
void main(String[]
 main(String[] args
args)
) throws
throws IOException
 IOException
{
Runtime.getRuntime ().exec(
().exec("C:\\Users\\Harish
"C:\\Users\\Harish
Korgal\\Desktop\\cal1.exe");
Korgal\\Desktop\\cal1.exe");
}
}

Note:

Sl.No Pop-ups Solution

1. Alert and confirmation driver.switchTo().alert();


driver.switchTo().alert();

2. Hidded division Ok –


Ok – accept();
 accept(); and cancel –
cancel – dismiss();
 dismiss();

3. File upload sendKeys(path of file);

4. File download Robot class or AutoIT

5. Child browser getWindowHandle() or getWindowHandles()


getWindowHandles()

driver.switchTo().window(id
driver.switchTo().window(id of browser)

6. Window popup AutoIT

Interview Questions:

1.  Minimize browser


Robot r = new
new Robot();
 Robot();

r .keyPress(KeyEvent.VK_ALT 
r.keyPress(KeyEvent. )
);
VK_SPACE ;);
r.keyPress(KeyEvent.VK_N )
);;

r.keyRelease(KeyEvent.VK_ALT ));;
r.keyRelease(KeyEvent.VK_SPACE );
r.keyRelease(KeyEvent.VK_N )
);; 

2.  Close browser (without using quit and close method)


Robot r = new
new Robot();
 Robot();

r.keyPress(KeyEvent.VK_ALT ));
;
r.keyPress(KeyEvent.VK_SPACE);
r.keyPress(KeyEvent.VK_C )
); ;

r.keyRelease(KeyEvent.VK_ALT )
);;

By: Harish Korgal  Page | 50


 

 
r.keyRelease(KeyEvent.VK_SPACE );
r.keyRelease(KeyEvent.VK_C )
);; 

3.  Resize the browswer and maximize browser


Dimension d = new
new 
 Dimension(300,200);
Dimension(300,200);
driver .manage().window().setSize(d
driver.manage().window().setSize( d);

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

4.  To drag browser to particular x and y axis


Point p = new
new 
 Point(300,200);
Point(300,200);
p); 
driver .manage().window().setPosition(p
driver.manage().window().setPosition(

 Java Script Executor


  To handle disabled element we use Java Script executor


  It is a Interface
Interface  

To access Java Script Executor methods we Type cast from WebDriver to Java script

interface (explicit type casting) i.e.


WebDriver driver =
driver  = new
new 
 FirefoxDriver();
FirefoxDriver();
JavascriptExecutor js =
js = (JavascriptExecutor) driver ; 
(JavascriptExecutor) driver;

I  SearchContext

I WebDriver I  JavaScriptExecutor

© 
RemoteWebDriver

© Firefox © Google Chrome © Inter explorer

By: Harish Korgal  Page | 51


 

 
  Java script executor should be imported from the following package 
package  
import
import  org.openqa.selenium.Jav
org.openqa.selenium.JavascriptExecutor; 
ascriptExecutor;

Java script executor consist of 2 abstract methods, 


methods, 

1.   js.executeAsync
 js.executeAsyncScript(String...
Script(String...arg0,
arg0, Object..args.arg1);
Object..args.arg1);

2.   js.executeScript(S
 js.executeScript(String...arg0,
tring...arg0, Object..args.arg1);
Object..args.arg1);

Script: To pass the data inside


insid e disabled text box without using sendKeys method

Source code: <input
code: <input id="t1" type="text" value="abc" disabled>
public 
public class Sample
class Sample
{
public
public  static  void
 static  void main(String[]
 main(String[] args
args)
)
{

System.setProperty("webdriver.gecko.driver" ,"./softwares/geckodriver.exe" );

driver =
WebDriver driver  = new
new 
 FirefoxDriver();
FirefoxDriver();
driver .get("file:///C:/Users/Harish%20Korgal/Desktop/disabled.html"
driver.get( "file:///C:/Users/Harish%20Korgal/Desktop/disabled.html" );

JavascriptExecutor js
js =
 = (JavascriptExecutor)
(JavascriptExecutor) driver;
driver ;
js.executeScript(
js.executeScript("document.getElementById('t1').value('XYZ')"
"document.getElementById('t1').value('XYZ')" );
}

Note:

  document  partially implemented class


  getElementById  static method of document class
  To pass data inside text box we use value
value comment.
 comment. It will override the value 
value 

By: Harish Korgal  Page | 52


 

 
Script to scroll down webpage for 500 pixels and scroll up for 500 pixels
public
public 
 class Sample
class Sample
{
public 
public  static 
static  void
void main(String[]
 main(String[] args
args)
) throws
throws 
 Interrupted
InterruptedException
Exception
{

System.setProperty("webdriver.gecko.driver" ,"./softwares/geckodriver.exe" );

WebDriver driver
driver =
 = new
new 
 FirefoxDriver();
FirefoxDriver();
driver.get(
driver .get("https://www.amazon.in/"
"https://www.amazon.in/" );

JavascriptExecutor js =
js = (JavascriptExecutor)
(JavascriptExecutor) driver;
driver ;

js.executeScript(
js.executeScript("window.scrollBy(0,500)"
"window.scrollBy(0,500)" ); //scroll down
down  
Thread.sleep(4000);
js
js.executeScript(
.executeScript("window.scrollBy(0,-500)"
"window.scrollBy(0,-500)");
); //scroll up 
up 
}

Script to scroll down webpage for specified element


public 
public class Sample
class Sample
{
public 
public  static 
static  void
void main(String[]
 main(String[] args
args)
) throws
throws 
 Interrupted
InterruptedException
Exception
{

System.setProperty("webdriver.gecko.driver","./softwares/geckodriver.exe ");
webdriver.gecko.driver",

WebDriver driver
driver =
 = new
new 
 FirefoxDriver();
FirefoxDriver();
driver.get(
driver .get("https://docs.seleniumhq.org/"
"https://docs.seleniumhq.org/" );

ele =
WebElement ele = driver.findElement(By.
driver .findElement(By. xpath("//a[.='Selenium
Conf 2016']"));
2016']"));

Point p = ele.getLocation();


ele.getLocation();
int x = p.getX();
int 
int 
int y = p.getY();

JavascriptExecutor js =
js = (JavascriptExecutor)
(JavascriptExecutor) driver;
driver ;

js.executeScript(
js.executeScript("window.scrollBy("
"window.scrollBy("+
+x+","
","+
+y+")");
")");
}

By: Harish Korgal  Page | 53


 

 
Advantages of Java Script Executor: 
Executor: 

1.  To handle disabled element

2.  To pass the data inside text box without sendKeys()

3.  To clear the data inside text box without clear()

4.  To scroll down and scroll up web page

 Take Screen Shot:


I  SearchContext

JavaScriptExecutor I WebDriver I  TakeScreenShot

© 
RemoteWebDriver

© Firefox © Google Chrome © Inter explorer

1.  Take screen shot is Interface


Interface consist
 consist of 1 Abstract method 
method (getScreenshotAs())
(getScreenshotAs())

2.  Take screen shot should be imported from the following package,

Steps to take screenshot of application: 


application:  

1.  Typecast from WebDriver


WebDriver to
 to TakeScreenShot
TakeScreenShot interface
 interface

2.  Capture the screenshot by using getScreenshotAs() method and it will store screenshot

in temp folder

3.  Create a file in required location (Hard disk)

4.  Copy from temp folder to  hard disk

By: Harish Korgal  Page | 54


 

 
Script:

public
public 
 class Sample
class Sample
{
public
public  static 
static  void
void main(String[]
 main(String[] args
args)
) throws
throws 
  InterruptedException,
IOException
{
String key
key=="webdriver.gecko.driver" ;
String value=
value="./softwares/geckodriver.exe"
"./softwares/geckodriver.exe";
;
System.setProperty(key,
key,value);
value);

driver =
WebDriver driver  = new
new 
 FirefoxDriver();
FirefoxDriver();
driver .get("https://www.amazon.in/"
driver.get( "https://www.amazon.in/" );

//step1 
//step1 
TakesScreenshot ts =
ts = (TakesScreenshot)
(TakesScreenshot) driver;
driver;

//step2
//step2 
 
File src =
src = ts
ts.getScreenshotAs(OutputType.
.getScreenshotAs(OutputType. FILE);

//step3 
//step3 
File dst =
dst = new
new File(
 File("D:\\login.png"
"D:\\login.png");
);

//step4 
//step4 
FileUtils.copyFile (src,
src,dst);
dst);
}
}

 Synchronization:

The process of matching selenium speed with application speed is called as

synchronization. It is classified into 2 types,

1.  Implicit wait

2.  Explicit wait

Implicit wait:

By using this we can synchronize only 2 methods

1.  findElement()

2.  findElements()

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

By: Harish Korgal  Page | 55


 

 
In the browser manage the time and implicitly wait for 10 seconds

This method takes 2 arguments

1.  Specified time

2.  Time unit (Ex for abstract enum)

Time unit
unit can be DAYS, HOURS, MINUTES, SECONDS… 
SECONDS… 

Script:
public
public 
 class Sample
class Sample
{
public
public  static 
static  void
void main(String[]
 main(String[] args
args)
) throws
throws 
  InterruptedException,
IOException
{
String key
key=="webdriver.gecko.driver" ;
String value=
value="./softwares/geckodriver.exe"
"./softwares/geckodriver.exe";;
System.setProperty(key,
key,value);
value);

WebDriver driver
driver =
 = new
new 
 FirefoxDriver();
FirefoxDriver();
driver.manage().timeouts().implicitlyWait(10,
driver .manage().timeouts().implicitlyWait(10, TimeUnit. SECONDS);
driver.get(
driver .get("https://www.amazon.in/"
"https://www.amazon.in/" );

driver .findElement(By. xpath("//a[.='SeleniumConf
driver.findElement(By. "//a[.='SeleniumConf 2016']"
2016']"));
));
}
}

1.  When the control comes to findElement(), it will verify whether element present or not

2.  If element is present findElement() will return the address of first element

3.  If element is not present then it will verify whether implicit wait is specified ornot

4.  If implicit wait is not specified then it will throw ‘NoSuchElementException’ or ‘Emply

list/array’ 
list/array’ 

5.  If implicit wait is specified then it will verify the specific time is over or not

6.  If the specific time it over then it will throw ‘NoSuchElementException’ or ‘Emply

list/array’ 
list/array’ 

7.  If implicit wait time is not over then it waits for 500ms (1/2) seconds 
seconds 

8.  Waiting for 500ms is called as Pooling period which is present in Fluent wait(Concrete

class) 
class) 

By: Harish Korgal  Page | 56


 

 
9.  And this process continues until,

a.  Finds the element OR


OR  

b.  Until specific time is over

Explicit wait:


  In order to synchronize all the methods including findElement() and findElements()
method we go for explicit wait statement

   In selenium explicit wait is represented by WebDriverWait


WebDriverWait class
 class

   In explicit wait we specify individual condition for individual methods


   In explicit wait if condition is not satisfied it will throw ‘TimeOutException’
‘TimeOutException’  

   In explicit wait by default time unit is SECONDS


SECONDS  

1.  In explicit wait it will verify whether condition is satisfied or not

2.  If condition is satisfied then it will go to next statement


3.  If condition is not satisfied then it will verify whether the specific time is over or not

4.  If time is over it will throw ‘TimeOutException’


‘TimeOutException’  

5.  If time is not over then it will wait for 500ms (1/2) second

6.  Waiting for 500ms is called as Pooling period which is present in Fluent wait(Concrete

class) 
class) 

7.  And this process continues until,

a.  Finds the element OR


OR  

b.  Until specific time is over

Implicit wait Explicit wait

1.  Supports for findElement() and 1.  Supports for all the methods including

findElements() findElement() and findElements()

2.  Time unit can be set to min, sec, days 2.  Time unit always seconds

3.  We don’t specify the conditions 3.  We specify condition for individual

method

4.  If time is over it will throw 4.  It will throw ‘TimeOutException’ 


‘TimeOutException’ 

By: Harish Korgal  Page | 57


 

 
‘NoSuchElementException’
‘NoSuchElementException’ or empty

list/ array

Explicit wait Thread.sleep()

1.  We specify the condition 1.  We don’t specify the condition 


condition 
2.  It will throw ‘TimeOutException’ 
‘TimeOutException’  2.  It will throw ‘InterruptedException’
‘InterruptedException’  

3.  Selenium exception 3.  Java exception

4.  Run time exception 4.  Compile time exception

5.  Time unit is seconds 5.  Time unit is milli seconds

6.  If page found it will go for next page 6.  It waits for specified duration then it

will go for next page

 Test NG:

  Test NG is a unit testing framework


  Test NG is basically used by developers in order to perform white box testing or unit
testing

  In selenium we use Test NG because,


1.  To run multiple scripts

2.  To generate reports/result

3.  To perform verification

4.  To achieve parallel execution (executing in multiple browsers)

Steps to download Test NG:

1.  In Eclipse  Help  Eclipse market place

2.  Search for Test NG

3.  Click on Install

By: Harish Korgal  Page | 58


 

 
Steps to attach Test NG to the project 
project  

1.  Right click on Project folder  Build path  Add libraries

2.  Select Test NG  Next  Finish

Rules for developing Test NG class:

1.  Create user defined package, never go for default package


2.  Never use main()
main() method
 method for execution. Use test method annotation @Test
@Test  

3.  To print the message we use Reporter.log()


Reporter.log()  

Note: 
Note: 

1.  JVM will search for either main() method or @Test

2.  In a single class we can have multiple @Test, but we cannot have multiple main()

method

3.  By using Reporter.log() we can print message in both report and console

Test NG class:

  It is a Java class which consist of Test method annotation @Test


@Test  

  Test method –  any method developed by using @Test


method – any @Test is
 is called test method annotation

import org.testng.Reporter;
import org.testng.Reporter;
import
import 
 org.testng.annotations.Te
org.testng.annotations.Test;
st;

public 
public class Sample
class Sample
{
@Test
@Test 
 
public 
public  void test1()
void test1()
{
"1",
Reporter.log("1", true
true);
);
}

//create in another file


import org.testng.Reporter;
import org.testng.Reporter;
import
import 
 org.testng.annotations.Te
org.testng.annotations.Test;
st;

public class Sample2
public  class Sample2
{
@Test 
@Test  
public 
public  void test2()
void test2()
{

By: Harish Korgal  Page | 59


 

 
Reporter.log("2"
"2",
, true
true);
);
}

  To run multiple scripts and


scripts and to generate reports we use Test NG

  Test NG we generate testng.xml file



  testing.xml file consist of multiple classes

Steps to generate testng.xml file 


file  

1.  Right click on project  click on Test NG

2.  Convert to Test NG  Finish

Contents of testng.xml file 


file  
<suite name="Suite">

<test thread-count="5" name="Test">


<classes>
<class name="popup.Sample"/>
name="popup.Sample"/>
<class name="popup.Sample2"/>
name="popup.Sample2"/>
</classes>
</test>
</suite>

Steps to run testng.xml file

1.  Right click on testng.xml


testng.xml file
 file
2.  Run as  click on Test NG suite 
suite 

Steps to generate reports

1.  Once after execution Refresh


Refresh the
 the project, it will generate folder called test outuput 
outuput 

2.  Expand folder  Right click on ‘emailable report.html’   open with web browser
‘emailable--report.html’

Steps to export report to excel sheet 


sheet 

Right click on report  click on ‘Export to Excel’ 

By: Harish Korgal  Page | 60


 

 
Interview questions 
  Priority for Test methods

import org.testng.Reporter;
org.testng.Reporter;
import org.testng.annotations.Test;
org.testng.annotations.Test;

class Sample

{
(priority=1))
@Test (priority=1
public void test1()
{
Reporter.log("1", true);
}
}

class Sample2
{
@Test //default priority=0
public void test2()

{
Reporter.log("2", true);
}
}
Output:: 2 1
Output

By default priority=0, if the priority is same it will execute based on alphabetical order of
method name

  How to execute same test cases multiple times?


By using parameter called invocation count 


count 

import org.testng.Reporter;
org.testng.Reporter;
import org.testng.annotations.Test;
org.testng.annotations.Test;

class Sample
{
@Test (invocationCount=2,
(invocationCount=2, priority= -4)
public void test1()
{
Reporter.log("1", true);
}
}

class Sample2
{

By: Harish Korgal  Page | 61


 

 
@Test(priority= -8)
public void test2()
{
Reporter.log("2", true);
}
}
Output:
2
1
1

  By default invocationCount=1
  If we specify invocation count < =0 then it will skip the test case

  How to skip the Test cases without using invocation count 


count  

( enabled=false))
We using @Test (enabled=false //by default enabled = true
true  

  Important annotation of Test NG


1.  @BeforeSuite

2.  @BeforeTest

3.  @BeforeClass

4.  @BeforeMethod

5.  @Test
@Test  

6.  @AfterMehtod

7.  @AfterClass

8.  @AfterTest

9.  @AfterSuite

10. @Parameters (Used for parallel


parallel execution)

11. @FindBy (used in POM)

12. @DataProvider

1.  @BeforeSuite

In order to verify the server issue before executing the frame work (pre condition)

2.  @BeforeTest

In order to connect JDBC/to retrieve data from data base (Test data)

By: Harish Korgal  Page | 62


 

 
3.  @BeforeClass

In order to open the application in each and every script

4.  @BeforeMethod

We can use for opening application / login into application

5.  @Test

To perform action on the application


6.  @AfterMethod

We can use for closing application / logout to application

7.  @AfterClass

application 
To close the application 

8.  @AfterSuite

To verify whether reports are generated or not

Script: 
package inbox;
package inbox;  
public 
public class Generic
class Generic
{
@BeforeSuite
@BeforeSuite   
public
public  void 
void beforeSuite()
beforeSuite()
{
"BeforeSuite",
Reporter.log("BeforeSuite" true);
,true);
}

@BeforeTest 
@BeforeTest 
public
public  void beforeTest()
void beforeTest()
{
"BeforeTest",
Reporter.log("BeforeTest" ,true
true);
);
}

@BeforeClass
@BeforeClass   
public
public  void 
void beforeClass()
beforeClass()
{
Reporter.log("BeforeClass"
"BeforeClass",
,true);
true);
}

@BeforeMethod 
@BeforeMethod 
public 
public void 
void beforeMethod()
beforeMethod()
{
Reporter.log("BeforeMethod"
"BeforeMethod",
,true);
true);
}

By: Harish Korgal  Page | 63


 

 
@AfterMethod
@AfterMethod   
public 
public  void 
void afterMethod()
afterMethod()
{
Reporter.log("AfterMethod"
"AfterMethod",
, true);
true);
}

@AfterClass 
@AfterClass  
public
public  void afterClass()
void afterClass()
{
Reporter.log("AfterClass"
"AfterClass",,true
true);
);
}

@AfterTest 
@AfterTest  
public 
public  void afterTest()
void afterTest()
{
Reporter.log("AfterTest"
"AfterTest",
,true
true);
);
}

@AfterSuite
@AfterSuite  
public
public  void afterSuite()
void afterSuite()
{
"AfterSuite",
Reporter.log("AfterSuite" ,true
true);
);
}

package inbox; 
package inbox;
public
public 
 class Demo2
class Demo2 extends
extends Generic
 Generic
{
@Test 
@Test  
public 
public  void test2()
void test2()
{
Reporter.log("2"
"2",
,true
true);
);
}

Output:
BeforeSuite
BeforeTest
BeforeClass
BeforeMethod
2
AfterMethod
AfterClass
AfterTest

PASSED: test2

By: Harish Korgal  Page | 64


 

=====================================
===============================================
==========
Default test
Tests run: 1, Failures: 0, Skips: 0
=========================
=====================================
======================
==========

AfterSuite

=====================================
===============================================
==========
Default suite
Total tests run: 1, Failures: 0, Skips: 0
=========================
=====================================
======================
==========

package inbox; 
package inbox;
public
public 
 class Demo1
class Demo1 extends
extends Generic
 Generic
{
@Test
@Test  
public
public   void test1()
void test1()
{
"1",
Reporter.log("1" ,true
true);
);
}

@Test
@Test 
 
public 
public  void test2()
void test2()
{
"2",
Reporter.log("2",true
true);
);
}
}
Output:
BeforeSuite 
BeforeTest
BeforeClass

BeforeMethod
1
AfterMethod
BeforeMethod
2
AfterMethod
AfterClass
AfterTest
PASSED: test1

PASSED: test2

By: Harish Korgal  Page | 65


 

 
=========================
=====================================
======================
==========
Default test
Tests run: 2, Failures: 0, Skips: 0
===========================
=======================================
====================
========

AfterSuite

=====================================
===============================================
==========
Default suite
Total tests run: 2, Failures: 0, Skips: 0
=========================
=====================================
======================
==========

 Verification

  In order to perform verification we use Test NG


  In TestNG we use Assert
Assert class
 class

  In Assert class we use assertEquals()


assertEquals() method
 method

  Assert class methods are static methods


  assertEquals() methods take 2 arguments (Actual,
( Actual, Expected)
Expected)

If Actual and Expected results are same, then it will perform


p erform the following actions

1.  Pass the test case

2.  Continues execution

3.  Not throw exception

4.  Display in Green color (Results)

If Actual and Expected results are not


n ot same, then it will perform the following actions

1.  Fail the test case


2.  Stops execution

3.  Throw exception (Assertion error)

4.  Diplay in Red color (Reports)

By: Harish Korgal  Page | 66


 

 
public
public 
 class Generic
class Generic
{
public
public WebDriver
 WebDriver driver;
driver ; //global declaration 
declaration 

@BeforeMethod 
@BeforeMethod  
public 
public void openApp()
void openApp()
{

System.setProperty("webdriver.gecko.driver" ,"./softwares/geckodriver.ex
e");
e" );
driver =
driver  = new
new 
 FirefoxDriver();
FirefoxDriver();
driver.get(
driver .get("http://localhost/login.do"
"http://localhost/login.do");
);
}

@AfterMethod
@AfterMethod   
public 
public  void closeApp()
void closeApp()
{
driver .quit();
driver.quit();
}

public 
public class Login
class Login extends
extends Generic
 Generic
{
@Test
@Test  
public
public   void testLogin()
void testLogin() throws
throws   InterruptedException
InterruptedException
{
driver .findElement(By. id ("username")).sendKeys(
driver.findElement(By. "username")).sendKeys("admin"
"admin");
);
driver.findElement(By.
driver .findElement(By. name("pwd")).sendKeys(
"pwd")).sendKeys("manager"
"manager");
);
driver.findElement(By.
driver .findElement(By. xpath("//div[.='Login
"//div[.='Login ']"
']")).click();
)).click();

Thread.sleep(3000);

String title =
title = driver.getTitle();
driver .getTitle();
System.out.println(
.println(title
title);
);

title,
Assert.assertEquals(title,"actiTIME - Enter Time-Track"
Time-Track");
);
System.out.println(
.println("1"
"1");
);
}

Output:
actiTIME - Enter Time-Track
1
PASSED: testLogin

=====================================
===============================================
==========
Default test
Tests run: 1, Failures: 0, Skips: 0
=========================
=====================================
======================
==========

By: Harish Korgal  Page | 67


 

=====================================
===============================================
==========
Default suite
Total tests run: 1, Failures: 0, Skips: 0
=========================
=============================================== 
======================

  List of methods in Assert class


1.  Assert.assertEquals(actual, expected);


2.  Assert.assertN
Assert.assertNotEquals(actu
otEquals(actual,
al, expected);

3.  Assert.assertTrue(condition);

4.  Assert.assertFalse(condition);

5.  Assert.fail();

  Soft Assert
Even though if comparison gets failed, in order to continue the execution we use soft assert

In soft assert comparison gets fail, it will perform below

1.  It will fail the test case

2.  It will throw exception

3.  It will continue exception

4.  Reports displayed in Red color

In soft assert, by default we should call assertAll() method at the last


last  
public
public 
 class SoftAssert
class SoftAssert extends Generic
extends Generic
{
@Test 
@Test 
public
public  void 
void softAssert() throws 
throws  InterruptedException
InterruptedException
{
driver.findElement(By.
driver .findElement(By. id ("username")).sendKeys(
"username")).sendKeys("admin"
"admin");
);
driver .findElement(By. name("pwd")).sendKeys(
driver.findElement(By. "pwd")).sendKeys("manager"
"manager");
);
driver
driver.findElement(By.
.findElement(By. xpath("//div[.='Login
"//div[.='Login ']"
']")).click();
)).click();

Thread.sleep(3000);

String title =
title = driver.getTitle();
driver .getTitle();
System.out.println(
.println(title
title);
);

SoftAssert sa
sa =
 = new SoftAssert();
new SoftAssert();

By: Harish Korgal  Page | 68


 

 
sa.assertEquals(title
sa.assertEquals(title,,"actiTIME - Enter Time-Track"
Time-Track");
); //
//(a)
(a) 
 
System.out.println(
.println("1"
"1");
);
sa.assertAll();
sa.assertAll();
System.out.println(
.println("2"
"2");
);
}

Output:

  If (a)
(a) is
 is pass
pass  then S.o.p(“1”) and S.o.p(“2”) will display
display  

  If (a)
(a) is
 is fail
fail  then S.o.p(“1”) 
S.o.p(“1”) 

  assertAll()
assertAll() should
 should always be at last

  If (a)
(a) is
 is fail,
fail, all
 all the status after assertAll() will not be executed

Assert SoftAssert

1.  All are static method 1.  All are non-static methods

2.  If comparision gets failed it will stop 2.  If comparision gets fail it will continue

exection exection

3.  We don’t call assetAll() 


assetAll()  3.  We call assertAll() at last by default

TestNG Junit

1.  We can generate report 1.  We cannot generate report

2.  We can achieve parallel exection 2.  We cannot achieve parallel exection

 Data Driven Testing


1.  Testing the application for multiple test data is called as data driven testing

2.  In order to store the data we use Excel files

3.  Excel file is also called as work book 


book 

4.  Excel file is a stand alone application


alone application
5.  In order to retrieve data from excel file, we use Apache POI (third
POI (third party/supporting file)

By: Harish Korgal  Page | 69


 

 
6.  Apache POI is used to read the data from excel

7.  Apache POI consist of 13 jar files

   Apache POI can be downloaded from below website


1.  Navigate to  https://poi.apache.org/download.html 

download  poi-bin-3.17-20170915.zip  (consists of 13 jar


2.  Binary Distrubution section download
files) 

3.  Create a folder ‘Apache


‘Apache POI’ in
POI’ in project and copy paste 13 jar files and add to ‘Build

path’ 
path’ 

4.  Create a folder ‘Excel’


‘Excel’ and
 and create data.xlsx
data.xlsx (excel)
 (excel) file in the respective path of that

particular folder (in ‘D’ or ‘E’ driver) 


driver)  

   Steps to read the data from excel file

file  
1.  Specify the path of the file 
2.  Open the excel file 
file 

3.  Go to sheet by specifying sheet name 


name  

4.  Go to row (starts from 0) 


0)  

5.  Go to column/cell (starts from 0) 


0)  

6.  Retrieve the data from the cell 


cell  

public class Excel
public class Excel

{
public 
public  static 
static  void
void main(String[]
 main(String[] args
args)
) throws
throws 
 
EncryptedDocumentExceptio
EncryptedDocumentException,
n, InvalidFormatException
InvalidFormatException,
, IOException
{
fs =
FileInputStream fs = new
new 
 FileInputStream(
FileInputStream("./Excel/data.xlsx"
"./Excel/data.xlsx");
);
//step 1
Workbook wb
wb =
 = WorkbookFactory.
WorkbookFactory.create(fs);
fs); //step 2 

sh =
Sheet sh = wb
wb.getSheet(
.getSheet("Sheet1"
"Sheet1");
); //step 3 

int
int 
 row =
row = sh.getLastRowNum();
sh.getLastRowNum(); //step 4 

System.out.println(
.println(row
row);
); //step 5 

Row r = sh.getRow(0);
sh.getRow(0); //step 6 

By: Harish Korgal  Page | 70


 

 
Cell c = r.getCell(1);
String v = c.getStringCellValue();
System.out.println(
.println(v
v);
}
}

Note:
1.  Row position starts
starts from
from 0

2.  Cell position starts form 0

3.  Row count starts from 0

4.  Cell count starts from 1 

5.  If we try to read the data from empty cell it throw ‘NullPointerException’
‘NullPointerException’  

6.  If we try to retrieve numeric value from the cell it throw ‘IllegalStateException’
‘IllegalStateException’  

7.  To convert numeric to string we use single quote ( ‘ ) at


)  at left side of number

WAS to count number of rows in a sheet

0 1 2
0 123
1 456
2 789
3 101
4
5

Total data = 4
Row count = 4-1 =3
=3  

  Consider only data cell not empty cell

{
sh =
Sheet sh = wb
wb.getSheet(
.getSheet("Sheet1"
"Sheet1");
);
int 
int count =
count = sh.getLastRowNum();
sh.getLastRowNum();
System.out.println(
.println(count
count);
);
}
Output: 3

By: Harish Korgal  Page | 71


 

 
10 rows 15 cells 100 rows 100 cells

5 rows(data) 9 cells(data) 100 cells(data) 100 cells (data)

O/p: 4 (5-1) O/p: 9 (9-0) O/p: 99 (100-1) O/p: 100 (100-0)

 ‘StaleElementRefere
‘StaleElementReference’
nce’ exception

public 
public class Demo
class Demo
{
public 
public  static 
static  void
void main(String[]
 main(String[] args
args)
) throws
throws 
 Interrupted
InterruptedException
Exception
{

System.setProperty("webdriver.gecko.driver"
"webdriver.gecko.driver",
,"./softwares/geckodriver.exe"
"./softwares/geckodriver.exe");
);
driver =
WebDriver driver  = new
new 
 FirefoxDriver();
FirefoxDriver();
driver.get(
driver .get("http://localhost/login.do"
"http://localhost/login.do");
);

driver .findElement(By. id ("username")).sendKeys(


driver.findElement(By. "username")).sendKeys("admin"
"admin");
);
driver.findElement(By.
driver .findElement(By. name("pwd")).sendKeys(
"pwd")).sendKeys("manager"
"manager");
);
WebElement ele
ele =
 = driver.findElement(By.
driver .findElement(By. xpath("[.='Login ']"
']"));
));

ele.click();
ele.click(); //pass 
//pass 

Thread.sleep(3000);
driver.navigate().refresh();
driver .navigate().refresh(); //pass
//pass  

Thread.sleep(3000);
ele.click();
ele.click(); //thorws 'StaleElement
'StaleElementReferenceExc
ReferenceException'
eption' 
 
}
}

  In the above script after refreshing page, address of the element


e lement will change

  If you perform click operation it will throw ‘StaleElementReferenceException’


‘StaleElementReferenceException’  

  Stale
o Stale –
 – Old
 Old (or) expired

  Reference
o Reference –
 – address
 address (i.e. address is expired

  To handle 
handle ‘StaleElementReferenceException’ we go for POM
for POM (Page Object Model) 
Model)  

By: Harish Korgal  Page | 72


 

 
  POM
  POM
POM –
 – Page
 Page Object Model

  POM is a java design pattern whichis mainely used to handle ‘StaleElementReference


Exception’  
Exception’

  POM consists of 3 stages


1.  Declaration

2.  Initilization

3.  Utilization

  Declaration:
 Declaration:  

In POM we declare elemet by using @findBy annotation

Syntax: @findBy(LocatorName
@findBy(LocatorName = “LocatorValue”) 
“LocatorValue”) 

private Webelement/List of webelements VariableName/Element


VariableName/ElementName
Name

Example: <a id = “a1”> Login </a> 


</a> 

@findBy (id = “a1”)


“a1”)  

private WebElement loginBtn;

  Initilization:
 Initilization:  

1.  In POM we use constructor for initilizing elements

2.  In constructor we use ‘PageFactory’


‘PageFactory’ class
 class

3.  In ‘PageFactory’ class we use ‘initElements()’


‘ initElements()’ method
 method

4.  ‘initElements()’ takes 2 arguments 


arguments 

a.  driver
driver –
 – Application
 Application control (OR) object of WebDriver

b.  this
this –
 – current
 current object (OR) current page

public
public PomLogin
 PomLogin (WebDriver driver)
driver)
{
PageFactory.initElements(driver,
driver,this);
this);
}

By: Harish Korgal  Page | 73


 

 
  Utilization:
 Utilization:  

In POM we utilize the elements by developing methods


public
public  void clickLogin()
void clickLogin()
{
loginBtn.click();
loginBtn.click();
}

Login script for ActiTime application

POM class for login page 


page  
public
public 
 class PomLogin
class PomLogin
{
//Declaration
//Declaration  
@FindBy(id=
@FindBy(id="username"
"username")
)
private WebElement
private WebElement unBox;
unBox;

@FindBy(name=
@FindBy(name="pwd"
"pwd")
)
private WebElement pwdBox;
private WebElement pwdBox;

@FindBy
@FindBy(xpath=
(xpath="//div[.='L
"//div[.='Login
private WebElement
private WebElement ogin ']"
']")
loginBtn;
loginBtn;)

//Initilization
//Initilization  
public PomLogin
public  PomLogin (WebDriver driver)
driver)
{
PageFactory.initElements(driver,
driver,this);
this);
}

//utilization
//utilization   
public 
public void 
void  setUserName(String un)
un)
{
unBox.sendKeys(un
unBox.sendKeys( un);
);
}

public 
public  void 
void  setPassword(String pwd)
pwd)
{
pwdBox .sendKeys(pwd
pwdBox.sendKeys( pwd);
);
}

public 
public  void clickLogin()
void clickLogin()
{
loginBtn.click();
loginBtn.click();
}
}

Test case for Login page 


page  
public 
public class Demo
class Demo

By: Harish Korgal  Page | 74


 

 
{
public
public  static 
static  void
void main(String[]
 main(String[] args
args)
)
{

System.setProperty("webdriver.gecko.driver" ,"./softwares/geckodriver.ex
e");
e" );
WebDriver driver
driver =
 = new
new 
 FirefoxDriver();
FirefoxDriver();
driver.get(
driver .get("http://localhost/login.do"
"http://localhost/login.do");
);

PomLogin pl =
pl = new
new PomLogin(
 PomLogin(driver
driver);
);
pl.setUserName(
pl.setUserName("admin"
"admin");
);
pl.setPassword("manager"
pl.setPassword("manager");
);
pl.clickLogin();
pl.clickLogin();
}
}

Interview Question

1.  What is POM


It is a java design pattern which is mainly used to handle ‘StaleElementReference

Exception’

2.  Advantages of POM

a.  To handle ‘StaleElementReference Exception’ 


Exception’ 

b.  To achieve encapsulation / to encapsulate by gets() and sets()

c.  To store elements

d.  POM is also called as Object Reprository

3.  How to handle elements in POM


- @findBy annotation

4.  How to intialize element in POM

- in constructor by using PageFactory.initEleme


PageFactory.initElements(driver,
nts(driver, this);
this);  

5.  What happens if we do not intilize elements

- NullPointerException
NullPointerException

6.  How to handle multiple elements

@findBy (//a)

private <list of WebElements> links;

By: Harish Korgal  Page | 75


 

 
FRAMEWORK
Framework is a set of procedure / guideliness / rules / protocol followed while

automating the application.

In order to have consistency we use framework.


fra mework.

Framework consist of 3 stages

1.  Design (Automation lead / manager)

2.  Implimentation (Sn/Jn Automation engineer)

3.  Exection (Jn Automation engineer/ fresher)

  Framework Design:

  In this stage either Automation lead/ manager is involved 


involved  

  They will develop standard files and folder structure and also generic libraries (methods)
required for framework

Steps to configure the design

1.  Create a folder


folder in
 in respective drive and specify the folder name as Domain name

(Banking, helathcare, transport)

2.  Create a project


project inside
 inside the workspace and specify project name as application name

(Actitime, gmail, facebook)

3.  Create a folder ‘jars’


‘jars’  and copy paste ‘Selenium Stand alone jar’ files (3.4.4 and 2.5.3.1)

 jar file and attach jar


jar files to build path

4.  Create a folder drivers


drivers and
 and copy paste driver executable files (geckdriver.exe and

chromedriver.exe)

5.  Create a folder Apache POI and


POI and copy paste 13 jar files
f iles and attach all to build path

6.  Create a folder Excel


folder Excel and create one excel sheet inside the folder

7.  In order to run multiple scripts and to genrate reports attach TestNG
TestNG to
 to the project

8.  Create 3 packages inside


packages inside the project

a.  Generic (Design)

b.  POM (Implementation)

c.  Scripts (Execution)

By: Harish Korgal  Page | 76


 

 
Initial structure of folder structure of framework

Using interface in the framework

  In our framework/ project we have set of constants such as key, value and path of excel
file etc… 
etc… 

  In our framework we store constants inside


insi de interface

  In inteface if we declare any variables by default it is public, static and final variable


final variable  

  Create a interface with name ‘Automation_CONST’ inside generic package 


package 

package generic;
package generic;

public 
public interface 
interface Automation_CONST
Automation_CONST
{
String key = "webdriver.gecko.driver" ;
String value = "./drivers/geckodriver.exe"
"./drivers/geckodriver.exe";
;

String PATH ="./Excel/data.xlsx" ;

Using inheritance in the framework

1.  For each and every test case we develop Test


T est class

By: Harish Korgal  Page | 77


 

 
2.  In each and every test class we perform common actions such as (open application and

close application)

3.  In order to avoid the repetition of code we develop generic method for (open

application and close application)

4.  In order to access the generic method we use Inheritance

5.  Instead of creating an object we use annotation


6.  Create a class with the name ‘Base_TEST’
‘Base_TEST’ inside
 inside generic package

package generic;
package generic;

public 
public class Base_TEST
class Base_TEST implements 
implements  Automation_CONST
Automation_CONST
{
public
public WebDriver
 WebDriver driver;
driver ;

@BeforeMethod 
@BeforeMethod  
public 
public void 
void openApplication()
openApplication()
{
System.setProperty(key, value);
driver
driver==new
new 
 FirefoxDriver();
FirefoxDriver();
driver.get(
driver .get("http://localhost/login.do"
"http://localhost/login.do");
);
}

@AfterMethod
@AfterMethod   
public
public  void 
void closeApplication()
closeApplication()
{
driver.quit();
driver .quit();
}

1.
1.  Auto_CONST (I)  2. Auto_CONST (I)  3. Base_TEST (C) 

Key, value Key, value @BM (Open App)


Path of excel Path of excel @AM (Close App)

Base_TEST (C) 

@BM (Open App) @Test @Test @Test


@AM (Close App)

(for all 3 @Test method below is the input)


Output: @BeforeMethod
@Test
@AfterMethod

By: Harish Korgal  Page | 78


 

Using Excel file in the framework 


framework  

1.  In order to test the application with the multiple data is called as data driven testing

2.  In order to store the data we use excel file

3.  In order to read the data from excel we use Apache POI files
POI files

 
4. We develop generic method to read the data from excel file
5.  Create a class ‘Excel’
‘Excel’ in
 in generic package

package generic; 
package generic;
public
public  class Excel
class Excel
{
public 
public  static String
static  String getCellValue(String PATH,
PATH, String sheet
sheet,
, int 
int row,
row,
int 
int  cell)
cell) throws
throws  EncryptedDocumentExcept
EncryptedDocumentException,
ion, InvalidFormatException,
InvalidFormatException,
IOException
{
String v="""";
;
try 
try 
{
FileInputStream fis =
fis = new FileInputStream(
new FileInputStream(PATH
PATH);
);
Workbook wb =
wb = WorkbookFactory.
WorkbookFactory.create (fis);
fis);
Cell c = wb.getSheet(
wb.getSheet(sheet
sheet).getRow(
).getRow(row
row).getCell(
).getCell(cell
cell);
);
v=c.getStringCellValue();
}
catch(Exception
catch(Exception e)
{

}
return  v;
return 
}

Using abstract class in the framework: 


framework:  

1.  For each and every page we develop POM class

2.  In each and every POM class we perform common action such as (verification of title

and verification of element etc…) 


etc…) 

3.  In order to avoid repetation of code we develop generic methods in the generic class

4.  In order to access the generic methods we use inheritance


inheritance  

5.  Since this class only for inhertiance purpose, not for execution we declare class as

abstract  
abstract

By: Harish Korgal  Page | 79


 

 
6.  Create a class ‘Base_PAGE’
‘Base_PAGE’ inside
 inside generic package

 generic; 
package generic;
package
public
public 
 abstract 
abstract class Base_PAGE
class Base_PAGE
{
public WebDriver
public WebDriver driver;
driver ;
public
public  Base_PAGE(WebDriver
Base_PAGE(WebDriver driver)
driver)
{
this.driver=
this. driver =driver;
driver;
}

public 
public  void 
void  verifyTitle(String title)
title)
{
WebDriverWait wait
wait =
 = new
new 
 WebDriverWait(
WebDriverWait(driver
driver,10);
,10);
try
try  
{
wait.until(ExpectedConditions.
wait.until(ExpectedConditions.titleContains(title
title));
));
Reporter.log("title is matching",
matching",true);
true);
}
catch (Exception e)
catch (Exception
{
Reporter.log("title is not matching",
matching" ,true);
true);
Assert. fail();
}
}

public
public  void 
void verifyElement(WebElemen
verifyElement(WebElementt element)
element)
{
WebDriverWait wait
wait =
 = new
new 
 WebDriverWait(
WebDriverWait(driver
driver,10);
,10);
try 
try  
{
wait.until(ExpectedConditions.visibilityOf (element
wait.until(ExpectedConditions. element));
));
Reporter.log("element is present",
present",true);
true);
}
catch (Exception e)
catch (Exception
{
Reporter.log("element is not present",
present",true
true);
);
Assert. fail();
}
}

  Framework Implementation:

  Converting manual test cases to Automation scripts with the help of framework design

(generic methods/libraries ) 

  In this stage either Senior /Junior Automation engineer will be involved

By: Harish Korgal  Page | 80


 

 
   In this stage they will develo POM classes for individual
for individual webpage.
 webpage.  

Test cases for Automation

Script 1: Valid login and logout

Step1: Enter valid user name

Step2: Enter valid password


Step3: Click on Login button

Step4: Verify home page is displayed or not

Step5: Click on Logout

Step6: Verify login page is displayed or not

Script2 : Invalid login

Step1: Enter invalid user name

Step2: Enter invalid password


Step3: Click on Login button

Step4: Verify Error message is displayed

Script3 : Verify ActiTime


ActiTime version

Step1: Enter valid user name

Step2: Enter valid password

Step3: Click on Login button

Step4: Verify home page is displayed or not


Step5: click on help button

Step6: click on
on ‘About ActiTime’ 
ActiTime’ 

Step7: Verify ActiTime version

Step8: Click on close button

Step9: Click on Logout

Step10: Verify login page is displayed or not

By: Harish Korgal  Page | 81


 

 
Elements required for POM class

Login page Home page

1.  User name 1.  Logout

2.  Password 2.  Help

3.  Login 3.  About actitime

4.  Error message 4.  Actitime version


5.  Close popup

Rules for developing POM class

1.  POM class depends on number of web pages 


pages  

2.  For each and every webpage we develop POM class

3.  POM class name should


name should be same as title of the web page 
page 

4.  POM class name should ends with keyword called ‘page’
‘page’  

5.  Each and every POM class shold extends from ‘Base_PAGE’ class
6.  POM class should be develop inside ‘POM’ package

POM class for login page 


page  
package pom; 
package pom;
public
public 
 class LoginPage
class LoginPage extends Base_PAGE
extends Base_PAGE
{
//declarations

@FindBy(id=
@FindBy(id="username"
"username")
)
private
private WebElement
 WebElement untbox;
untbox;
@FindBy(name=
@FindBy(name="pwd"
"pwd")
)
private WebElement
private WebElement pwdtbox;
pwdtbox;

@FindBy(xpath=
@FindBy(xpath="//div[.='L
"//div[.='Login
ogin ']"
']"))
private WebElement
private WebElement loginbtn;
loginbtn;

@FindBy
@FindBy(xpath=
(xpath="//span[contains(.,'invalid')]"
"//span[contains(.,'invalid')]")
)
private
private WebElement
 WebElement errormsg;
errormsg;

//initilization

public LoginPage(WebDriver
public  LoginPage(WebDriver driver)
driver)
{
super(driver
super( driver);
); //to achieve constructor chaining 
chaining 

By: Harish Korgal  Page | 82


 

 
PageFactory.initElements(driver
driver,
,this);
this);
}

//utilization

public void 
public  void  setUserName(String un)
un)
{
untbox.sendKeys(
untbox .sendKeys(un
un);
);

}
public
public  void 
void  setPassword(String pwd)
pwd)
{
pwdtbox.sendKeys(pwd
pwdtbox.sendKeys( pwd);
);
}

public 
public void clickLogin()
void clickLogin()
{
loginbtn.click();
loginbtn.click();
}

public 
public  void 
void verifyErrorMsg()
verifyErrorMsg()
{
verifyElement(errormsg);
verifyElement(errormsg);
}

public 
public void 
void verifyLoginPage(String
verifyLoginPage(String lp_title)
lp_title )
{
verifyTitle(lp_title
verifyTitle( lp_title);
);
}

POM class for home page 


page  
package pom;
package pom;

public
public 
 class 
class EnterTimeTrackPage
EnterTimeTrackPage extends Base_PAGE
extends Base_PAGE
{
//declarations

@FindBy (id="logoutLink"
@FindBy (id= "logoutLink")
)
private
private WebElement
 WebElement logout;
logout;

@FindBy (xpath=
@FindBy (xpath="((//div[@cl
"((//div[@class='popup_me
ass='popup_menu_arrow'])[
nu_arrow'])[3]"
3]"))
private WebElement
private WebElement help;
help;

@FindBy
@FindBy (xpath=
 (xpath="//a[.='Abou
"//a[.='About
t actiTIME']"
actiTIME']")
)
private WebElement
private WebElement aboutActiTime;
aboutActiTime;

@FindBy (xpath=
@FindBy (xpath="//span[.='a
"//span[.='actiTIME
ctiTIME 2014 Pro']"
Pro']"))
private WebElement
private WebElement version;
version;

By: Harish Korgal  Page | 83


 

 
@FindBy
@FindBy (xpath=
 (xpath="//img[@title='Close']"
"//img[@title='Close']")
)
private WebElement
private WebElement closePopup;
closePopup;

//initilization

public EnterTimeTrackPage(WebD
public  EnterTimeTrackPage(WebDriver
river driver)
driver)
{
super(driver
super( driver);
); //constructo
//constructor
r chaining
chaining 
 

} PageFactory.initElements(driver
driver,
,this);
this);

//utilization

public void logout()
public  void logout()
{
logout.click();
logout .click();
}

public
public  void clickHelp()
void clickHelp()
{
help.click();
help.click();
}

public
public  void 
void clickAboutActiTime()
clickAboutActiTime()
{
aboutActiTime.click();
aboutActiTime.click();
}

public void clickClose()
public  void clickClose()
{
closePopup.click();
closePopup.click();
}

public
public  void 
void verifyHomePage(String
verifyHomePage(String hp_title
hp_title)
)
{
hp_title);
verifyTitle(hp_title
verifyTitle( );
}

public void 
public  void  verifyActiTimeVersion(String eversion
eversion))
{
String aversion
aversion =
 = version
version.getText();
.getText();
Assert.assertEquals(aversion
aversion,
,eversion
eversion);
);
}

  Framework Execution:

1.  In this stage Jn. Automation engineer / fresher will be involved

2.  In this stage we will develop test classes

By: Harish Korgal  Page | 84


 

 
3.  Test cases depends on number of test cases

4.  For each and every test case we develop test classes

Rules for developing test class

1.  Test class depends on number of test cases 


cases 

class 
2.  For each and every test case we develop test class 
3.  Test class name should be same as test case name
n ame or test script name

4.  Test class should be developed inside ‘scripts


scripts’’ package

5.  Each and every test class extends from ‘Base_TEST’


‘Base_TEST’ class
 class

6.  In test class we call POM class method to perform action on the browser

Script 1: Valid login and logout


package scripts; 
package scripts;

public
public 
 class 
class ValidLoginLogout
ValidLoginLogout extends
extends Base_TEST
 Base_TEST
{
@Test 
@Test 
public 
public  void 
void testValidLoginLogout()
testValidLoginLogout() throws
throws  EncryptedDoc
EncryptedDocumentExcept
umentException,
ion,
InvalidFormatException,
InvalidForma tException, IOException
{
String un =
un = Excel.getCellValue (PATH ,"ValidLoginLogout"
"ValidLoginLogout",
, 1, 0);
pwd =
String pwd  = Excel.getCellValue (PATH ,"ValidLoginLogout"
"ValidLoginLogout",, 1, 1);
lp_title =
String lp_title  = Excel.getCellValue (PATH ,"ValidLoginLogout",
"ValidLoginLogout", 1, 2);
String hp_title
hp_title =
 = Excel.getCellValue (PATH ,"ValidLoginLogout",
"ValidLoginLogout", 1, 3);

LoginPage lp
lp =
 = new
new LoginPage(
 LoginPage(driver
driver);
);
lp.setUserName(
lp.setUserName(un
un);
);
lp.setPassword(pwd
lp.setPassword(pwd);
);
lp.clickLogin();
lp.clickLogin();

EnterTimeTrackPage ep =
ep = new 
new EnterTimeTrackPage(
EnterTimeTrackPage(driver
driver);
);
ep.verifyHomePage(
ep.verifyHomePage(hp_title
hp_title);
);
ep.logout();
ep.logout();
lp.verifyLoginPage(
lp.verifyLoginPage(lp_title
lp_title);
);
}
}

Script 2: Invalid login


package scripts;
package scripts;

public
public 
 class 
class InvalidLogin extends
extends Base_TEST
 Base_TEST
{

By: Harish Korgal  Page | 85


 

 
@Test
@Test 
 
public 
public  void 
void  testInvalidLogin() throws 
throws  EncryptedDocumentException,
InvalidFormatException,
InvalidFormatException, IOException
{
String un
un =
 = Excel.getCellValue (PATH ,"InvalidLogin",
"InvalidLogin", 1, 0);
String pwd =
pwd = Excel.getCellValue (PATH ,"InvalidLogin",
"InvalidLogin", 1, 1);

LoginPage lp =
lp = new
new LoginPage(
 LoginPage(driver
driver);
);

lp.setUserName(un
lp.setUserName(
lp
lp.setPassword(un);
);
.setPassword(pwd
pwd);
);
lp.clickLogin();
lp.clickLogin();
lp.verifyErrorMsg();
lp.verifyErrorMsg();
}

Script 3: Verify ActiTime version


package scripts;
package scripts;
public 
public class 
class VerifyVersion
VerifyVersion extends Base_TEST
extends Base_TEST
{
@Test 
@Test 
public 
public  void 
void testValidLoginLogout()
testValidLoginLogout() throws
throws   EncryptedDoc
EncryptedDocumentExcept
umentException,
ion,
InvalidFormatException,
InvalidForma tException, IOException
{
String un =
un = Excel.getCellValue (PATH ,"VerifyVersion",
"VerifyVersion", 1, 0);
String pwd =
pwd = Excel.getCellValue (PATH ,"VerifyVersion",
"VerifyVersion", 1, 1);
lp_title =
String lp_title  = Excel.getCellValue (PATH ,"VerifyVersion"
"VerifyVersion",
, 1, 2);
String hp_title
hp_title =
 = Excel.getCellValue (PATH ,"VerifyVersion"
"VerifyVersion",
, 1, 3);

LoginPage lp
lp =
 = new
new LoginPage(
 LoginPage(driver
driver);
);
lp.setUserName(
lp.setUserName(un
un);
);
lp.setPassword(
lp.setPassword(pwd
pwd);
);

lp.clickLogin();
lp.clickLogin();

EnterTimeTrackPage ep =
ep = new 
new EnterTimeTrackPage(
EnterTimeTrackPage(driver
driver);
);
ep.verifyHomePage(
ep.verifyHomePage(hp_title
hp_title);
);
ep.clickHelp();
ep.clickHelp();
ep.clickAboutActiTime();
ep.clickAboutActiTime();
ep.verifyActiTimeVersion(
ep.verifyActiTimeVersion("actiTIME
"actiTIME 2014 Pro");
Pro");
ep
ep.clickClose();
.clickClose();
ep.logout();
ep.logout();

lp.verifyLoginPage(
lp.verifyLoginPage(lp_title
lp_title);
);
}

By: Harish Korgal Page | 86


By: Harish Korgal  Page | 86

 

  In order to run multiple scripts we use TestNG


  In order to generate reports and perform verification we use TestNG
  In the framework we develop TestNG.xml
TestNG.xml file
 file


  To convert project to TestNG.xml (Right
TestNG.xml (Right click on project  TestNG Convert to TestNG
 Finish

o   Contents of TestNG.xml file


<suite name="Suite">
<test thread-count="5" name="Test">
<classes>
name="scripts.VerifyVersion"/>
<class name="scripts.VerifyVersion "/>
name="scripts.InvalidLogin"/>
<class name="scripts.InvalidLogin "/>
name="scripts.ValidLoginLogout"/>
<class name="scripts.ValidLoginLogout "/>
</classes>

</test>
</suite>
  To Run TestNG.xml file (Right
file (Right click on TestNG.xml  Run As  TestNG suite

  To genrate reports after proejct (Refresh the project  it will generate test-output
test-output  

folder

  Expand the folder  right click on Emalable report.html 


report.html open with  web browser

  Right click on reprot Export to excel

FRAMEWORK ARCHITECTURE

1.  In our project we use Hybrid Framework 


Framework 

2.  Hybrid framework is a combination of multiple frameworks such as POM, Data driven,

Method driven and TestNG

TestNG

1.  In order to run multiple scripts, genrate report and to perform verification we use

TestNG
By: Harish Korgal  Page | 87

 
2.  TestNG is a unit testing framework

POM

1.  In order to handle ‘StaleElementReferenceException’


‘StaleElementReferenceException’ and
 and to store the elements we go

for POM

2.  POM is also called as Object frmework 


frmework 

Data Driven Framework 


Framework 

In order to test the application with multiple test data from the excel and retreive data

with the help of Apache POI libraries


POI libraries is called as Data driven framework

Method Driven Framework

In order to avoid repetation of the code we develop individual methods for individual

components in POM class is called as Method Driven Framework

  In our framework we store the constants


constants in
 in interface
interface called
 called as Auto_CONST
Auto_CONST  

  Base_TEST
Base_TEST   class consists of 2 methods i.e. @BeforMethod   to open application

@AfterMethod  to close application


@AfterMethod 

  In Base_PAGE
Base_PAGE   class we develop generic methods such as verification of title and

verification of elements etc…


etc…  

  Each and every POM class should be extend


extend from
 from Base_PAGE
Base_PAGE class
 class

  During the run time, first it will execute @BeforMethod and it perform open browser
and enter the URL

  After executing @BeforeMethod, it will execute @Test method i.e. it will perfom action
on the browser with the help of POM class methods (i.e. genric methods)

  Once after executing @Test control will come to @AfterMethod (it will close browser)
  Once after executing all the scripts it will generate report in HTML format using TestNG

You might also like