Beruflich Dokumente
Kultur Dokumente
Table of Contents
1.
Software Testing.................................................................................................................. 2
1.1
1.2
1.3
Automation................................................................................................................... 2
1.4
Advantages:.................................................................................................................. 2
1.5
1.6
1.7
2.
Selenium IDE....................................................................................................................... 4
2.1
Introduction.................................................................................................................. 4
2.2
History of selenium....................................................................................................... 4
2.3
Selenium Components.................................................................................................. 4
2.4
Advantages................................................................................................................... 4
2.5
Disadvantages.............................................................................................................. 4
2.6
Installation.................................................................................................................... 5
2.7
Recording...................................................................................................................... 8
2.8
3.
HTML............................................................................................................................. 9
3.2
Java............................................................................................................................. 13
4.
Web Driver........................................................................................................................ 13
4.1
4.2
4.3
5.
4.3.1
4.3.2
WebDriver......................................................................................................................... 18
5.1
5.2
5.3
5.4
5.5
Prathap Kumar
1. Software Testing
1.1 What is mean by Testing?
The process of exercising software to verify that it satisfies specified
requirements and to detect errors.
The process of analyzing a software item to detect the differences
between existing and required conditions (that is, bugs), and to evaluate
the features of the software item.
The process of operating a system or component under specified
conditions, observing or recording the results, and making an evaluation
of some aspect of the system or component.
1.2
1.3 Automation
Automation Testing: Testing which is done by any other third party tool.
Test automation is the use of software to control the execution of tests, the
comparison of actual outcomes to predicted outcomes, the setting up of test
preconditions, and other test control and test reporting functions. Commonly,
test automation involves automating a manual process already in place that
uses a formalized testing process.
1.4
Advantages:
Reliable: Tests perform precisely the same operations each time they are
run, thereby eliminating human error
Repeatable: You can test how the software reacts under repeated execution
of the same operations. Programmable: You can program sophisticated tests
that bring out hidden information from the application.
2
Prathap Kumar
Comprehensive: You can build a suite of tests that covers every feature in
your application.
Reusable: You can reuse tests on different versions of an application, even if
the user interfaces changes.
Better Quality Software: Because you can run more tests in less time with
fewer resources
Fast: Automated Tools run tests significantly faster than human users.
Cost Reduction: As the number of resources for regression test are reduced.
Reporting: Customized reporting of application defects.
1.5
1.6
Open Source
Selenium-1.0
Web driver 2.0
Sahi
Bad Boy
Ruby
Watir
1.7
QTP
Paid tool
Works on Windows
Tests web and desktop applications
Works on Firefox 3.5.x and IE
VB Script
Object properties, Repository
Prathap Kumar
There is no option, can record script in
Selenium IDE, can spy objects using IE
developer tool bar, Firebug and also
using http://saucelabs.com/builder
IDE sometimes does not record some
events
Set of Libraries, around 20MB (Need
to include other supporting software)
Saucelabs.com, Element34 ,
Commercial Support
2.
objects
GUI Spy
Selenium IDE
2.1 Introduction
The selenium IDE is the tool you use to develop your selenium test cases by using
record and play back.
2.4 Advantages
Its an easy to-use
Its just Firefox plug in and is generally the most efficient way to develop test
cases
Very useful tool for beginners
Firefox extension which allows record/Play testing paradigm
Creates the simplest possible locator based on selenes
Look at various possible commands in the dropdown
Records a test at HTML file
We can export the test as Java /Ruby etc...
4
Prathap Kumar
2.5 Disadvantages
Selenium-IDE does not directly support:
Condition statements
Iteration or looping
Logging and reporting of test results
Error handling, particularly unexpected errors
Database testing
Test case grouping
Re-execution of failed tests
Test case dependency
Capture screenshots on test failures
Results Report generations
2.6 Installation
Open Mozilla firefox browser and type http://seleniumhq.org/download in the url and hit
enter.
The following window appears.
Click on the latest version link in Selenium IDE section as shown above. The follow pop
up appears as shown below. Click on the Allow pop up.
Prathap Kumar
Prathap Kumar
Restart Firefox
Navigate to -> tools option here we can find IDE
Prathap Kumar
Selenium IDE looks like below
2.7 Recording
Recording user actions with respect to user objects
In selenium we have two types of recording options
Prathap Kumar
Prathap Kumar
This is the required web page. The HTML code should be as follows.
<html>
<head>
<title>Welcome to html</title>
</head>
<body>
Username:<input type="text" name="uname"/>
Password:<input type="password" name="pwd"/>
<input type="button" id="but" value="Login"/>
<input type="checkbox" id="rep"/>Reports
<table >
<tr>
<td><input type="radio" name="gender" id="female"/> Female</td>
<td><input type="radio" name="gender" id="male"/> Male</td>
10
Prathap Kumar
</tr>
</table>
<table >
<tr>
<td><a href="http://google.com" class="myclass">Google </a></td>
</tr>
</table>
<table >
<tr>
<td><img src="mobile.jpg"/></td>
</tr>
<tr>
<td><a href="http://flipkart.com" >
<img src="flip.jpg"/></a></td>
</tr>
</table>
<table>
<tr>
<td><select name="city">
<option value="1">Bangalore</option>
<option value="2">Chennai</option>
<option value="3">Kolkatta</option>
<option value="4">Delhi</option>
</select></td>
<td><select name="city-multiple" multiple="">
<option value="1">Bangalore</option>
<option value="2">Chennai</option>
11
Prathap Kumar
<option value="3">Kolkatta</option>
<option value="4">Delhi</option>
</select></td>
</tr>
</table>
<table >
<tr>
<td><textarea name="description"></textarea></td>
<td><input type="file" name="browse"/></td>
</tr>
</table>
</body>
</html>
Write the above code in Note pad and save as filename.html. Double click on the file where it
is saved. The required html is obtained.
The given below shows the detailed html tags.
Element
Text box
HTML
Tag
input
Mandato
ry
Property
type
Value
text
2
3
4
Password
Box
Button
Checkbox
input
input
input
type
type
type
password
submit/button
checkbox
Radio button
input
type
Link
href
Image
img
src
radio
internal/exter
nal
path of the
image
Single select
Combo Box
select
9
10
11
Multi Select
Combo Box
Text area
File Browser
select
textarea
input
Sl.
no
1
12
multiple
TRUE
type
file
Addition
al
property
Name/ID
Value
User defined
Name/ID
Name/ID
Name/ID
Name and
ID
User defined
User defined
User defined
Name/ID
User defined
Name/ID
Name/ID
Name/ID
User defined
User defined
User defined
User defined
Prathap Kumar
3.2 Java
4. Web Driver
There are only two actions performed in any automation tool.
i.
ii.
Element identification
Performing action on the particular element.
ID.
Name.
Link text.
CSS Selectors.
XPath.
Partial Link text.
Class name
Tag name.
13
Prathap Kumar
4.2 Element identification using Css selectors:
Css selectors can be used to identify the elements which dont have id or name
property and they are not links.
Css selectors use the HTML tag properties and values of the element to identify the
element.
Eg. To identify the button with the HTML source.
HTML source:
<input type=submit value=login/>
The Css selector value is:
input[type=submit]
The syntax is:
html tag[property=value]
We can use any property value pair to identify the element. To evaluate the Css
expression, we can use the tool called firepath which is an add-on for the firefox and
an extension for firebug.
Css Expression for:
Textbox: input[type=text]
Button: input[type=submit]
Checkbox: input[type=checkbox]
Radio: input[type=radio]
Link: a
Image: img
Select: select
Textarea: text area
If any element has an id property we can use the generic expression
Syntax:
html tag#Propertyvalue
Example:
input#reports
If any element has a class property we can use the generic expression
Syntax:
html tag.Classname
Example:
input.linkclass
Css is mostly used for buttons.
14
Prathap Kumar
Prathap Kumar
Example 2:
//input[@type='text' and @name='uname']
Identification of
Check box //input[@type=checkbox]
Radio button //input[@type=radio]
Link //a
Image img
Table//table
Image with link //a/img
b) Text()
Finding an element by its text using text()
Syntax:
//html tag[text()=Value]
Example: To find a link where text is google
//a[text()=Google]
//a[text()=Big brother]
Note: text() is an exact match function and it will not be able to match an element, if the
text of the element has spaces on either side.
c) Contains(text())
Contains text is the pattern matching function which can be used to match an element
with any text in the pattern.
Syntax:
//html tag[contains(text(),value)
Example:
//a[contains(text(),Google)]
Note:
Text() exact match
Contains pattern match
d) Contains(attribute)
To find a link with its part of attribute value we use contains attribute.
Syntax:
//html tag[contains(@attribute,value)]
Example:
//input[contains(@id,fema)]
Finding the parent and child element of html tags
To find the child elements of html tag we can use
the syntax
//parent html tag/ child html tag
16
Prathap Kumar
Example:
//a/img output is img which is child of link.
To find the parent of a child we can use the syntax
//parent html tag [Child html tag]
Example:
//a[img] output is a
Dynamic changing elements
To identify dynamic elements using Xpath we can take the help of dependent and
independent concepts.
Following are the steps to find dynamic elements:
1) Identify dependent and independent elements
Independent elements generally will be unique elements based on which all the action
are performed.
Example: a) Name of the mobile is independent while the price is dependent
b) Title of the book is independent and author of the book is dependent
Independent elements are not duplicated for that particular table.
2) Right click on independent element and inspect the element for the independent
element.
3) Find the immediate common parent for both dependent and independent elements.
Note: In firebug move the mouse courser from the independent element upwards in
the html till an html tag covers both the dependent and independent element.
4) From the immediate common parent write the tree structure
5) Write the Xpath expression to find the immediate common parent from the
independent element
Note: The concept used here will be finding the parent and the syntax will be
square braces ( [ ).
Example:
//tr[td[a[text()='Bing']]]
6) Write the Xpath expression to find the dependent element from the immediate
common parent.
Note: The concept used here will be finding the child and the syntax will be slash ( /
).
Example:
1) //tr[td[a[text()='Bing']]]/td[3]/input
17
Prathap Kumar
2) //div[div[div[div[a[contains(text(),'Ophelia and the Marvellous Boy
(Paperback)')]]]]]/div[2]/div[1]/div[3]/a
This Xpath can be reduced as
//div[div[div[div[a[contains(text(),'Ophelia and the Marvellous Boy
(Paperback)')]]]]]//a[text()='Buy Now']
Or
//div[div[div[div[a[contains(text(),'Ophelia and the Marvellous Boy
(Paperback)')]]]]]/descendant::a[text()='Buy Now']
Descendant function can be used to find descendant child element under the
immediate common parent.
Descendant() matches the element at any level in the hierarchy under the parent
Note: we can use either // or descendant::
5. WebDriver
Web driver is an automation tool which can be used to automate web applications
which have DOM structure.
Configuring eclipse the web driver
Requirements
18
Prathap Kumar
Right Click on Project Build Path Configure Build path Libraries Select
the Path of stand alone server and click on OK. Selenium configuration is done.
Note: Disable the firefox update.
The firefox browser launched by the web driver will not have history or add-ons.
A bottom right corner you have webdriver. By default it will be minimized.
driver.get() will continue to wait until the page has loded completely
Write down the following code in the java class to open a browser.
package Basics;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class Demo {
public static void main(String[] args) {
WebDriver driver=new FirefoxDriver();
}
}
To launch application the code is
package Basics;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class Demo {
public static void main(String[] args) {
// to open the browser
WebDriver driver=new FirefoxDriver();
// to launch an application and open the URL
driver.get("http://www.gmail.com");
// to quit the browser
driver.quit();
}
}
To identify the element webdriver provide a method called findelement() which takes
an argument of By class which has eight element locators.
To perform a type of action
WebElement un=driver.findElement(By.id("username"));
un.sendKeys("admin");
OR
19
Prathap Kumar
driver.find element (by name (username).sendkeys(admin);
Prathap Kumar
System.out.println("fail");
}
21
Prathap Kumar
5.3 WORKING WITH SELECT DROPDOWNS
To work with select html tag elements (single select combo box or multi select list
box). We need to use select class
On a select html tag element we can do the following.
1.
1)
2)
3)
In multi select list box the same method will be used however, if we write select
methods multiple times in the code, it will select multiple options from the list box.
WebDriver driver=new FirefoxDriver();
driver.get("file:///C:/Users/pratap/Desktop/Batch19/mypage.html");
//find the city drop down using driver.findElement
WebElement city=driver.findElement(By.name("city"));
//pass the WebElement city as an argument to the constructor of the Select class
Select dd=new Select(city);
//Using the object of select class, select option
dd.selectByIndex(2);
Thread.sleep(5000);
dd.selectByValue("4");
Thread.sleep(5000);
dd.selectByVisibleText("Chennai");
Multi select:
WebDriver driver=new FirefoxDriver();
driver.get("file:///C:/Users/pratap/Desktop/Batch19/mypage.html");
WebElement city=driver.findElement(By.name("cities"));
Select dd=new Select(city);
dd.selectByIndex(2);
Thread.sleep(5000);
dd.selectByValue("4");
Thread.sleep(5000);
dd.selectByVisibleText("Chennai");
2. Deselecting options from multi select list box.
22
Prathap Kumar
To deselect all of the options we can use deSelectAll().
To deselect individual options we can use deselectByIndex(), deselectByValue() or
deselectByVisibleText().
dd.deselectAll();
3. To get all available options select class provides a method getOptions() which
returns a collection of all the options in the select dropdown. This collection is
represented as a list of webElement. Using a for loop we can iterate the list, get
each element from the List<WebElement> print the text of each element (Text of
the option tag or visible text).
WebDriver driver=new FirefoxDriver();
driver.get("file:///C:/Users/pratap/Desktop/Batch19/mypage.html");
//find the city drop down using driver.findElement
WebElement city=driver.findElement(By.name("city"));
//pass the WebElement city as an argument to the constructor of the Select class
Select dd=new Select(city);
//Using the object of select class, select option
dd.selectByIndex(2);
Thread.sleep(5000);
dd.selectByValue("4");
Thread.sleep(5000);
dd.selectByVisibleText("Chennai");
//to know all options in a select drop down
List<WebElement> allOptions=dd.getOptions();
int k=allOptions.size();
System.out.println(k);
for (int i = 0; i < k; i++) {
// to get each element from list
WebElement option=allOptions.get(i);
String text=option.getText();
// Print the text of each element4
System.out.println(text);
}
4. To get all the selected options from a multi select list box, we can use the method
getAllSelectedOptions() which returns a list of web element (Collection of all the
select options). We can use a for loop and get each selected option and print the
text of each element.
WebDriver driver=new FirefoxDriver();
driver.get("file:///C:/Users/pratap/Desktop/Batch19/mypage.html");
WebElement city=driver.findElement(By.name("cities"));
Select dd=new Select(city);
dd.selectByIndex(2);
Thread.sleep(5000);
dd.selectByValue("4");
Thread.sleep(5000);
dd.selectByVisibleText("Chennai");
Thread.sleep(5000);
23
Prathap Kumar
//dd.deselectAll();
List<WebElement> allOptions=dd.getAllSelectedOptions();
int k=allOptions.size();
System.out.println(k);
for (int i = 0; i < k; i++) {
WebElement option=allOptions.get(i);
String text=option.getText();
System.out.println(text);
}
}
Prathap Kumar
driver.get("http://www.gsmarena.com/samsung-phones-9.php");
List<WebElement>
allCheck=driver.findElements(By.xpath("//input[@type='Checkbox']"));
int l=allCheck.size();
System.out.println(l);
To check all checkboxes we can use loop through the list of using for loop. Get each
element from the list using get() which will return a web element and use click() to
check the checkbox.
for (int i = 0; i < l; i++) {
WebElement check=allCheck.get(i);
check.click();
}
CONCEPT OF SYNCHRONIZATION IN WEB DRIVER:
Synchronization refers to matching the speed of script execution with the speed of
application. In web driver we can use implicitlyWait() to achieve the synchronization
How does it works?
Every driver.findElement() checks if implicitlyWait() is defined. If it is defined
web driver will wait for the element to be found till the duration specified in
implicitlyWait() and if the element if found wit in the duration, it will try to perform the
action and if the element is found it will throw an exception NoSuchElementException
ImplicitlyWait() its defined once for the automation.
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
HOW TO HANDLE TOOL TIPS:
There are totally 7 kinds of pop ups.
1. Tool tip Moving the mouse over the image.
- Clicking on the image link?
2. Calendar pop up
3. Java Script alert and confirmation pop up.
4. Page on load authentication pop up.
5. File download/upload.
6. New browser pop up/New tab.
7. Light box/Model window.
1. How to handle tool tips:
Tool tips are two types
1) Generated using title attribute
2) Has a pop up in the html(division pop-up)
If the tool tips coming from the title attribute, we can find the element and use
getAttribute() to get tool tip text.
WebDriver driver=new FirefoxDriver();
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
25
Prathap Kumar
driver.get("http://www.flipkart.com/samsung-galaxy-s-duos-2s7582/p/itmdqzpfvmmzzxme?pid=MOBDQZPYAZSDKBWH&srno=b_1&ref=930dfd23203e-4a60-abcb-bfcf06f27fcf");
String tooTip=driver.findElement(By.id("visible-image-small")).getAttribute("title");
System.out.println(tooTip);
If the tool tips coming from div pop up we can find div using driver.findElement() and
use getText() to get text from the division
driver.findElement(By.id("fk-shipping-info-link")).click();
String tooltip2=driver.findElement(By.id("fk-shipping-info-message")).getText();
System.out.println(tooltip2);
2. Calendar pop-ups.
There are generally two kinds of calendar fields.
a. Which allows you to type the date.
b. Which allows you to select the date from the calendar pop up.
If the calendar allows to type the date use driver.findElement() and sendKeys().
If it is a pop up then click on the calendar icon to make the calendar icon visible. Use
an Xpath to find the date and click on it.
Note: Calendar pop up will generally be in a table structure. Web driver cannot identify
the hidden elements. Web driver cannot identify or perform action on the hidden
elements. If the element is visible to the user web driver can identify it. If the element
is hidden to the user Web driver cannot identify it.
WebDriver driver=new FirefoxDriver();
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
driver.get("http://www.yatra.com");
driver.findElement(By.xpath("//i[@class='sprite calenderIcon' and
@onclick='BE_Flights_Action.openDepartDateCalender();']")).click();
driver.findElement(By.xpath("//a[@id='a_2014_5_27']")).click();
3) Java script alert confirmation pop-up
Java script pop-up
Alert
Confirmation
26
Prathap Kumar
To handle javascript alert or confirmation pop-up, we need to first switch to the
pop-up using driver.switchTo().alert() which will return on object of alert. Using this
object we can
1)get the text on the pop-up using get text
2)click on cancel using dismiss()
3)click on ok using accept ()
WebDriver driver=new FirefoxDriver();
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
driver.get("http://demo.actitime.com/");
driver.findElement(By.id("username")).sendKeys("admin");
driver.findElement(By.name("pwd")).sendKeys("manager");
driver.findElement(By.linkText("Login")).click();
driver.findElement(By.xpath("//a[@href='/tasks/otasklist.do']")).click();
driver.findElement(By.linkText("Projects & Customers")).click();
driver.findElement(By.xpath("//span[text()='Create Customer']")).click();
driver.findElement(By.name("name")).sendKeys("prathap");
driver.findElement(By.xpath("//input[@onclick='cancelCustomerCreation();']")).click();
Alert alt=driver.switchTo().alert();
String alertText=alt.getText();
System.out.println(alertText);
//driver.switchTo().alert().accept();
alt.dismiss();
PAGE UNLOAD POP-UP
Handling page on load authentication pop-up.
By default selenium cannot handle page on load authentication pop-up. To
overcome the problem we can pass the username and password in the URL with the
following syntax.
http://username:password@ipaddress/domainname
driver.get("http://admin:password@192.168.1.1");
File download pop-up in firefox
Preference type is available from about:config.
Mime type can be download from
http://www.hansenb.pdx.edu/DMKB/dict/tutorials/mime_typ.php.
To save a file to disk automatically without the pop-up, we can take help of Firefox
preferences by using Firefox profile.
27
Prathap Kumar
Case 1:
To save the file to the downloads folder, we can use the preference
browser.helperApps.neverAsk.saveToDisk and provide the file MIME type as a value for
the preference i.e., application/zip. If there are multiple files types to be download we
can provide (,) separated list of MIME types of all the files.
FirefoxProfile prof=new FirefoxProfile();
prof.setPreference("browser.helperApps.neverAsk.saveToDisk", "application/zip");
Case 2:
If the file has to be downloaded to desktop along with never
browser.helperApps.neverAsk.saveToDisk preference we need to provide another
preference which is browser.download.folderList with an integer value 0.
By default the value for browser.download.folderList will be 1 which represents
download folder.
FirefoxProfile prof=new FirefoxProfile();
prof.setPreference("browser.helperApps.neverAsk.saveToDisk", "application/zip");
prof.setPreference("browser.download.folderList", 0);
Case 3:
Save file to custom folder path.
To download a file to custom folder path we need to set the preference
browser.download.folderList with integer value 2 and we also need to set the
preference browser.download.dir with the value which is custom folder path.
FirefoxProfile prof=new FirefoxProfile();
prof.setPreference("browser.helperApps.neverAsk.saveToDisk", "application/zip");
prof.setPreference("browser.download.folderList", 2);
prof.setPreference("browser.download.dir","D:\\Docs");
// common for each case
WebDriver driver=new FirefoxDriver(prof);
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
driver.get("http://docs.seleniumhq.org/download/");
driver.findElement(By.xpath("//a[@href='http://seleniumrelease.storage.googleapis.com/2.41/selenium-java-2.41.0.zip']")).click();
Note: Dont forget to set the preference in Firefox class which is done in common for
each case.
Working with menu drop down:
28
Prathap Kumar
If we want to click on a sub-menu item which will be visible when we move the
mouse on to parent menu, we can use Actions class. Actions class provides methods
to perform mouse and key board related actions.
Sub-menu items or link will not be visible until we move the mouse on parent
menu item or link. If the element is not visible, web driver cannot perform the action.
Hence we need to stimulate moving to parent menu item so that drop down with submenu links is visible and web driver can find the sub menu items.
We can use moveToElement() and pass parent menu as an argument which will
stimulate the drop down menu.
How do you perform right click using web driver?
The right click menu is called context menu. We can use the Actions class
ContextClick() to perform right click.
How to perform key board action?
We can use sendKeys() of Actions class to send any key. We can also use
sendkeys() for Web Element to send any key. Keys enumerator provides all the keys of
the key board and can be used to sendKeys() like tab, control, alt, shift.
WebDriver driver=new FirefoxDriver();
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(30,TimeUnit.SECONDS);
driver.get("http://yatra.com/");
WebElement
parentMenu=driver.findElement(By.xpath("//a[@href='http://www.yatra.com/holidays/i
ndia-tour-packages' and @data-pagetrackvalue='/Clicks/GN/Holidays']"));
Actions act=new Actions(driver);
act.moveToElement(parentMenu).perform();
//WebElement
subMenu=driver.findElement(By.xpath("(//a[@href='http://railtourpackages.yatra.com/
trainpackages/home'])[1]"));
//act.moveToElement(subMenu).perform();
act.contextClick(parentMenu).perform();
//System.out.println("Begin");
//act.sendKeys("T").perform();
act.sendKeys(Keys.DOWN).perform();
act.sendKeys(Keys.ENTER).perform();
DRAG AND DROP:
We can use the dragAndDrop() of Action class which takes two arguments
source and target.
IDENTIFYING SOURCE:
29
Prathap Kumar
When we move the mouse type to the element if the curser type changes to
move that part can be used to drag. The part which can be dragged will generally
have a class property with the value drag or class name will have the drag.
WebDriver driver=new FirefoxDriver();
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(30,TimeUnit.SECONDS);
driver.get("http://www.dhtmlgoodies.com/submitted-scripts/i-google-like-drag-drop/");
Actions act=new Actions(driver);
WebElement source=driver.findElement(By.xpath("//div[@id='block-1']/h1"));
WebElement target=driver.findElement(By.id("block-3"));
act.dragAndDrop(source, target).perform();
BROWSER ACTIONS:
// Maximize the browser
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
//driver.get("http://demo.actitime.com");
// alternate to driver.get()
driver.navigate().to("http://demo.actitime.com");
driver.findElement(By.id("username")).sendKeys("admin");
driver.findElement(By.name("pwd")).sendKeys("manager");
driver.findElement(By.linkText("Login")).click();
driver.findElement(By.xpath("//a[@href='/tasks/otasklist.do']")).click();
//to get current url
String Url=driver.getCurrentUrl();
System.out.println(Url);
Thread.sleep(5000);
//simulate browser back button action
driver.navigate().back();
Thread.sleep(5000);
//simulate browser forward button action
driver.navigate().forward();
Thread.sleep(5000);
//simulate browser refresh button action
driver.navigate().refresh();
driver.close();
WORKING WITH IE:
REQUIREMENTS
Driver executable which can be downloaded from
http://docs.seleniumhq.org/download/.
Depending on the operating system (32 bit or 64 bit) Download the respective
browser driver i.e., IEDriverServer.exe
IE Settings
The following settings has to be done to IE.
1) Tools Internet options Security Tab make sure all the four zones i.e.,
internet, local intranet, trusted sites and restricted sites have enable
protected mode check box.
2) Make sure browser zoom level is set to 100%. Press ctrl+0 to set Zoom level
to 100%.
30
Prathap Kumar
In selenium script write the following code.
System.setProperty("webdriver.ie.driver",
"D:\\Seleniumprogs\\workspace\\Batch18web\\IEDriverServer.exe");
WebDriver driver=new InternetExplorerDriver();
WORKING WITH THE GOOGLE CHROME REQIREMENT:
Requirements.
Driver executable which can be downloaded from
http://docs.seleniumhq.org/download/
Go to section Third party browser driver, click on download page against
chrome. Download chromedriver.exe. In eclipse write the following code.
System.setProperty("webdriver.chrome.driver",
"D:\\Seleniumprogs\\workspace\\Batch18web\\chromedriver.exe");
WebDriver driver=new ChromeDriver();
Untrusted connection:
Firefox automatically handles untrusted connection. Change the system time to 2
years back and open a secures site like www.gmail.com
HOW TO HANDLE UNTRUSTED CERIFICATES CONNECTION ISSUES.
By default, Google chrome and Firefox automatically handles untrusted connection
issues. However internet explorer doesnt handle it automatically. We have to use java
script to overcome the problem
System.setProperty("webdriver.ie.driver", "D:\\Seleniumprogs\\IEDriverServer.exe");
WebDriver driver=new InternetExplorerDriver();
driver.get("http://gmail.com");
JavascriptExecutor jse = (JavascriptExecutor)driver;
jse.executeScript("document.getElementById('overridelink').click();");
Handling frames in web driver
Problem:
Web driver cannot understand the element present inside an iframe by default.
It cannot search for any element which is present in the iframe DOM.
Solution:
Transfer the control of web driver to the DOM of the iframe using
driver.switchTo.frame(). Frame() is an overloaded method with
frame(int arg)
frame(String arg)
frame(WebElement arg)
31
Prathap Kumar
1) Frame(int arg)
If the page has one or two iframes we can use this method by passing zero
based index of the frame.
Eg.
driver.switchTo().frame(0);
driver.switchTo().frame(1);
2) Frame(String arg)
If an iframe has id or name property we can use the value of the id or the name
property to find the iframe.
Eg.
driver.switchTo().frame(mailroifrm12);
3) Frame(WebElement arg)
If we have multiple iframes on the page the frames does not have ID or name
property, we can use the Web Element arg and find the iframe.
Eg.
WebElement frm=driver.findElement(By.id("mailroifrm12"));
driver.switchTo().frame(frm);
After performing the action on an element inside iframe. If we want to come out
of the iframe, we
we can use
driver.switchTo().defaultContent();
How to identify the element inside a frame?
Right click on the element in Firefox in the context menu, if it shows This frame
which means the
element is inside the frame.
WebDriver driver=new FirefoxDriver();
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
driver.get("http://timesofindia.indiatimes.com/");
Thread.sleep(20000);
WebElement frm=driver.findElement(By.id("mailroifrm12"));
driver.switchTo().frame(frm);
//driver.switchTo().frame("mailroifrm12");
driver.findElement(By.id("mathuserans2")).sendKeys("2");
driver.switchTo().defaultContent();
driver.findElement(By.xpath("(//a[text()='Entertainment'])[1]")).click();
Excel Library:
32
Prathap Kumar
Requirements:
Apache poi
We can download apache poi from poi.apachi.org/download.html
Go to the binary distribution section click on the link poi-bin-3.9.20122013.zip which
will navigate to a page with the links called download. Click on the first link to
download apache poi.
GETTING DATA FROM AN EXCEL CELL:
1. Get the excel file as an input.
2. Convert the excel file to a work book (Get the workbook object or create the work
book object) from the Excel file.
3. Go to a particular sheet of the Excel (Get the sheet object from the work book).
4. Go to a particular row in the sheet (Get the row object from the sheet).
5. Go to a particular cell in the row (Get the cell object from the row).
6. Get the data from the cell depending on the type of data.
33
org.apache.poi.openxml4j.exceptions.InvalidFormatException;
org.apache.poi.ss.usermodel.Cell;
org.apache.poi.ss.usermodel.Row;
org.apache.poi.ss.usermodel.Sheet;
org.apache.poi.ss.usermodel.Workbook;
Prathap Kumar
import org.apache.poi.ss.usermodel.WorkbookFactory;
public class ExcelLibrary {
public String getExcelData(String sheetname,int i, int j) {
String dataText=null;
try {
FileInputStream fis=new
FileInputStream("../Batch18web/data/data.xlsx");
Workbook wb=WorkbookFactory.create(fis);
Sheet s=wb.getSheet(sheetname);
Row r=s.getRow(i);
Cell c=r.getCell(j);
dataText=c.getStringCellValue();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvalidFormatException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return dataText;
}
public int getRowNum(String sheetname) {
int rowCnt=0;
try {
FileInputStream fis=new
FileInputStream("../Batch18web/data/data.xlsx");
Workbook wb=WorkbookFactory.create(fis);
Sheet s=wb.getSheet(sheetname);
rowCnt=s.getLastRowNum();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvalidFormatException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return rowCnt;
}
}
34
Prathap Kumar
Program 2:
package driverPackage;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class LoginLogout {
public static void main(String[] args) {
WebDriver driver=new FirefoxDriver();
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(30,TimeUnit.SECONDS);
driver.get("http://demo.actitime.com");
ExcelLibrary xlib=new ExcelLibrary();
int rowNum=xlib.getRowNum("Sheet1");
//System.out.println(rowNum);
for (int i = 1; i <=rowNum; i++) {
String un=xlib.getExcelData("Sheet1",i, 0);
String pw=xlib.getExcelData("Sheet1",i, 1);
driver.findElement(By.id("username")).sendKeys(un);
driver.findElement(By.name("pwd")).sendKeys(pw);
driver.findElement(By.linkText("Login")).click();
driver.findElement(By.linkText("Logout")).click();
}
}
}
TestNG
TestNG (test next generation) is created by Cedric Beust and its an unit testing frame
work which can be used for white box testing. TestNG provides features like multiple
test execution, assertions, results and execution control. This features are essential
part of automation and we can use testNG with selenium to achieve robust
automation.
Installation of TestNG:
Open Eclipse Goto Help Install new software Click on Add Button. In the name
text box give a name i.e., textNG. In the location text box type
http://www.beust.com/eclipse. click on Next, Next and install.
Every testNG class should have @test annotation which will ensure the class can be
executed. There can be multiple method in a testNG class but each test method
should have @test annotation. By default all the test methods of testNG class will get
executed.
35
Prathap Kumar
If there are either pre-condition or post condition for the test we can code them in
different methods with @BeforeMethod and @AfterMethod annotation. If there are
multiple test methods @BeforeMethod and @AfterMethod will get execute for each
test in that class.
If there are pre and post condition for entire class we can put them under two different
method with @BeforeClass and @AfterClass class annotation.
package DemoTestNg;
import
import
import
import
import
org.testng.annotations.AfterClass;
org.testng.annotations.AfterMethod;
org.testng.annotations.BeforeClass;
org.testng.annotations.BeforeMethod;
org.testng.annotations.Test;
Prathap Kumar
AcreateCustomer
ALogout
ALogin
AeditCustomer
ALogout
AcloseUrl
37
Prathap Kumar
System.out.println("Executing Modify customer");
}
@Test(priority=3)
public void testDeleteCustomer() {
System.out.println("Executing Delete customer");
}
}
4) Assertions:
We can use Assert class of TestNG which has list of static assertEquals()
(overloaded static methods) for comparing the actual and expected
(Checkpoints). If the assertions passes the test will be marked as pass and if
assertion fails the test will be marked as FAIL. If there is any statement after the
assert, it will not get executed if assertion fails.
38
Prathap Kumar
5) Skipping test methods:
If we set a test method to depend on another test method and if the assertion
fails the dependant test method will be skipped.
public class NewTest {
@Test
public void createTest() {
String actual="Hello123";
String expected="Hello";
Assert.assertEquals(actual, expected);
System.out.println("This test is pass");
}
@Test(dependsOnMethods={"createTest"})
public void anotherTest() {
System.out.println("Executing another test");
}
@Test
public void firstTest() {
System.out.println("Executing first test");
}
}
FrameWork
Create a folder called frame work. Create a folder called jars inside the framework
folder.
Copy selenium stand alone server, apache server and poi jars into the Jars folder.
Launch eclipse and set the framework folder as workspace.
Create a Java project and in the java settings. Go to libraries tab Click on Add
External Jars and select all the jar file folder. Click on Add Library and select TestNG
library and click on finish.
39
Prathap Kumar
Each Module in the package is created as package in the project and the scenario
related to that module will be created as TestNG classes under the respective classes.
Each scenario will be one TestNG class and one test method to test the functionality.
Each module will have separate xml which can be used to execute scenarios of that
module.
The common functionalities which is Pre and Post condition like launching browser,
opening URL, Login, Logout and quitting the browser will be created before and after
method and before and after class in a separate TestNG class called base class. Each
automation scenario will extend this base class which will ensure pre and post
conditions are executed.
Base Class.java
package com.mindq.actitime.testbase;
import
import
import
import
org.testng.annotations.AfterClass;
org.testng.annotations.AfterMethod;
org.testng.annotations.BeforeClass;
org.testng.annotations.BeforeMethod;
40
Prathap Kumar
@AfterClass
public void quitBrowser() {
System.out.println("Quit Browser");
}
CreateCustomers.java
package com.mindq.actitime.tasks;
import org.testng.annotations.Test;
public class CreateCustomers {
@Test
public void testCreateCustomer() {
System.out.println("Create Customer");
}
}
DeleteCustomers.java
package com.mindq.actitime.tasks;
import org.testng.annotations.Test;
public class DeleteCustomers {
@Test
public void testDeleteCustomer() {
System.out.println("Delete Customer");
}
}
CreateReport.Java
package com.mindq.actitime.reports;
import org.testng.annotations.Test;
public class CreateReport {
@Test
public void testCreateReport() {
System.out.println("Create Report");
}
}
DeleteReport.java
package com.mindq.actitime.reports;
import org.testng.annotations.Test;
public class DeleteReport {
@Test
public void testDeleteReport() {
System.out.println("Delete Report");
}
}
41
Prathap Kumar
42