Professional Documents
Culture Documents
Seleniumbook Prathap
Seleniumbook Prathap
Seleniumbook Prathap
Table of Contents
1. Software Testing ...................................................................................................................................................... 2
1.1 What is mean by Testing?................................................................................................................................ 2
1.2 Disadvantages of Manual Testing .................................................................................................................... 2
1.3 Automation ...................................................................................................................................................... 2
1.4 Advantages: ..................................................................................................................................................... 2
1.5 Disadvantages of Automation Testing ............................................................................................................. 3
1.6 Functional Testing tools ................................................................................................................................... 3
1.7 Selenium vs. QTP ............................................................................................................................................. 3
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 Challenges in Selenium IDE.............................................................................................................................. 8
3. Requirements of Selenium Webdriver. ................................................................................................................... 9
3.1 HTML................................................................................................................................................................ 9
3.2 Java ................................................................................................................................................................ 13
4. Web Driver ............................................................................................................................................................. 13
4.1 Element identification in selenium. ............................................................................................................... 13
4.2 Element identification using Css selectors: ................................................................................................... 14
4.3 Element identification using Xpath: .............................................................................................................. 15
4.3.1 X-path position (absolute Xpath): .......................................................................................................... 15
4.3.2 Xpath Attributes(relative Xpath): .......................................................................................................... 16
5. WebDriver.............................................................................................................................................................. 18
5.1 Checkpoints verification in automation: ....................................................................................................... 20
5.2 Element Check points .................................................................................................................................... 21
5.3 WORKING WITH SELECT DROPDOWNS ......................................................................................................... 22
5.4 TO FIND THE VALUE ATRIBUTE OF AN ELEMENT .......................................................................................... 24
1
Prathap Kumar
5.5 WORKING WITH MULTIPLE ELEMENTS: ........................................................................................................ 24
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.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.
Selenium QTP
Open source Paid tool
Works on all OS (Windows, OS X, Linux, Solaris) Works on Windows
Tests only Web applications Tests web and desktop applications
Works on almost all browsers(IE, Firefox, Safari, Works on Firefox 3.5.x and IE
Opera)
Code can be made in any one of languages VB Script
such as Java, C#, Ruby, Python, pearl, php etc
Html ID, Xpath, CSS, DOM, Link text Object properties, Repository objects
There is no option, can record script in GUI Spy
Selenium IDE, can spy objects using IE
developer tool bar, Firebug and also using
http://saucelabs.com/builder
IDE sometimes does not record some events Recording is a little reliable
3
Prathap Kumar
Set of Libraries, around 20MB (Need to include Around 1.5GB
other supporting software)
Saucelabs.com, Element34 , Commercial From HP
Support
2. 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
It’s an easy –to-use
It’s 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...
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
4
Prathap Kumar
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.
5
Prathap Kumar
6
Prathap Kumar
Restart Firefox
Navigate to -> tools option here we can find IDE
7
Prathap Kumar
2.7 Recording
8
Prathap Kumar
How to verify the text on the pop up.
Difference between verify and assert.
Why Selenium IDE is using in industries still.
Converting of code.
Purpose of all the buttons.
Align the test cases in test suite.
Aligning of statements in script.
Let is create a web page which has the following elements in it.
9
Prathap Kumar
This is the required web page. The HTML code should be as follows.
<html>
<head>
<title>Welcome to html</title>
</head>
<body>
<table >
<tr>
10
Prathap Kumar
<td><input type="radio" name="gender" id="male"/> Male</td>
</tr>
</table>
<table >
<tr>
</tr>
</table>
<table >
<tr>
<td><img src="mobile.jpg"/></td>
</tr>
<tr>
<img src="flip.jpg"/></a></td>
</tr>
</table>
<table>
<tr>
<td><select name="city">
<option value="1">Bangalore</option>
<option value="2">Chennai</option>
<option value="3">Kolkatta</option>
<option value="4">Delhi</option>
</select></td>
11
Prathap Kumar
<option value="1">Bangalore</option>
<option value="2">Chennai</option>
<option value="3">Kolkatta</option>
<option value="4">Delhi</option>
</select></td>
</tr>
</table>
<table >
<tr>
<td><textarea name="description"></textarea></td>
</tr>
</table>
</body>
</html>
Write the above code in Note pad and save as filename.html. Double click on the file where it is saved. The required
html is obtained.
Mandatory Additional
Sl.no Element HTML Tag Property Value property Value
1 Text box input type text Name/ID User defined
12
Prathap Kumar
Multi Select
9 Combo Box select multiple TRUE Name/ID User defined
10 Text area textarea Name/ID User defined
11 File Browser input type file Name/ID User defined
3.2 Java
4. Web Driver
There are only two actions performed in any automation tool.
i. Element identification
ii. Performing action on the particular element.
1. ID.
2. Name.
3. Link text.
4. CSS Selectors.
5. XPath.
6. Partial Link text.
7. Class name
8. Tag name.
Elements are generally identified by its html tag, its properties and values. To identify an element, we
should be able to inspect the html source of the element. By default each browser provides an inspector
tool.
On Mozilla firefox we generally do not use the default inspector, we use and add-on called firebug.
13
Prathap Kumar
In google type firebug. Click on firebug. Add-ons for firefox. In the add-ons page click on the button
add to firefox which will download the add-on and throw a pop up.
HTML source:
<input type=”submit” value=”login”/>
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.
14
Prathap Kumar
To identify elements in the web page, we can use Xpath expression. There are two categories of X-path.
They are Xpath-position and X-path attributes.
To identify an element by its position in html hierarchy we can use Xpath position.
Example: For the above html page, if we want to find out the Xpath for username text box. Then the Xpath will be.
html/body/input[1]
Xpath position is nothing but finding out the exact position of the element in the html page. This is applicable for
small web pages which are constant.
If the Html structure is
<html>
<Body>
<table>
<tbody>
<tr>
<td>
<input>
</td>
</tr>
</tbody>
</table>
</body>
</html>
The Absolute Xpath Would be
Html/body/table/tbody/tr/td/input
15
Prathap Kumar
4.3.2 Xpath Attributes(relative Xpath):
a) Attributes
Identifying an element using its set of attributes and values is called Xpath attributes.
The Syntax is
//html tag*@attribute=’value’+
Example 1:
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()
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:
16
Prathap Kumar
//html tag*contains(@attribute,’value’)+
Example:
//input*contains(@id,’fema’)+
To identify dynamic elements using Xpath we can take the help of dependent and independent concepts.
Independent elements generally will be unique elements based on which all the action are performed.
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:
17
Prathap Kumar
1) //tr[td[a[text()='Bing']]]/td[3]/input
2) //div[div[div[div[a[contains(text(),'Ophelia and the Marvellous Boy (Paperback)')]]]]]/div[2]/div[1]/div[3]/a
5. WebDriver
Web driver is an automation tool which can be used to automate web applications which have DOM
structure.
Requirements
http://code.google.com/p/selenium/downloas/list
selenium –server-standalone-2.35.0.jar
Create a folder in the hard disk, launch eclipse and set the folder as works space.
Create a java class with public static void main() to launch firefox browser, the code is web driver
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.
18
Prathap Kumar
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;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
To identify the element webdriver provide a method called findelement() which takes an argument of By
class which has eight element locators.
WebElement un=driver.findElement(By.id("username"));
un.sendKeys("admin");
OR
19
Prathap Kumar
driver.find element (by name (“username”).sendkeys(“admin”);
Every single point under the expected column in manual test case should be present as a checkpoint in the
automation test script. Selenium recommends 3 different checkpoints
1) Title
2) Text
3) Element
Title checkpoints
Comparing the expected title with the actual title from the application.To get the actual title we can use
driver.getTitle().
2) Text checkpoint
Text checkpoint can be used to compare any text on the application page
Text will generally be inside an html tag (span, td, div, p, b). To get the text we have to find the element and
use the method getText();
20
Prathap Kumar
System.out.println("fail");
}
We can use the driverfindElement() to find the checkbox and use the method isselected() which will return
a boolean, if true checkbox is selected and false if checkbox is unselected.
Output:
false
true
false
We can use the driverfind() element to find the radio button and use the method isselected() which will
return a boolean, if true radio button is selected and false if radio button is unselected.
Output:
false
true
true
21
Prathap Kumar
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.
Multi select:
22
Prathap Kumar
2. Deselecting options from multi select list box.
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).
23
Prathap Kumar
dd.selectByIndex(2);
Thread.sleep(5000);
dd.selectByValue("4");
Thread.sleep(5000);
dd.selectByVisibleText("Chennai");
Thread.sleep(5000);
//dd.deselectAll();
List<WebElement> allOptions=dd.getAllSelectedOptions();
int k=allOptions.size();
System.out.println(k);
for (int i = 0; i < k; i++) {
WebElement option=allOptions.get(i);
String text=option.getText();
System.out.println(text);
}
}
We can use driver.findElement() to find element and use the method getAttribute() and pass the attribute
name as an argument which will return the value of the attribute.
driver.get("http://demo.actitime.com");
String attValue=driver.findElement(By.id("username")).getAttribute("class");
System.out.println(attValue);
24
Prathap Kumar
WebElement link=allLinks.get(i);
String text=link.getText();
System.out.println(text);
}
Find number of check boxes in a page and check all check boxes.
To find number of checkboxes in a page we can use driver.findelements() and the elements locater either
xpath or css selection
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.
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 with in
the duration, it will try to perform the action and if the element is found it will throw an exception
NoSuchElementException
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
25
Prathap Kumar
4. Page on load authentication pop up.
5. File download
6. File download.
7. New browser pop up/New tab/Light box or Model window.
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);
driver.get("http://www.flipkart.com/samsung-galaxy-s-duos-2-
s7582/p/itmdqzpfvmmzzxme?pid=MOBDQZPYAZSDKBWH&srno=b_1&ref=930dfd23-203e-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.
26
Prathap Kumar
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();
Alert Confirmation
Java script alert or confirmation cannot be handled by driver.findElement() as it does not have any
html structure. Java script alert is generated from alert() of java script and has one button ‘ok’ and is used
to provide the user some information.
Confirmation pop-up is generated from confirm() method of javascript and has two buttons, ok and
cancel and based on the inputs executes action.
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
Alert alt=driver.switchTo().alert();
String alertText=alt.getText();
27
Prathap Kumar
System.out.println(alertText);
//driver.switchTo().alert().accept();
alt.dismiss();
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");
To save a file to disk automatically without the pop-up, we can take help of Firefox preferences by using
Firefox profile.
Case 1:
To save the file to the downloads folder, we can use the preference
browser.helperApps.neverAsk.saveToDisk and provide the file MIME type as a value for the preference i.e.,
application/zip. If there are multiple files types to be download we can provide (,) separated list of MIME
types of all the files.
Case 2:
By default the value for browser.download.folderList will be 1 which represents download folder.
28
Prathap Kumar
Case 3:
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.
Note: Don’t forget to set the preference in Firefox class which is done in common for each case.
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 sub-menu links is visible and web driver can find the sub menu
items.
We can use moveToElement() and pass parent menu as an argument which will stimulate the drop down
menu.
The right click menu is called context menu. We can use the Actions class ContextClick() to perform
right click.
We can use sendKeys() of Actions class to send any key. We can also use sendkeys() for Web
Element to send any key. Keys enumerator provides all the keys of the key board and can be used to
sendKeys() like tab, control, alt, shift.
29
Prathap Kumar
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/india-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/ho
me'])[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();
We can use the dragAndDrop() of Action class which takes two arguments source and target.
IDENTIFYING SOURCE:
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.
BROWSER ACTIONS:
30
Prathap Kumar
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();
System.setProperty("webdriver.ie.driver",
"D:\\Seleniumprogs\\workspace\\Batch18web\\IEDriverServer.exe");
WebDriver driver=new InternetExplorerDriver();
Requirements.
Go to section – Third party browser driver, click on download page against chrome. Download
chromedriver.exe. In eclipse write the following code.
System.setProperty("webdriver.chrome.driver",
"D:\\Seleniumprogs\\workspace\\Batch18web\\chromedriver.exe");
WebDriver driver=new ChromeDriver();
Untrusted connection:
31
Prathap Kumar
Firefox automatically handles untrusted connection. Change the system time to 2 years back and open a
secures site like www.gmail.com
By default, Google chrome and Firefox automatically handles untrusted connection issues. However
internet explorer doesn’t 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();");
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)
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)
32
Prathap Kumar
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();
Right click on the element in Firefox in the context menu, if it shows This frame which means the
element is inside the frame.
Excel Library:
Requirements:
Apache poi
Go to the binary distribution section click on the link poi-bin-3.9.20122013.zip which will navigate to a
page with the links called download. Click on the first link to download apache poi.
33
Prathap Kumar
poi-3.9-20121203.jar
poi-ooxml-3.9-20121203.jar
poi-ooxml-schemas-3.9-20121203.jar
dom4j-1.6.1.jar
xmlbeans-2.3.0.jar
Program:
package driverPackage;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
34
Prathap Kumar
} catch (InvalidFormatException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return dataText;
} 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;
}
}
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;
35
Prathap Kumar
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.
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 org.testng.annotations.AfterClass;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
36
Prathap Kumar
@BeforeClass
public void OpenUrl() {
System.out.println("AOpenUrl");
}
@BeforeMethod
public void Login() {
System.out.println("ALogin");
}
@Test
public void createCustomer() {
System.out.println("AcreateCustomer");
}
@Test
public void editCustomer() {
System.out.println("AeditCustomer");
}
@Test(enabled=false)
public void deleteCustomer() {
System.out.println("AdeleteCustomer");
}
@AfterMethod
public void Logout() {
System.out.println("ALogout");
}
@AfterClass
public void closeUrl() {
System.out.println("AcloseUrl");
}
}
Output:
AOpenUrl
ALogin
AcreateCustomer
ALogout
ALogin
AeditCustomer
ALogout
AcloseUrl
37
Prathap Kumar
Each time an individual testing class or a package is executed testing creates an xml in the temp folder.
Paste the path in windows explorer to open the folder where xml created.
Copy the xml file. In eclplise Right click on the project and paste it.
@Test(enabled=false)
public void testEditCustomer() {
System.out.println("Executing Edit customer");
}
38
Prathap Kumar
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.
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");
}
}
39
Prathap Kumar
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.
Create a Java project and in the java settings. Go to libraries tab Click on Add External Jars and select all
the jar file folder. Click on Add Library and select TestNG library and click on finish.
Each Module in the package is created as package in the project and the scenario related to that module
will be created as TestNG classes under the respective classes.
Each scenario will be one TestNG class and one test method to test the functionality. Each module will have
separate xml which can be used to execute scenarios of that module.
The common functionalities which is Pre and Post condition like launching browser, opening URL, Login,
Logout and quitting the browser will be created before and after method and before and after class in a
separate TestNG class called base class. Each automation scenario will extend this base class which will
ensure pre and post conditions are executed.
Base Class.java
package com.mindq.actitime.testbase;
import org.testng.annotations.AfterClass;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.BeforeMethod;
40
Prathap Kumar
CreateCustomers.java
package com.mindq.actitime.tasks;
import org.testng.annotations.Test;
DeleteCustomers.java
package com.mindq.actitime.tasks;
import org.testng.annotations.Test;
CreateReport.Java
package com.mindq.actitime.reports;
import org.testng.annotations.Test;
41
Prathap Kumar
}
DeleteReport.java
package com.mindq.actitime.reports;
import org.testng.annotations.Test;
42