Test Automation Using Selenium Web Driver Java Preview
Test Automation Using Selenium Web Driver Java Preview
Navneesh Garg
Selenium WebDriver 2.0
Learn Automation on a
on Selenium
Selenium WebDriver
Step By Step Guide
Contents
About the Author ...................................................................................................... 9
Preface..................................................................................................................... 11
1. Introduction to Automation................................................................................ 15
1.1 What is Functional Automation?...........................................................................15
1.2 Why do we Automate?..........................................................................................16
1.3 When should we Automate? Economics of Automation........................................... 17
1.4 Commercial and Open Source Automation Tools.................................................18
2. Training Application Walkthrough...................................................................... 20
2.1 Training Application Walkthrough .......................................................................20
3 . Planning before Automation............................................................................... 26
3.1 Pre-requisites Before you Start Recording..............................................................26
3.2 Test Automation Process .......................................................................................30
4. Introduction to Selenium..................................................................................... 32
4.1 Seleniums Tool Suite.............................................................................................32
4.2 How to Choose the Right Selenium Tool for your need.......................................36
4.3 Installation Requirements for Selenium ................................................................38
5. Installing Selenium Components......................................................................... 39
5.1 Installing Selenium IDE........................................................................................39
5.2 Installing Firebug plug-in......................................................................................42
5.3 Installing the FirePath ..........................................................................................46
5.4 Installing Java Development Kit............................................................................50
5.5 Installing and Configuring Eclipse.........................................................................53
5.6 Installing WinANT...............................................................................................57
Contents
Contents
10
Preface
My motivation for writing this book stems from my hands-on experience in the IT and
testing domain and the experience I have gained as an automation consultant working in
numerous complex automation projects.
Selenium, being an open source tool, is gaining huge popularity but still is not conceived
as an easy to use tool especially by testers due to a variety of reasons, including tool setup,
programming background and support issues. A key objective of this book is showcase
in a simple guided way how to use Selenium WebDriver so that we can attain maximum
return on investment from using the tool. Not only will we learn how to use the tool but
also how to effectively create maintainable frameworks using Selenium.
In my previous book Test Automation using HP Unified Functional Testing we had
taken a similar step by step guided approach using commercial tool HP UFT which has
been excellently received by the testing fraternity.
Scope of Topics
As part of the scope of this book we will cover Selenium WebDriver (Selenium 2.0) with
Java as a programming language. We will also cover how to use Selenium IDE which is a
Firefox based Selenium Plug-in for easy record and replay.
We will be using Eclipse as the main IDE for creating Selenium WebDriver tests.
No prior knowledge of Java language is required for this book but having understanding
of object oriented programming language concepts will definitely help. As part of this book
we will be covering Basics of Java which would be required to use Selenium WebDriver
for beginner users.
In the later section we also show how to configure and use Selenium Grid to run parallel
tests on multiple browsers and OS configurations.
As part of reporting frameworks, the book will show how to configure and use both custom
JUnit and TestNG reports.
We will also see how Selenium WebDriver integrates with continuous Integration tools
like Jenkins.
11
My intent in this book is to discuss the key features of Selenium WebDriver, WebDriver
methods and cover all crucial aspects of the tool which help to create effective automation
frameworks.
The book does not have samples or examples on how to use Selenium WebDriver with
Python, C# and Ruby languages. The book focuses on using Selenium WebDriver with
Java language.
Key Audience
The target audience for this book are manual functional testers who want to learn Selenium
WebDriver quickly and who want to create effective automation frameworks that generate
positive ROIs to stakeholders.
Preface
The sample application used in the book can be accessed at the following URL:
www.adactin.com/HotelApp/
The source code used in the book can be found at the following link
www.adactin.com/store/
Acknowledgements
I would like to thank my family (my parents, my wife Sapna, my wonderful kids Shaurya
and Adaa) for their continued support. Without them this book would not have been
possible.
Special thanks to Emily Jones and William B. for their reviews and feedback, which
immensely helped as I worked on this book.
I would also like to thank my colleagues and clients for the inspiration, knowledge and
learning opportunities provided.
13
14
Introduction to Automation
Introduction
In this chapter we will talk about automation fundamentals and understand what
automation is and the need for automation. An important objective of this chapter is
to understand the economics of automation, and determine when we should carry out
automation in our projects. We will also discuss some popular commercial and open source
automation tools available in the market.
Key objectives:
What is automation?
Why automate? What are the benefits of automation?
Economics of automation
Commercial and Open Source automation tools
15
16
Introduction to Automation
17
Automate if:
Cost of automation is lower than the manual execution of those scripts.
The key idea here is to plan for the cost of script maintenance. I have seen a lot of automation
projects fail because project managers did not plan for the labor costs involved in script
maintenance.
Example
Let me give you an example from my personal experience.
I performed some automation work for one of our investment banking clients. We had
a five-member team, which automated almost 3000 test cases in about six months time,
which included around total 30 man months of effort. At the end of project, we gave the
clients testing team a hand-over of the entire automation suite created by our team. Our
recommendation to them was that they would need at least a one or two member team
to continuously maintain the scripts. This was because there were still functional changes
happening to the application and scripts would need maintenance. But since the client
project manager had no budget allocated for this activity; they skipped this advice and
continued to execute automation scripts. After the first six months of the 3000 test cases,
only 2000 test cases were passing, while the rest started failing. These scripts failures were
because script fixes were needed due to application changes. The client team was okay with
that and continued to execute those 2000 working test cases, and got rid of the remaining
1000 test cases, which were now executed manually. After another six months, only scripts
corresponding to 1000 test cases were passing. So they got rid of another 1000 test cases
and started executing them manually. After another six months (1.5 years in total), all the
scripts were failing, and testing had to move back to manual functional testing.
In the above real-life scenario, the cost of automation and its benefits could have been
reaped, if the client had allocated 1-2 automation testers (could have been part-time) to
maintain the scripts and had properly planned and budgeted for it.
Tool
Details
OpenSource
(free)
Selenium
18
Introduction to Automation
OpenSource
(free)
Watir
HP
Unified Functional
Testing
IBM
Rational Functional
Tester
Microfocus
SilkTest
Microsoft
VSTP
Coded UI tests
SmartBear
TestComplete
19
Introduction to Selenium
Introducing Selenium
Selenium is an Open Source tool for automating browser-based applications. Selenium is
a set of different software tools, each with a different approach to support test automation.
The tests can be written as HTML tables or coded in a number of popular programming
languages and can be run directly in most modern Web browsers. Selenium can be
deployed on Windows, Linux, and Macintosh and many OS for mobile applications like
iOS, Windows Mobile, and Android.
Among all Open Source tools, Selenium functional testing tool is considered to be a highly
portable software testing framework and one of the best tools available in the current
market for automation of Web applications.
Key objectives:
1. Understand Selenium Tool Suite
2. Choosing right Selenium Tool for use
3. Requirements for Selenium Setup
32
Introduction to Selenium
In the section below we will understand more about each of these components.
1. Selenium IDE
Selenium IDE (Integrated Development Environment) is a prototyping tool for building
test scripts. It comes as a Firefox plug-in and provides an easy-to-use interface for developing
automated tests. Selenium IDE has a recording feature, which records user actions as they
are performed and then exports them as a reusable script in one of many programming
languages for execution later.
Selenium IDE is simply intended to be a rapid prototyping tool. Selenium IDE has a
Save feature that allows users to keep the tests in a table-based format for later import
and execution. Selenium IDE doesnt provide iteration or conditional statements for test
scripts. Use Selenium IDE for basic automation. Selenium developers usually recommend
Selenium 2 or Selenium 1 to be used for serious, robust test automation.
2. Selenium 1- Selenium RC or Remote Control
Selenium RC is the main Selenium project allowing user actions to be simulated in a
browser like clicking a UI element, input data, etc. It executes the user commands in the
browser by injecting Java script functions to the browser when the browser is loaded. As we
know, Java Script has its own limitations and so does Selenium RC.
33
Key objectives:
1. Setup Instructions for installing Selenium IDE
2. Setup Instructions to install add-on Firebug
3. Setup Instructions to install add-on Firepath
4. Setup Instructions to install Java Development toolkit
5. Setup Instructions to install and setup Eclipse
6. Setup Instructions to install WinANT
39
3. Firefox will protect you from installing add-ons from unfamiliar locations, so you
will need to click Allow to proceed with the installation
4. Add-on will get downloaded and you will see Software Installation pop-up. Click
on Install Now
40
5. Firefox will show restart dialog to restart Firefox. Click on Restart Now
6. After Firefox reboots you will find the Selenium-IDE listed under the Firefox Tools
menu. Go to Tools Selenium IDE
42
43
Key objectives:
Exporting Selenium IDE script as a Java Selenium WebDriver script
Configuration of project structure in Eclipse and use Selenium WebDriver script
Running of Selenium WebDriver script
131
i.
Note: We will focus on Selenium WebDriver with Java but as you can see
Selenium supports export as C#, Python and Ruby languages as well.
2. Save it as MyFirstWebDriverTest in C:\Selenium Folder. You will notice that the
script is saved as MyFirstWebDriverTest.java file
3. Try to open the script you have saved in an editor like NotePad++ (you can download
this freely from internet)
133
134
Description
Let the method fail. Might be used to
check that a certain part of the code is
not reached. Or to have a failing test
before the test code is implemented. The
String parameter is optional.
Checks that the boolean condition is
true.
Checks that the boolean condition is
false.
Tests that two values are the same. Note:
for arrays the reference is checked, not
the content of the arrays.
Test that float or double values match.
The tolerance is the number of decimals
which must be the same.
Checks that the object is null.
Checks that the object is not null.
Checks that both variables refer to the
same object.
Checks that both variables refer to
different objects.
Let us see an example where we had earlier used the Assert statement.
1. Go to your Selenium IDE and make sure script IDEVerificationScript is Open
If you notice a new statement, assertTrue has been added which validates that the logout
link is present.
174
14
Using Functions
Functions help divide your test into logical units, such as areas of key functionalities of
the application. Functions help make our scripts modular and reusable, which will save
us maintenance effort and also help us improve productivity. These functions can then be
re-used in different scripts.
For example, all of our scripts will have to login to the application. Now, instead of
recording login steps repeatedly in every script, we can keep an external login function and
re-use that function in all of our scripts.
Example
Let us see another practical example here:
At one of our client engagements, we were automating an investment banking application.
As a first step of every test case, we had to create investment instruments after which we
had to validate, and add details in later steps (we had more than 100 test cases for each
instrument type). Creating an instrument was a tedious step with up to 50 field values to
be entered. Based on the test scenario, input data would change. Now recording the steps
of investment instrument creation in each and every script would have been a nightmare
and time consuming. It would have also been a maintenance issue, if in later development
stages the application workflow is changed or new fields were added.
So we created functions to create instruments and for each of the test cases that were
automated, we just invoked the same function in every script. This helped us reduce
the overall time to automate. This also assisted in maintenance down the line, when the
investment instrument creation workflow changed.
Key objectives:
Create Functions
Calling Functions in WebDriver script
191
2. Create Function definition and import any required Java libraries in the class
3. Add steps to functions based on functions objective
4. Replace any data within functions with arguments from that function
5. Within the script, import Functions Package and Extend class to use function
within your scripts
Pre-conditions
1. Select HotelApp_TestAutomation/src folder, right click and select New Package
192
Using Functions
2. In Java Package dialog enter the Name functions and click Finish
22
This is followed by a catch block of code where we tell the system what should be done
when the exception occurs. Generally this is where we display the message of the exception
object so that we know which exception has occurred and why.
272
You see in the above snapshot the value for locator id is username_show
3. Add this to our SharedUIMap.properties file for further use
driver.findElement(By.xpath(prop.getProperty(Txt_Login_Username))).
driver.findElement(By.xpath(prop.getProperty(Txt_Login_Username))).
sendKeys(sUserName);
// Provide Password.
driver.findElement(By.id(prop.getProperty(Txt_Login_Password))).clear();
274
driver.findElement(By.id(prop.getProperty(Txt_Login_Password))).
23
Reporting in Selenium
One of the very important features of a test automation solution is its reporting structure.
After test execution we inspect the test report for results and defect detection. Selenium
does not have its own mechanism for reporting results. Rather, it allows the automation
tester to build their own reporting structure, customized to their needs, using features of
the programming language of your choice.
As part of this section, we are going to try to understand Test Framework Reporting tools
Key objectives:
Test Framework Reporting Tools
Configuring Junit HTML Report
Configuring TestNG reports
Custom Excel or Database reports
282
Reporting in Selenium
283
25
About Jenkins
Jenkins is a popular continuous integration server in the Java development community. It is
derived from the Hudson CI server. It supports configuration management tools including
CVS, Subversion, Git, Mercurial, Perforce, and ClearCase, and can execute Apache Ant
and Apache Maven based projects as well as arbitrary shell scripts and Windows batch
commands.
Jenkins can be deployed to set up an automated testing environment where you can
runSelenium WebDriver tests unattended based on a defined schedule, or every time
changes are submitted in configuration.
Key objectives:
Install Jenkins tool
Jenkins Configuration
Run Jenkins with ANT
Scheduling Auto-Runs
319
320
27
Selenium Functions,
Common Questions and Tips
In this chapter we will try to address a few of the important selenium functions and other
common questions and tips that can be used in Selenium.
Key objectives:
How to use JavaScript?
How to take a Screen Shot?
How to use Keyboard or Mouse movements?
How to read row, columns and cells data from a table?
Working with multiple browsers
How to maximize the Browser window
Checking an Elements Presence
Checking an Elements Status
Working with drop-down lists
Working with Radio buttons and groups
Working with Checkboxes
Measuring Response time for performance testing using timer
Xpath and Properties finder in IE and Chrome browsers
How to use WebDriver test remotely using Selenium Grid?
343
Example
Below code executes javascript and returns the Web page title
JavascriptExecutor js = (JavascriptExecutor) driver;
// returns Web page title
String title = (String) js.executeScript(return document.title);
//returns handle to Webelement with id myid
WebElement element = (WebElement)js.executeScript(return document.
getElementById(myid));
You need to return from your Javascript snippet to return a value, so:
js.executeScript(document.title);
will return null, but:
js.executeScript(return document.title);
will return the title of the document.
Note: Based on the type of return value, we need to cast the executeScript()
method. For decimal values, Double can be used, for non-decimal numeric
values Long can be used, and for Boolean values Boolean can be used.
Example
Below code will return the count of combo boxes on the Search Hotel Page
344