PDF Selenium Notes Compress
PDF Selenium Notes Compress
SELENIUM
History
Locators
Web elements
Handling dropdown
Handling popup
Synchronization
Take screenshot
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.
section
‘Java’ under ‘Selenium client and WebDriver language bindings’ section
Flavors of Selenium
1. Selandroid
Selandroid –
– For
For android applications
2. Appium
Appium –
– For
For IOS, Windows and android applications
Advantages
languages
Supports 13 languages
Supports for multiple browsers
Disadvantages
Does not support for client server and stand alone applications
applications
Difference between Selenium and QTP
Selenium QTP
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/
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
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”
Steps to configure the downloaded files to Eclipse
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
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’
9. ‘Referenced Libraries’
Libraries’ will be created as below which consist of set of methods to
perform action on browsers
11. Enter a package name (in lower case) and click on ‘Finish’ button
button
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
Selenium Architecture
1. Selenium supports for multiple languages i.e. Java, C#, Ruby etc… these languages are
2. These client bindings will communicate to server and it will perform action on browsers
4. While communicating between server and browser uses protocol called as
class Lauch
key="webdriver.gecko.driver";
String key="webdriver.gecko .driver";
value="./software/
String value=". geckodriver.exe";
/software/geckodriver .exe";
System.setProperty (key,value);
(key,value);
WAP to launch empty Google Chrome Browser
class Lauch
key="webdriver.chrome.driver";
String key="webdriver.chrome .driver";
value="./software/
String value=". chromedriver.exe";
/software/chromedriver .exe";
System.setProperty (key,value);
(key,value);
Note:
2. System
System is
is a concrete class
3. setProperty()
setProperty() is
is static method of System class
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(); //To launch the browser
browser
1. Search context is the super most interface which has 2 abstract methods
of search context)
3. Remote web driver is an implantation class which consist of 13 concrete methods
Example for Run time polymorphism:
WebDriver driver = new FirefoxDriver();
Where,
WebDriver Is an interface
memory block
FirefoxDriver It is a constructor used to launch empty firefox driver and initialize all
class Lauch
key="webdriver.gecko.driver";
String key="webdriver.gecko.driver";
value="./software/
String value=". geckodriver.exe";
/software/geckodriver.exe";
System.setProperty (key,value);
(key,value);
driver.get(“https://www.google.com”);
driver.get (“https://www.google.com”); //To enter the URL
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);
1. findElement(By.args())
2. findElements(By.args())
1. close()
2. findElement(By.args())
3. findElements(By.args())
5. getCurrentUrl()
6. getPageSource ()
7. getTitle()
8. getWindowHandle()
9. getWindowHandles()
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.
1. tagName()
2. id()
3. name()
4. className()
5. linkText()
6. partialLinkText()
7. cssSelector()
8. xpath()
<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>
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";
System.setProperty (key,value);
(key,value);
driver.get(“https://www.google.com”);
driver.get (“https://www.google.com”); //To enter the URL
element/link
ele.click(); //To click the element/link
}
Note:
3. findElement will point to the first matching, in case of multiple webelements
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
class Sample
{
public static void main(String[] args)
{
System.setProperty ("webdriver.gecko.driver"
"webdriver.gecko.driver",,"./software/geckodriver.exe"
/software/geckodriver );
.exe");
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
}
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");
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
}
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
}
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
}
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:
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
5. In the ‘Search all add-
add -ons’ text box enter Firepath
Firepath
5. Notice that it will display source code and matching element will be highlighted
3. Press Ctrl+F and type css expression (a[id=’a1’]) and click enter
enter
Note:
class Sample
{
public static void main(String[] args)
{
System.setProperty ("webdriver. gecko.driver"
"webdriver.gecko .driver",,"./software/geckodriver.exe"
/software/geckodriver );
.exe");
driver.get(“https://www.google.com”);
driver.findElement(By.cssSelector("a[id=’a1’]")).click();
driver.findElement(By.cssSelector("a[id=’a1’]")).click();
}
}
X-path
X-path is a path of the element in HTML tree structure. In x-path we have 2 types,
Absolute x-path
x-path
<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>
1 html
1 body
1 div
1 input A
2 input B
2 div
1 input C
2 input D
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
element. Where ‘//’ indicates traverse form parent to any child or immediate child.
child.
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
2. //a
//a all the matching links and //a[1]
//a[1] all the links which has index as 1
X-path by attributes
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
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’]
When we don’t have attributes we use text() function.
function.
Syntax:
tag[text() = ‘Text_Value’]
‘Text_Value’]
Example:
X-path -
X-path - //div[text()= ‘Login’]
‘Login’]
Source code - <td>Java</td>
X-path - //td[text()=
X-path - //td[text()= ‘Java’]
‘Java’]
Ex: //td[
//td[.. = ‘Java’]
‘Java’]
Syntax:
<span>India **</span>
<span>Asia **</span>
X-path
//span[contains(( . , ‘India’)] OR
//span[contains OR //span[
//span[ . = ‘India’]
‘India’]
//span[contains(( . , ‘Asia’)]
//span[contains ‘Asia’)]
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>
X-path by traversing
Forward traversing –
traversing – Navigating from parent to child element by using / or //
//
Backward traversing –
traversing – Navigating from child element to parent element by using /..
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]
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
A 1 Bahubali 999 B
2 1 1 2
Preceding Sibling Following Sibling
Preceding sibling –
sibling – It will highlight element above/before the current element
Syntax: /preceding-sibling :: tag
Syntax: /preceding-sibling
A 1 Bahubali 999 B
2 1 1 2
Preceding Sibling Following Sibling
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
2 input B
2 div
1 input C
2 input D
store all matching element inside an array and it will specify index for individual component or
<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>
//input 10 (1 to 10)
(//input)[1] 1 (1)
(//input)[7] 1 (7)
(//input)[last()] 1 (10)
(//input)[last()-1] 1 (9)
(//input)[position()>3] 7 (4 to 10)
(//input)[1] | (//input)[last()]
(//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)
7. getLocation()
8. getRect()
9. getScreenshotAs
getScreenshotAs(OutputType<X>
(OutputType<X> arg)
10. getSize()
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
Script2 –
Script2 – To
To verify whether element is enabled or disabled
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. 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
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
Note: we can write as “ele.sendKeys(Keys.CONTROL+"ac"
“ele.sendKeys(Keys.CONTROL+"ac");”
);”
Script8 –
Script8 – To
To print text of the element
Script9 –
Script9 – To
To print location of the element in webpage
List is an interface
interface and
and it is one of the collection type
If the specified locator is not matching with any of the web elements then
System.out.println(count);
System.out.println(count);
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
System.out.println(count);
System.out.println(count);
for(WebElement we : links)
{
String text = we.getText();
System.out.println(text);
System.out.println(text);
}
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);
driver.findElement(By.id("//input[@id='lst-ib']")).sendKeys("Java");
driver.findElement(By.id("//input[@id='lst-ib']")).sendKeys("Java"); //step 3
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
4
System.out.println(count);
auto.get(count-1).click(); //step6
//step6
}
}
findElement() findElements()
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
‘NoSuchElementException’
‘NoSuchElementException’ Empty list or Empty array
array
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
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();
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
a. For Chrome browser it display as ‘Frame source / Frame page source
source
Source code:
For page3.html (frame)
t2 : <input id= “t3” type= “text”>
“text”>
System.setProperty(key,value);
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:
HANDLING DROPDOWNS
Dropdwons can
can be classified into 2 types
class Select
{
{Select(WebElement ele
ele)) //ele is a address
address of
of the dropdown
}
}
Select(ele);
Select s = new Select(ele); //ele is a address
address of
of the dropdown
c. selectByVisibleText(Stri
selectByVisibleText(String
ng text);
Select class consist of parameterized constructor
constructor which takes argument of WebElement (i.e. for
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");
}
}
a. deselectAll();
c. deselectByValue(Stri
deselectByValue(String
ng value);
d. deselectByVisibleText(S
deselectByVisibleText(String
tring text);
Note:
To verify whether dropdown is single/multiple select, we use ‘isMultiple()’
‘isMultiple()’ method
method
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");
}
}
}
{
WebElement ele
ele = driver.findElement(By.id("Iyengar"));
Select(ele);
Select s = new Select(ele);
List<WebElement> option = s.getOptions();
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
}
{
String text = we.getText();
we.getText();
l.add(text);
}
//sorting
Collections.sort(l); //sorting
for(String t : l)
{
//printing
System.out.println(t); //printing
}
}
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’
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()
4. doubleClick()
driver.findElement(By.xpath("//button[.='✕']")).click();
Thread.sleep(3000);
Actions(driver);
Actions act = new Actions(driver application
); //address of the application
act. moveToElement(ele).perform();
act.moveToElement (ele).perform();
Thread.sleep(3000);
driver.findElement(By.xpath("//span
driver.findElement(By.xpath("//span[.='T-Shirts']")).click(
[.='T-Shirts']")).click();
);
}
}
Note:
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'"));
}
HANDLING RIGHT CLICK OR CONTEXT CLICK ACTION
To handle right click action we go for Actions
Actions class
class
Script:
{
String key="webdriver.gecko.driver";
key="webdriver.gecko.driver";
String value="./software/geckodriver.exe";
value="./software/geckodriver.exe";
System.setProperty(key,value);
Script:
Thread.sleep(3000);
act. doubleClick(link).perform();
act.doubleClick (link).perform();
HANDLING POP-UPS
In selenium pop-ups are classified into 6 types,
1. Alert and confirmation popup
Characteristics:
Note:
To click ‘Ok’ button
‘Ok’ button we use accept()
accept() method
method
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:
block.click();
Alert a = driver.switchTo().alert();
driver.switchTo().alert(); //switch control to alert popup
String text = a.getText();
System.out.println(text);
a.accept(); OR
a.dismiss()
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.
Characteristics:
1. We can inspect the popup
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();
Characteristics:
3. It consist of 2 buttons ‘Open’ and ‘Cancel’
‘Cancel’
<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”);;
Characteristics:
a. Ok
b. Cancel
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’
ele.sendKeys(Keys.ENTER);
Thread.sleep(3000);
r.keyRelease(KeyEvent.VK_ALT);
r.keyRelease(KeyEvent.VK_S);
r.keyPress(KeyEvent.VK_ENTER);
r.keyRelease(KeyEvent.VK_ENTER);
}
}
popup
The browser re-sized to look like a popup is called as child browser popup
Characteristics:
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
Window popup
popup
2. ‘AutoIT’ is a free automation tool which is mainly used to handle window popup/ stand
alone application
1. Start All program AutoIT V3 AutoIT window Infor(x64)
2. Drag and drop finder tool on standalone application or window popup
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")
Script:
import java.io.IOException;
import java.io.IOException;
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:
driver.switchTo().window(id
driver.switchTo().window(id of browser)
Interview Questions:
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 )
);;
r.keyPress(KeyEvent.VK_ALT ));
;
r.keyPress(KeyEvent.VK_SPACE);
r.keyPress(KeyEvent.VK_C )
); ;
r.keyRelease(KeyEvent.VK_ALT )
);;
r.keyRelease(KeyEvent.VK_SPACE );
r.keyRelease(KeyEvent.VK_C )
);;
driver.manage().window().maximize();
driver .manage().window().maximize(); //maximize
To access Java Script Executor methods we Type cast from WebDriver to Java script
I SearchContext
I WebDriver I JavaScriptExecutor
©
RemoteWebDriver
Java script executor should be imported from the following package
package
import
import org.openqa.selenium.Jav
org.openqa.selenium.JavascriptExecutor;
ascriptExecutor;
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);
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:
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
}
}
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']"));
JavascriptExecutor js =
js = (JavascriptExecutor)
(JavascriptExecutor) driver;
driver ;
js.executeScript(
js.executeScript("window.scrollBy("
"window.scrollBy("+
+x+","
","+
+y+")");
")");
}
}
Advantages of Java Script Executor:
Executor:
I SearchContext
©
RemoteWebDriver
2. Take screen shot should be imported from the following package,
2. Capture the screenshot by using getScreenshotAs() method and it will store screenshot
in temp folder
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:
Implicit wait:
1. findElement()
2. findElements()
Statement:
driver.manage().timeouts().implicitlyWait(10, TimeUnit. SECONDS);
driver.manage().timeouts().implicitlyWait(10,
In the browser manage the time and implicitly wait for 10 seconds
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)
9. And this process continues until,
Explicit wait:
In order to synchronize all the methods including findElement() and findElements()
method we go for explicit wait statement
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)
1. Supports for findElement() and 1. Supports for all the methods including
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
‘NoSuchElementException’
‘NoSuchElementException’ or empty
list/ array
6. If page found it will go for next page 6. It waits for specified duration then it
Test NG:
Steps to attach Test NG to the project
project
Note:
Note:
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:
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);
);
}
}
public class Sample2
public class Sample2
{
@Test
@Test
public
public void test2()
void test2()
{
Reporter.log("2"
"2",
, true
true);
);
}
}
2. Expand folder Right click on ‘emailable report.html’ open with web browser
‘emailable--report.html’
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
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
{
@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
( enabled=false))
We using @Test (enabled=false //by default enabled = true
true
2. @BeforeTest
3. @BeforeClass
4. @BeforeMethod
5. @Test
@Test
6. @AfterMehtod
7. @AfterClass
8. @AfterTest
9. @AfterSuite
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)
3. @BeforeClass
4. @BeforeMethod
5. @Test
7. @AfterClass
application
To close the application
8. @AfterSuite
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);
}
@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
=====================================
===============================================
==========
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
=========================
=====================================
======================
==========
Default test
Tests run: 2, Failures: 0, Skips: 0
===========================
=======================================
====================
========
AfterSuite
=====================================
===============================================
==========
Default suite
Total tests run: 2, Failures: 0, Skips: 0
=========================
=====================================
======================
==========
Verification
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
=========================
=====================================
======================
==========
=====================================
===============================================
==========
Default suite
Total tests run: 1, Failures: 0, Skips: 0
=========================
===============================================
======================
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
Thread.sleep(3000);
String title =
title = driver.getTitle();
driver .getTitle();
System.out.println(
.println(title
title);
);
SoftAssert sa
sa =
= new SoftAssert();
new SoftAssert();
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
TestNG Junit
2. We can achieve parallel exection 2. We cannot achieve parallel exection
1. Testing the application for multiple test data is called as data driven testing
6. Apache POI is used to read the data from excel
path’
path’
file
1. Specify the path of the file
2. Open the excel file
file
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
2
sh =
Sheet sh = wb
wb.getSheet(
.getSheet("Sheet1"
"Sheet1");
); //step 3
3
int
int
row =
row = sh.getLastRowNum();
sh.getLastRowNum(); //step 4
4
System.out.println(
.println(row
row);
); //step 5
5
Row r = sh.getRow(0);
sh.getRow(0); //step 6
6
Cell c = r.getCell(1);
String v = c.getStringCellValue();
System.out.println(
.println(v
v);
}
}
Note:
1. Row position starts
starts from
from 0
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’
0 1 2
0 123
1 456
2 789
3 101
4
5
Total data = 4
Row count = 4-1 =3
=3
{
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
10 rows 15 cells 100 rows 100 cells
‘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");
);
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'
}
}
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)
POM
POM
POM –
– Page
Page Object Model
2. Initilization
3. Utilization
Declaration:
Declaration:
Syntax: @findBy(LocatorName
@findBy(LocatorName = “LocatorValue”)
“LocatorValue”)
Initilization:
Initilization:
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);
}
Utilization:
Utilization:
@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();
}
}
{
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
Exception’
- NullPointerException
NullPointerException
@findBy (//a)
FRAMEWORK
Framework is a set of procedure / guideliness / rules / protocol followed while
Framework Design:
They will develop standard files and folder structure and also generic libraries (methods)
required for framework
chromedriver.exe)
7. In order to run multiple scripts and to genrate reports attach TestNG
TestNG to
to the project
Initial structure of folder structure of framework
In our framework/ project we have set of constants such as key, value and path of excel
file etc…
etc…
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" ;
}
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
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)
Base_TEST (C)
1. In order to test the application with the multiple data is called as data driven testing
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
}
}
2. In each and every POM class we perform common action such as (verification of title
3. In order to avoid repetation of code we develop generic methods in the generic class
5. Since this class only for inhertiance purpose, not for execution we declare class as
abstract
abstract
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 they will develo POM classes for individual
for individual webpage.
webpage.
Step6: click on
on ‘About ActiTime’
ActiTime’
Elements required for POM class
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
@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
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);
);
}
}
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;
@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:
3. Test cases depends on number of test cases
4. For each and every test case we develop test classes
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
6. In test class we call POM class method to perform action on the browser
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);
);
}
}
public
public
class
class InvalidLogin extends
extends Base_TEST
Base_TEST
{
@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();
}
}
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);
);
}
}
To convert project to TestNG.xml (Right
TestNG.xml (Right click on project TestNG Convert to TestNG
Finish
</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
FRAMEWORK ARCHITECTURE
2. Hybrid framework is a combination of multiple frameworks such as POM, Data driven,
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
for POM
In order to test the application with multiple test data from the excel and retreive data
In order to avoid repetation of the code we develop individual methods for individual
Base_TEST
Base_TEST class consists of 2 methods i.e. @BeforMethod to open application
In Base_PAGE
Base_PAGE class we develop generic methods such as verification of title and
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