Seleniumbook Prathap

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 42

Prathap Kumar

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.2 Disadvantages of Manual Testing

 Manual tests can be very time consuming


 For every release you must rerun the same set of tests which can be time consuming.
 Requires heavy investment.
 Requires more number of human resources

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 Disadvantages of Automation Testing


Proficiency is required to write the automation test scripts.
Debugging the test script is major issue. If any error is present in the test script, sometimes it
may lead to deadly consequences.
Test maintenance is costly in case of playback methods. Even though a minor change occurs in
the GUI, the test script has to be rerecorded or replaced by a new test script.
Maintenance of test data files is difficult, if the test script tests more screens.

1.6 Functional Testing tools

Functional Testing Tools


Open Source Commercial
Selenium-1.0 QTP
Web driver 2.0 Test Partner
Sahi Test complete
Bad Boy RFT
Ruby Silk
Watir

1.7 Selenium vs. QTP

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.2 History of selenium

 In 2004 invented by Jason Huggins and team


 Originally name is JavaScript Functional Tester (JSFT)
 Open source browser based integration framework built originally by Thought Works
 100% JavaScript and HTML
 Web Testing Tool
 That supports testing web 2.0 applications
 Supports for cross –Browser testing (On Multiple browsers)
 Supports multiple operating systems

2.3 Selenium Components

 Selenium IDE (Integrated Development Environment) - Record & Play back


 Selenium Core –Runs the test suits on the web server where the web application is deployed
 Selenium RC 1.0 – Server /Client (Selenium. Start /Selenium. Stop)
 Selenium Grid – Performance Tool
 Selenium 2.0 (Known as selenium Web Driver)

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

 Click on the Allow pop up and the following window appears.

 Click on Install Now button

6
Prathap Kumar
 Restart Firefox
 Navigate to -> tools option here we can find IDE

7
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

2.8 Challenges in Selenium IDE.


 How to record a simple test case.
 How to prepare a test suite.
 How to run a test case and a test suite.
 Data Base connectivity links.
 How to write the scripts on your own.
 How to run from the middle of the script.
 How to insert the statements in the middle of the scripts.

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.

3. Requirements of Selenium Webdriver.


3.1 HTML
To start automating any web application it is required to have a web application. This topic explains how to
create a small webpage in our own machine.

Let is create a web page which has the following elements in it.

i. User name Text box.


ii. Password Text box.
iii. Login button.
iv. Reports check box.
v. Two radio buttons- Male and female.
vi. One link named google – If link is clicked it should redirect to Google page.
vii. One image.
viii. One image with the link – If clicked on the image it should
redirect to flipkart.
ix. Single select drop down.
x. Multi-select drop down.
xi. Text area.
xii. Browse button.

The page should appear as follows.

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>

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>

10
Prathap Kumar
<td><input type="radio" name="gender" id="male"/> Male</td>

</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="">

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>

<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.

Mandatory Additional
Sl.no Element HTML Tag Property Value property Value
1 Text box input type text Name/ID User defined

2 Password Box input type password Name/ID User defined


3 Button input type submit/button Name/ID User defined
4 Checkbox input type checkbox Name/ID User defined
Name and
5 Radio button input type radio ID User defined
6 Link a href internal/external
path of the
7 Image img src image
Single select
8 Combo Box select 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.

There are 8 different element locators. They are as follows.

1. ID.
2. Name.
3. Link text.
4. CSS Selectors.
5. XPath.
6. Partial Link text.
7. Class name
8. Tag name.

4.1 Element identification in selenium.


If any element has name or id property we can use the value of id or name property to identify the
element. If the element is a link we can use the link text to identify it. If the element does not have id or
name property and if it is not a link then we need to write either Css selector or Xpath expression.

Elements are generally identified by its html tag, its properties and values. To identify an element, we
should be able to inspect the html source of the element. By default each browser provides an inspector
tool.

F-12 Inspect element in all browser.

On Mozilla firefox we generally do not use the default inspector, we use and add-on called firebug.

Steps to install 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.

4.2 Element identification using Css selectors:


Css selectors can be used to identify the elements which don’t 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

4.3 Element identification using Xpath:

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.

4.3.1 X-path position (absolute Xpath):

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()

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:

16
Prathap Kumar
//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
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:

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

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

 Java client driver


 IDE

Java client driver can be downloaded from

http://code.google.com/p/selenium/downloas/list

And the file name is

selenium –server-standalone-2.35.0.jar

The version changes based on

1.Firefox version update


2.Enhancement or bugfixes

Create a folder in the hard disk, launch eclipse and set the folder as works space.

Create a new java project in eclipse

Under the project source folder, create a new package

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

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”);

5.1 Checkpoints verification in automation:

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().

WebDriver driver=new FirefoxDriver();


driver.get("http://demo.actitime.com");
String expectedTitle="actiTIME - Login";
String actualTitle=driver.getTitle();
//System.out.println(expectedTitle);
if (actualTitle.equals(expectedTitle)) {
System.out.println("Pass");
}else{
System.out.println("fail");
}

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();

Any html tag is a web element in selenium

WebDriver driver=new FirefoxDriver();


driver.get("http://demo.actitime.com");
driver.findElement(By.id("username")).sendKeys("admin");
driver.findElement(By.name("pwd")).sendKeys("manager");
driver.findElement(By.linkText("Login")).click();
Thread.sleep(10000);
String expectedText=driver.findElement(By.xpath("//td[text()='Enter Time-Track']")).getText();
//System.out.println(expectedText);
String actualText="Enter Time-Track";
if (expectedText.equals(actualText)) {
System.out.println("Pass");
}else{

20
Prathap Kumar
System.out.println("fail");
}

5.2 Element Check points


How do you know whether a checkbox is selected or not.

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.

WebDriver driver=new FirefoxDriver();


driver.get("file:///C:/Users/pratap/Desktop/Batch19/mypage.html");
//find the status of the check box
boolean chkBoxStatus=driver.findElement(By.name("Rep")).isSelected();
System.out.println(chkBoxStatus);
// click on the check box
driver.findElement(By.name("Rep")).click();
//find the status after clicking on the checkbox
boolean chkBoxStatus1=driver.findElement(By.name("Rep")).isSelected();
System.out.println(chkBoxStatus1);
driver.findElement(By.name("Rep")).click();
//find the status after clicking on the checkbox
boolean chkBoxStatus2=driver.findElement(By.name("Rep")).isSelected();
System.out.println(chkBoxStatus2);

Output:
false
true
false

How do you know whether a radio button is selected or not.

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.

WebDriver driver=new FirefoxDriver();


driver.get("file:///C:/Users/pratap/Desktop/Batch19/mypage.html");
boolean radioStatus=driver.findElement(By.id("male")).isSelected();
System.out.println(radioStatus);
driver.findElement(By.id("male")).click();
boolean radioStatus1=driver.findElement(By.id("male")).isSelected();
System.out.println(radioStatus1);
driver.findElement(By.id("male")).click();
boolean radioStatus2=driver.findElement(By.id("male")).isSelected();
System.out.println(radioStatus2);

Output:
false
true
true

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. Select an option or select multiple options.


2. Deselect options from multi select list box.
3. Get all available option.
4. Get all selected option from list box
1. To select an option from single select combo box or to select multiple options from list box select class
provides 3 different methods.
1. selectByindex()
2. selectByValue()
3. selectByVisibleText()
1) Select by index takes an integer element which is zero based index of the option to be selected. By
default each option tag will have an index starting from zero.
2) Select by value takes a string argument which is value of the attributes of the option tag.
3) Select be visible text takes a string argument which is text of option tag to select.

In multi select list box the same method will be used however, if we write select methods multiple times in
the code, it will select multiple options from the list box.

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");

22
Prathap Kumar
2. Deselecting options from multi select list box.

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);

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);
}
}

5.4 TO FIND THE VALUE ATRIBUTE OF AN ELEMENT

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.

WebDriver driver=new FirefoxDriver();

driver.get("http://demo.actitime.com");

String attValue=driver.findElement(By.id("username")).getAttribute("class");

System.out.println(attValue);

5.5 WORKING WITH MULTIPLE ELEMENTS:


Web driver provides a method findelements() which can be used to find multiple elements base on the
element locater.
Eg: To find all links in a page (count of link in a page)

WebDriver driver=new FirefoxDriver();


driver.get("http://www.flipkart.com/");
List<WebElement> allLinks=driver.findElements(By.xpath("//a"));
int k=allLinks.size();
System.out.println(k);
for (int i = 0; i < k; i++) {

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

WebDriver driver=new FirefoxDriver();


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 with 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.

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.

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);
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.

WebDriver driver=new FirefoxDriver();

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();

3) Java script alert confirmation pop-up


Java script pop-up

Alert Confirmation

Alert – has only one button i.e., ok


Confirmation - has more than one button i.e., ok and cancel.

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

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();

27
Prathap Kumar
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.

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);

28
Prathap Kumar
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://selenium-release.storage.googleapis.com/2.41/selenium-
java-2.41.0.zip']")).click();

Note: Don’t forget to set the preference in Firefox class which is done in common for each case.

Working with menu drop down:

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.

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.

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();

DRAG AND DROP:

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.

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");

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();

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%.

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:

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

HOW TO HANDLE UNTRUSTED CERIFICATES CONNECTION ISSUES.

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();");

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)

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();

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:

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
Prathap Kumar

The jar files required to work with Excel is

poi-3.9-20121203.jar
poi-ooxml-3.9-20121203.jar
poi-ooxml-schemas-3.9-20121203.jar

Under the folder ooxml-lib

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;

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();

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;

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;

}
}

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();

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;

public class Customer {

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

Creating testNG XML:


If we want to execute multiple testNG classes in a particular sequence then we need to create an xml.

PROCEDURE TO CREATE AN TESTING XML:

 Right click on the package  Run as testNG test.


 From the console output, copy the path of temp folder where testNG xml will be created.

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.

<suite name="Default suite">


<test verbose="2" name="Default test">
<classes>
<class name="DemoTestNg.Test1"/>
<class name="DemoTestNg.BasicTestNg"/>
</classes>
</test>
</suite>

Sequencing order of execution of Test Methods.


1) Using Priority
@Test annotation can be given priority and whichever the annotation has the least priority will get
executed first. Execution will follow ascending order of priority.
public class FirstClass {
@Test(priority=0)
public void testCreateCustomer() {
System.out.println("Executing create customer");
}
@Test(priority=1)
public void testEditCustomer() {
System.out.println("Executing Edit customer");
}
@Test(priority=2)
public void testModifyCustomer() {
System.out.println("Executing Modify customer");
}
@Test(priority=3)
public void testDeleteCustomer() {
System.out.println("Executing Delete customer");
}
}

2) Ignoring a test method in testing:

We can use enable=false to ignore a test method in testNG.

@Test(enabled=false)
public void testEditCustomer() {
System.out.println("Executing Edit customer");
}

38
Prathap Kumar

3) Sequencing execution order using dependsOnMethods.


dependsOnMethods can be use to sequence test methods and dependsOnMethods accept an array
of String which contains the list of methods which the test methods depends on.

public class FirstClass {


@Test
public void testcreateCustomer() {
System.out.println("Executing create customer");
}
@Test
public void testeditCustomer() {
System.out.println("Executing Edit customer");
}
@Test
public void testmodifyCustomer() {
System.out.println("Executing Modify customer");
}
@Test(dependsOnMethods={"testeditCustomer","testmodifyCustomer"})
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.

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");
}
}

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.

Launch eclipse and set the framework folder as workspace.’

Create a Java project and in the java settings. Go to libraries tab  Click on Add External Jars and select all
the jar file folder. Click on Add Library and select TestNG library and click on finish.

Each Module in the package is created as package in the project and the scenario related to that module
will be created as TestNG classes under the respective classes.

Each scenario will be one TestNG class and one test method to test the functionality. Each module will have
separate xml which can be used to execute scenarios of that module.

The common functionalities which is Pre and Post condition like launching browser, opening URL, Login,
Logout and quitting the browser will be created before and after method and before and after class in a
separate TestNG class called base class. Each automation scenario will extend this base class which will
ensure pre and post conditions are executed.

Base Class.java

package com.mindq.actitime.testbase;

import org.testng.annotations.AfterClass;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.BeforeMethod;

40
Prathap Kumar

public class BaseClass {


@BeforeClass
public void OpenBrowserURL() {
System.out.println("Open browser and url");
}
@BeforeMethod
public void Login() {
System.out.println("Login");
}
@AfterMethod
public void Logout() {
System.out.println("Logout");
}
@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");
}

41
Prathap Kumar
}

DeleteReport.java

package com.mindq.actitime.reports;

import org.testng.annotations.Test;

public class DeleteReport {


@Test
public void testDeleteReport() {
System.out.println("Delete Report");
}
}

42

You might also like