Test Automation Using Selenium Webdriver With Java: Navneesh Garg
Test Automation Using Selenium Webdriver With Java: Navneesh Garg
Navneesh Garg
• Selenium WebDriver 2.0
• Learn Automation on a
Web Based Application
Selenium WebDriver
Step By Step Guide
All rights reserved. No part of this publication may be reproduced, stored in a
retrieval system or transmitted in any form or by any means, electronic, mechanical,
photocopying, recording, scanning, or otherwise without either the prior written
permission of the author or authorization through payment of the appropriate per-copy
fee to the Author. For permission please contact author at adactin.com/contact.html.
By Navneesh Garg
ISBN - 978-0-9922935-1-2
This document also contains registered trademarks, trademarks and service marks that are owned by
their respective companies or organizations. The publisher and the author disclaim any responsibility
for specifying which marks are owned by which companies or organizations.
2
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 Selenium’s 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
3
Test Automation Using Selenium WebDriver with Java
4
Contents
5
Test Automation Using Selenium WebDriver with Java
6
Contents
7
8
About the Author
Navneesh Garg
Navneesh Garg is a recognized test automation architect and corporate trainer, specializing
in test automation, performance testing, security testing and test management. As a tool
specialist, he has worked on a variety of functional automation tools including Selenium,
HP QTP/UFT, TestComplete, TestPartner, SilkTest, Watir, RFT, and on varied technologies
including Web, Java, Dot-net, SAP, Peoplesoft and Seibel.
His previous book “Test Automation using Unified Functional Testing” is among the
bestselling books on HP QTP. This book has consistently ranked among the top 100
testing books on Amazon. It was the first book to be released globally on the latest version
of HP QTP.
He is an entrepreneur and founder of several successful IT companies which encompass
the AdactIn Group, CresTech Software, and Planios Technologies.
As an experienced corporate trainer, he has trained professionals in Selenium and other
test tools across a wide range of global clients such as Macquarie Bank, Corporate Express,
Max New York Life, Accenture, NSW Road and Maritime Services, Australian Dept of
Education, HCL Technologies, Sapient, Fidelity Group, Adobe Systems, and many more.
He has training experience in diverse geographies such as Australia, India, Hong Kong and
USA.
As a technical test delivery head for his company, he has led and managed functional
automation testing and performance testing teams across a wide range of domains, using
commercial tools and open source tools. Certified in HP QTP, HP Quality Center, HP
LoadRunner, IBM Rational Functional Tester and as a Certified Ethical Hacker, he has
designed several high-end automation frameworks including using Selenium and its
integrations with tools like TestNG, JUnit, Selenium Grid, Jenkins and ANT.
9
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
Test Automation Using Selenium WebDriver with Java
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.
12
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
1
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
Test Automation Using Selenium WebDriver with Java
16
Introduction to Automation
17
Test Automation Using Selenium WebDriver with Java
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
client’s 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.
18
Introduction to Automation
19
4
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 doesn’t 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
5
Installing Selenium Components
Introduction
Before we can start using Selenium, there are a few Selenium and non-Selenium components
that we need to install. In this chapter we will perform step by step installation and setup
of the components which we will need to use over the scope of this book.
Note: You need access to the internet to download the required setup files.
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
Note: The version of the link is constantly being updated. Click on the
latest link available at the time you install Selenium IDE.
39
Test Automation Using Selenium WebDriver with Java
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
Installing Selenium Components
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
41
Test Automation Using Selenium WebDriver with Java
42
Installing Selenium Components
43
9
Creating First Selenium
WebDriver Script
Now that we understand Selenium Basics (Selenium IDE and Locators) and basics of Java
we are ready to jump into the real Selenium automation tool – Selenium WebDriver.
In this chapter we will see how to create a WebDriver script. Also, we will configure Eclipse
environment.
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
Test Automation Using Selenium WebDriver with Java
132
Creating First Selenium WebDriver Script
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.
133
Test Automation Using Selenium WebDriver with Java
134
Verification Point in Selenium
Statement Description
fail(String) 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.
assertTrue([message], boolean condition) Checks that the boolean condition is
true.
assertFalse([message], boolean condition) Checks that the boolean condition is
false.
assertEquals([String message], expected, Tests that two values are the same. Note:
actual) for arrays the reference is checked, not
the content of the arrays.
assertEquals([String message], expected, Test that float or double values match.
actual, tolerance) The tolerance is the number of decimals
which must be the same.
assertNull([message], object) Checks that the object is null.
assertNotNull([message], object) Checks that the object is not null.
assertSame([String], expected, actual) Checks that both variables refer to the
same object.
assertNotSame([String], expected, actual) Checks that both variables refer to
different objects.
173
Test Automation Using Selenium WebDriver with Java
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
Test Automation Using Selenium WebDriver with Java
2. Create Function definition and import any required Java libraries in the class
3. Add steps to functions based on function’s 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
193
22
Exception Handling in WebDriver
We have already learned about exceptions and their handling techniques in the chapter on
Basics of Java. An exception is an event which occurs during the execution of a program that
disrupts the normal flow of the program’s instructions.
Exception handling in Selenium is also a crucial exercise. Most of the time when a selenium
script fails, it is because it has landed into an exception. The cause could be anything like:
• Element not found
• Couldn’t click the element
• Element not visible
The moment the driver comes across an exception it will halt the test. So it’s important for
a tester to foresee these exception conditions and handle them according to the script or
test requirements. This way the script failures are contributed to failures of test conditions
and not to unhandled code exceptions. So, we have a bug corresponding to every test
failure- which is our ultimate goal.
To catch an exception we first put the code which we suspect will throw an error into a try
block like
try{
if(txtbox_username.isEnabled()){
txtbox_username.sendKeys(“adactin123”);}
catch(NoSuchElementException e){
System.out.println(e.toString());}
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
Exception Handling in WebDriver
273
Test Automation Using Selenium WebDriver with Java
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”))).
clear();
driver.findElement(By.xpath(prop.getProperty(“Txt_Login_Username”))).
sendKeys(sUserName);
// Provide Password.
driver.findElement(By.id(prop.getProperty(“Txt_Login_Password”))).clear();
driver.findElement(By.id(prop.getProperty(“Txt_Login_Password”))).
274
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
Continuous Integration with Jenkins
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
Test Automation Using Selenium WebDriver with Java
1. Go to URL - http://jenkins-ci.org/
2. Download the Jenkins for the correct environment (in our case it is Windows)
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 Element’s Presence
• Checking an Element’s 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
Test Automation Using Selenium WebDriver with Java
Example
Below code executes javascript and returns the Web page title
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