Selenium Tutorial PDF
Selenium Tutorial PDF
Posted In | Automation Testing, Selenium Tutorials | Last Updated: "December 14, 2016"
After hundreds of requests from STH readers, today we are finally launching our FREE Selenium Tutorial
series. In this Selenium training series we will cover all Selenium testing concepts and its packages in detail
with easy to understand practical examples.
These Selenium tutorials are helpful for beginner to advanced level Selenium users. Starting from the very basic
Selenium concepts tutorial, we will gradually move on to the advanced topics like Framework creation,
Selenium Grid and Cucumber BDD.
Note: We will be increasing our article posting frequency for this series. Please don’t miss any tutorial. Keep
track of all the tutorials by bookmarking this page as we will keep updating it with links to all new Selenium
tutorials.
**********************************
Here we are listing all the Selenium Training Tutorials for your handy reference.
List of Selenium Online Training Tutorials:
Selenium Basics:
• Tutorial #1 – Selenium Testing Introduction (Must Read)
• Tutorial #2 – Selenium IDE Features, Selenium Download and installation
• Tutorial #3 – My first Selenium IDE script (Must Read)
• Tutorial #4 – Creating script using Firebug and its installation
• Tutorial #5 – Locator Types: ID, ClassName, Name, Link Text, Xpath
• Tutorial #6 – Locator Types: CSS Selector
• Tutorial #7 – Locating elements in Google Chrome and IE
Selenium WebDriver:
• Tutorial #8 – Selenium WebDriver Introduction (Must Read)
• Tutorial #9 – Selenium WebDriver Installation with eclipse
• Tutorial #10 – My first Selenium WebDriver script (Must Read)
• Tutorial #11 – Introduction to JUnit
• Tutorial #12 – Introduction to TestNG (Must Read)
• Tutorial #13 – Handling Drop-downs
• Tutorial #14 – Looping and Conditional commands
• Tutorial #15 – Explicit and Implicit Waits
• Tutorial #16 – Handling Alerts/popups
• Tutorial #17 – Commonly used commands
• Tutorial #18 – Handling Web Tables, Frames, Dynamic Elements
• Tutorial #19 – Exception Handling
Selenium Framework:
• Tutorial #20 – Most popular Test Automation frameworks(Must Read)
• Tutorial #21 – Selenium Framework Creation & Accessing Test Data from Excel (Must Read)
• Tutorial #22 – Creating Generics and Testsuite
1
• Tutorial #23 – Using Apache ANT
• Tutorial #24 – Setting up Selenium Maven Project
• Tutorial #25 – Using Hudson Continuous integration tool
Advanced Selenium:
• Tutorial #26 – Logging in Selenium
• Tutorial #27 – Selenium Scripting Tips and Tricks
• Tutorial #28 – Database Testing using Selenium WebDriver
• Tutorial #29 – Selenium Grid Introduction (Must Read)
• Tutorial #30 – Automation Testing Using Cucumber and Selenium Part -1
• Tutorial #31 – Integration of Selenium WebDriver with Cucumber Part -2
Selenium Tips and Interview Preparation:
• Tutorial #32 – Selenium project test effort estimation
• Tutorial #33 – Selenium Interview Questions and Answers
**********************************
2
Selenium Basic
Selenium Basics:
• Tutorial #1 – Selenium Testing Introduction (Must Read)
• Tutorial #2 – Selenium IDE Features, Selenium Download and installation
• Tutorial #3 – My first Selenium IDE script (Must Read)
• Tutorial #4 – Creating script using Firebug and its installation
• Tutorial #5 – Locator Types: ID, ClassName, Name, Link Text, Xpath
• Tutorial #6 – Locator Types: CSS Selector
• Tutorial #7 – Locating elements in Google Chrome and IE
3
Tutorial #1 – Selenium Testing Introduction (Must Read)
After hundreds of requests from STH readers, today we are finally launching our FREE Selenium Tutorial
series. In this Selenium training series we will cover all Selenium testing concepts and its packages in detail
with easy to understand practical examples.
These Selenium tutorials are helpful for beginner to advanced level Selenium users. Starting from the very basic
Selenium concepts tutorial, we will gradually move on to the advanced topics like Framework creation,
Selenium Grid and Cucumber BDD.
Note: We will be increasing our article posting frequency for this series. Please don’t miss any tutorial. Keep
track of all the tutorials by bookmarking this page as we will keep updating it with links to all new Selenium
tutorials.
Experienced Selenium professionals – you too can take part in this series by providing answers to reader’s
queries in comments.
This is our serious effort to help you learn and master one of the most popular software testing tools!
Selenium Introduction:
We are delighted to launch our yet another series of software testing training tutorials. The belief behind
introducing this tutorial is to make you an expert in a widely used software test automation solution, Selenium.
In this series we will look at the various facets of Selenium. Selenium is not just a tool; it is a cluster of
independent tools. We will look into some of the tools in detail, providing practical examples wherever
applicable.
Before you jump in to reading this exciting and useful series, let us take a look at what it has got in store for
you.
Why Selenium?
As the current industry trends have shown that there is mass movement towards automation testing. The cluster
of repetitive manual testing scenarios has raised a demand to bring in the practice of automating these manual
scenarios.
4
The benefits of implementing automation test are many; let us take a look at them:
Supports execution of repeated test cases
Aids in testing a large test matrix
Enables parallel execution
Encourages unattended execution
Improves accuracy thereby reducing human generated errors
Saves time and money
All this results in to the following:
High ROI
Faster GoTo market
Automation testing benefits are many and well understood and largely talked about in the software test industry.
5
Selenium Components
Selenium is not just a single tool or a utility, rather a package of several testing tools and for the same reason it
is referred to as a Suite. Each of these tools is designed to cater different testing and test environment
requirements.
The suite package constitutes of the following sets of tools:
Selenium Integrated Development Environment (IDE)
Selenium Remote Control (RC)
Selenium WebDriver
Selenium Grid
Selenium RC and WebDriver, in a combination are popularly known as Selenium 2. Selenium RC alone is also
referred as Selenium 1.
6
Brief Introduction to Selenium tools
Selenium Core
Selenium is a result of continuous efforts by an engineer at ThoughtWorks, named as Jason Huggins. Being
responsible for the testing of an internal Time and Expenses application, he realized the need for an automation
testing tool so as to get rid of repetitive manual tasks without compromising with the quality and accuracy.
As a result, he built a JavaScript program, named as “JavaScriptTestRunner” in early 2004 that could
automatically control the browser’s actions which seemed very much similar to that of a user communicating
with the browser.
Henceforth, Jason started demoing the tool to the vast audience. Eventually the discussions were laid out to
categorize this tool in the open source category as well as its potential to grow as a re-usable testing framework
for other web based applications.
The tool was later on acclaimed with the name “Selenium Core”.
Selenium IDE is the simplest and easiest of all the tools within the Selenium Package. Its record and playback
feature makes it exceptionally easy to learn with minimal acquaintances to any programming language. With
7
several advantages, a few disadvantages accompanied Selenium IDE, thus making it inappropriate to be used in
cases of more advanced test scripts.
The disadvantages of IDE are in reality not disadvantages of selenium, rather just limitations to what IDE could
achieve. These limitations can be overcome by using Selenium RC or WebDriver.
Loopholes and restrictions which were imposed while using Selenium Core made it difficult for the user to
leverage the benefits of the tool to its totality. Thus it made the testing process a cumbersome and a far reaching
task.
8
The problem of same origin policy disallows to access the DOM of a document from an origin that is different
from the origin we are trying to access the document.
Origin is a sequential combination of scheme, host and port of the URL. For example, for a URL
http://www.seleniumhq.org/projects/, the origin is a combination of http, seleniumhq.org, 80 correspondingly.
Thus the Selenium Core (JavaScript Program) cannot access the elements from an origin that is different from
where it was launched.
For Example, if I have launched the JavaScript Program from “http://www.seleniumhq.org/”, then I would be
able to access the pages within the same domain such as “http://www.seleniumhq.org/projects/” or
“http://www.seleniumhq.org/download/”. The other domains like google.com, yahoo.com would no more be
accessible.
Thus, to test the application using Selenium Core, one has to install the entire application on the Selenium Core
as well as web server to overcome the problem of same origin policy.
So, In order to govern the same origin policy without the need of making a separate copy of Application under
test on the Selenium Core, Selenium Remote Control was introduced. While Jason Huggins was demoing
Selenium, another fellow colleague at ThoughtWorks named Paul Hammant suggested a work around of same
origin policy and a tool that can be wired up with a programming language of our choice. Thus Selenium RC
came into existence.
Unlike selenium IDE, selenium RC supports a wide range of browsers and platforms.
9
Workflow Description
User creates test scripts in a desired programming language.
For every programming language, there is a designated client library.
Client library deports the test commands to the selenium server.
Selenium server deciphers and converts the test commands into JavaScript commands and sends them to
the browser.
Browser executes the commands using selenium core and sends results back to the selenium server
Selenium server delivers the test results to the client library.
There are a few pre-requisites to be in place before creating Selenium RC scripts:
10
Selenium Grid
With selenium RC, life of a tester has always been positive and favorable until the emerging trends raised a
demand to execute same or different test scripts on multiple platforms and browsers concurrently so as to
achieve distributed test execution, testing under different environments and saving execution time remarkably.
Thus, catering these requirements selenium grid was brought into the picture.
Selenium Grid was introduced by Pat Lightbody in order to address the need for executing the test suites on
multiple platforms simultaneously.
Selenium WebDriver
Selenium WebDriver was created by yet another engineer at ThoughtWorks named as Simon Stewart in the
year 2006. WebDriver is also a web-based testing tool with a subtle difference with Selenium RC. Since, the
tool was built on the fundamental where an isolated client was created for each of the web browser; no
JavaScript Heavy lifting was required. This led to a compatibility analysis between Selenium RC and
WebDriver. As a result a more powerful automated testing tool was developed called Selenium 2.
WebDriver is clean and a purely object oriented framework. It utilizes the browser’s native compatibility to
automation without using any peripheral entity. With the increasing demand it has gained a large popularity and
user base.
11
Selenium 3
Selenium 3 is an advance version of Selenium 2. It is a tool focused for automation of mobile and web
applications. Stating that it supports mobile testing, we mean to say that the WebDriver API has been extended
to address the needs of mobile application testing. The tool is expected to be launched soon in the market.
Supported Browsers
12
Supported Operating Systems
Conclusion
In this tutorial, we tried to make you acquainted with the Selenium suite describing its various components,
their usages and their advantages over each other.
13
Selenium Grid brings out an additional feature to Selenium RC by distributing its test script on different
platforms and browsers at the same time for execution, thus implementing the master slave architecture.
WebDriver is a different tool altogether that has various advantages over Selenium RC. The fusion of
Selenium RC and WebDriver is also known as Selenium 2. WebDriver directly communicates with the
web browser and uses its native compatibility to automate.
Selenium 3 is the most anticipated inclusion in the Selenium suite which is yet to be launched in the
market. Selenium 3 strongly encourages mobile testing.
In the next tutorial, we would be discussing about the basics of Selenium IDE, its installation and its features.
We would also have a look at the basic terminologies and nomenclatures of Selenium IDE.
Next Selenium Tutorial: Introduction to Selenium IDE and its installation with detailed study on all the
features of Selenium IDE (coming soon)
A remark for the readers: While our next tutorial of the Selenium training series is in the processing mode,
meanwhile you can explore a bit about the Selenium suite and its tools by looking at its official website.
About the authors:
Shruti Shrivastava (our main author for this series), Amaresh Dhal, and Pallavi Sharma are helping us to bring
this series to our readers.
Shruti is currently working as a Senior Test Engineer with 4+ years of automation testing experience. She is an
ISTQB certified professional and also an active blogger, always interested in solving testing related problems.
Amaresh is having 5+ years of manual and automation testing experience with expertise in WebDriver, Grid
and frameworks.
Pallavi Sharma has more than 7 years rich experience of working in automation testing field with hands-on
Selenium and JAVA experience.
Stay tuned till then and share your views, comments and knowledge to help us groom. Also let us know if
you find anything that we missed out so that we can include them in the subsequent tutorials.
14
Tutorial #2 – Selenium IDE Features, Selenium Download and installation
Getting Started with Selenium IDE (Installation and its Features) – Selenium
Tutorial #2
Before moving ahead, let’s take a moment to look at the agenda of this tutorial. In this tutorial, we will learn all
about Selenium IDE, starting from its installation to the details about each of its features. At the end of this
tutorial, the reader is expected to be able to install Selenium IDE tool and play around with its features.
=> This is a 2nd tutorial in our free online Selenium training series. If you have not read the first Selenium
tutorial in this series please get started from here: Free online Selenium Tutorial #1
Note: This is quite a extensive tutorial with lots of images so allow it to load completely. Also click on image or
open in new window to enlarge images.
Selenium integrated development environment, acronym as Selenium IDE is an automated testing tool that is
released as a Firefox plug-in. It is one of the simplest and easiest tools to install, learn and to go ahead with the
creation of test scripts. The tool is laid on a record and playback fundamental and also allows editing of the
recorded scripts.
The most impressive aspect of using selenium IDE is that the user is not required to possess any prior
programming knowledge. The minimum that the user needs is the little acquaintances with HTML, DOMS and
JavaScript to create numerous test scripts using this tool.
Being a Firefox plug-in, Selenium IDE supports only Firefox, thus the created test scripts could be executed
only on Firefox. A few more loopholes make this tool inappropriate to be used for complex test scripts. Thus,
other tools like Selenium RC, WebDriver comes into the picture.
So, before gripping on to the details of Selenium IDE, let’s have a look at its installation first.
Before taking off, there is one thing that needs to be in place prior to the installation; Mozilla Firefox. You can
download it from here => Mozilla Firefox download.
15
Step #1: Selenium IDE download: Open the browser (Firefox) and enter the URL – http://seleniumhq.org/ .
This would open the official Selenium head quarter website. Navigate to the “Download” page; this page
embodies all the latest releases of all the selenium components. Refer the following figure.
Step #2: Move under the selenium IDE head and click on the link present. This link represents the latest version
of the tool in the repository. Refer the following figure.
Step #3: As soon as we click on the above link, a security alert box would appear so as to safeguard our system
against potential risks. As we are downloading the plug-in from the authentic website, thus click on the “Allow”
button.
Step #4: Now Firefox downloads the plug-in in the backdrop. As soon as the process completes, software
installation window appears. Now click on the “Install Now” button.
16
Step #5: After the installation is completed, a pop up window appears asking to re-start the Firefox. Click on
the “Restart Now” button to reflect the Selenium IDE installation.
Step #6: Once the Firefox is booted and started again, we can see selenium IDE indexed under menu bar ->
Web Developer -> Selenium IDE.
Step #7: As soon as we open Selenium IDE, the Selenium IDE window appears.
Features of Selenium IDE
Let’s have a look at each of the feature in detail.
17
#1. Menu Bar
Menu bar is positioned at the upper most of the Selenium IDE window. The menu bar is typically comprised of
five modules.
File Menu
Edit Menu
Actions Menu
Options Menu
Help Menu
A) File Menu
File Menu is very much analogous to the file menu belonging to any other application. It allows user to:
Create new test case, open existing test case, save the current test case.
Export Test Case As and Export Test Suite As in any of the associated programming language
compatible with Selenium RC and WebDriver. It also gives the liberty to the user to prefer amid the
18
available unit testing frameworks like jUnit, TestNG etc. Thus an IDE test case can be exported for a
chosen union of programming language, unit testing framework and tool from the selenium package.
Export Test Case As option exports and converts only the currently opened Selenium IDE test case.
Export Test Suite As option exports and converts all the test cases associated with the currently opened
IDE test suite.
Close the test case.
The Selenium IDE test cases can be saved into following format:
HTML format
The Selenium IDE test cases can be exported into following formats/programming languages.
Notice that with the forthcoming newer versions of Selenium IDE, the support to formats may expand.
B) Edit Menu
19
Edit menu provides options like Undo, Redo, Cut, Copy, Paste, Delete and Select All which are routinely
present in any other edit menu. Amongst them, noteworthy are:
Insert New Command – Allows user to insert the new command/test step anywhere within the current
test case.
Insert New Comment – Allows user to insert the new comment anywhere within the current test case to
describe the subsequent test steps.
Insert New Command
The new command would be inserted above the selected command/test step.
Now the user can insert the actual command action, target and value.
20
Insert New Comment
In the same way we can insert comments.
C) Actions Menu
Record – Record options fine tunes the Selenium IDE into the recording mode. Thus, any action made
by the user on the Firefox browser would be recorded in IDE.
Play entire test suite – The option plays all the Selenium IDE test cases associated with the current test
suite.
Play current test case – The option plays the current Selenium IDE test case that has been
recorded/created by the user.
21
Pause / Resume – User can Pause/Resume the test case at any point of time while execution.
Toggle Breakpoint – User can set one or multiple breakpoint(s) to forcefully break the execution at any
particular test step during execution.
Set / Clear Start Point – User can also set start point at any particular test step for execution. This
would enable user to execute the test case from the given start point for the subsequent runs.
To deal with the page/element loads, the user can set the execution speed from fastest to lowest with
respect to the responsiveness of the application under test.
D) Options Menu
Options menu privileges the user to set and practice various settings provided by the Selenium IDE. Options
menu is recommended as one of the most important and advantageous menu of the tool.
Options Menu is primarily comprised of the following four components which can be sub-divided into the
following:
Options
Selenium IDE Options dialog box
22
2. Click on the Options
A Selenium IDE Options dialog box appears. Refer the following figure.
Selenium IDE Options dialog box aids the user to play with the general settings, available formats, available
plug-ins and available locators types and their builders.
General Settings
23
Default Timeout Value – Default Timeout Value represents the time (in milliseconds) that selenium
would wait for a test step to execute before generating an error. The standard timeout value is 30000
milliseconds i.e. 30 seconds. The user can leverage this feature by changing the default time in cases
when the web element takes more/less than the specified time to load.
Extensions – Selenium IDE supports a wide range of extensions to enhance the capabilities of the core
tool thereby multiplying its potential. These user extensions are simply the JavaScript files. They can set
by mentioning their absolute path in the text boxes representing extensions in the Options dialog box.
Remember base URL – Checking this option enables the Selenium IDE to remember the URL every
time we launch it. Thus it is advisable to mark it checked. Un-checking this option will leave the base
URL field as blank and it will be re-filled only when we launch another URL on the browser.
Record assertTitle automatically – Checking this field inserts the assertTitle command automatically
along with the target value for every visited web page.
Enable experimental features – Checking this field for the first time imports the various available
formats into the Selenium IDE.
Formats
24
Formats tab displays all the available formats with selenium IDE. User is levied with the choice to enable and
disable any of the formats. Refer the following figure.
25
Locator Builders
Locator builders allow us to prioritize the order of locator types that are generated while recording the user
actions. Locators are the set of standards by which we uniquely identify a web element on a web page.
Formats
Formats option allows user to convert the Selenium IDE test case (selenese commands) into desired format.
26
E) Help Menu
As Selenium has a wide community and user base, thus various documentations, release notes, guides etc. are
handily available. Thus, the help menu lists down official documentation and release notes to help the user.
Base URL bar is principally same as that of an address bar. It remembers the previously visited websites so that
the navigation becomes easy later on.
27
Now, whenever the user uses “open” command of Selenium IDE without a target value, the base URL would be
launched on to the browser.
#3. Toolbar
Toolbar provides us varied options pertinent to the recording and execution of the test case.
Playback Speed – This option allows user to control the test case execution speed from
fast to slow.
Play test suite – This option allows user to execute all the test cases belonging to the current
test suite sequentially.
Play test case – This option allows user to execute the currently selected test case.
Pause – This option allows user to pause the current execution.
Step – This option allows user to step into the test step.
28
Rollup– This option allows user to combine multiple test steps to act like a single command.
Record – This option allows user to start/stop the recording of user actions. The hollow red ball
indicates the start of the recording session whereas the solid red ball indicates the end of the recording
session. By default, the Selenium IDE opens in the recording mode.
#4. Editor
Editor is a section where IDE records a test case. Each and every user action is recorded in the editor in the
same order in which they are performed.
It is the default view provided by Selenium IDE. The test case is represented in the tabular format. Each user
action in the table view is a consolidation of “Command”, “Target” and “Value” where command, target and
value refers to user action, web element with the unique identification and test data correspondingly. Besides
recording it also allows user to insert, create and edit new Selenese commands with the help of the editor form
present in the bottom.
2) Source View
29
The test case is represented in the HTML format. Each test step is considered be a row <tr> which is a
combination of command, target and value in the separate columns <td>. Like any HTML document, more
rows and columns can be added to correspond to each Selenese command.
Editor Form lets the user to type any command and the suggestions for the related command would be
populated automatically. Select button lets the user to select any web element and its locator would be fetched
automatically into the target field. Find button lets the user find the web element on the web page against a
defined target. Value is the test input data entered into the targets with which we want to test the scenario.
30
At the instance we open Selenium IDE interface, we see a left container titled “Test case” containing an untitled
test case. Thus, this left container is entitled as Test case pane.
Test case pane contains all the test cases that are recorded by IDE. The tool has a capability of opening more
than one test case at the same time under test case pane and the user can easily shuffle between the test cases.
The test steps of these test cases are organized in the editor section.
Selenium IDE has a color coding ingredient for reporting purpose. After the execution, the test case in marked
either in “red” or “green” color.
Red color symbolizes the unsuccessful run i.e. failure of the test case.
Green color symbolizes the successful run of the test case
It also layouts the summary of the total number of test cases executed with the number of failed test
cases.
If we execute a test suite, all the associated test cases would be listed in the test case pane. Upon
execution, the above color codes would be rendered accordingly.
31
Log pane gives the insight about current execution in the form of messages along with the log level in the real
time. Thus, log messages enable a user to debug the issues in case of test case execution failures.
The printing methods / log levels used for generating logs are:
Error – Error message gives information about the test step failure. It may be generated in the cases
when element is not found, page is not loaded, verification/assertion fails etc.
Warn – Warning message gives information about unexpected conditions.
Info – Info message gives information about current test step execution.
Debug – Debug messages gives information about the technicalities in the backdrop about the current
test step.
Logs can be filtered with the help of a drop down located at the top-right corner of the footer beside the clear
button. Clear button erases all the log messages generated in the current or previous run.
32
Reference Pane
Reference Pane gives the brief description about the currently selected Selenese command along with its
argument details.
UI-Element Pane
UI – Element Pane allows Selenium user to use JavaScript Object Notation acronym as JSON to access the page
elements. More on this can be found in UI-Element Documentation under Help Menu.
Rollup Pane
Rollup Pane allows the user to roll up or combine multiple test steps to constitute a single command termed as
“rollup”. The rollup in turn can be called multiple times across the test case.
Conclusion
33
Through this tutorial, our objective was to make you familiar and accustomed with the basic terminologies and
nomenclatures of Selenium IDE. We also presented a detailed study on all the features of Selenium IDE.
34
Tutorial #3 – My first Selenium IDE script (Must Read)
This tutorial is by far one of the most important tutorials to get a hold on Selenium IDE.
This is the 3rd tutorial in our multi-part Selenium Tutorials series. We started this Selenium online Training
series from this tutorial where you can find list of all tutorials covered.
In the introductory tutorials, we got a brief idea about Selenium IDE and its features.
Going ahead, we would be exercising and implementing these features in real time by creating our own very
first Selenium IDE script. We would also peek into the details of recording fundamentals and available types of
commands in Selenium IDE. Apart from that we would also have a glance at the modifications which can be
incorporated into our Selenium scripts.
Before jumping on to the creation of Selenium IDE script, let us take a moment to introduce elementary
information about the application under test (AUT).
As a specimen, we would be using “Gmail” – an email service designed by Google. I believe because of its
unbounded popularity, it needs no more introductions. The URL we would be using is
“https://accounts.google.com”. I have also created dummy credentials to represent test data.
35
Verify that the user is re-directed to the Home page.
Step 1 – Launch the Firefox and open Selenium IDE from the menu bar.
Step 2 – Enter the address of application under test (“https://accounts.google.com”) inside the Base URL
textbox.
Step 3 – By default, the Record button is in ON state. Remember to tune it ON if it is in OFF state so as to
enable the recording mode.
Step 5 – Verify if the application title is correct. To do so, right click anywhere on the page except the
hyperlinks or images. The right click opens the Selenium IDE context menu listing few of the commands. To
get an entire list, select “Show Available Commands” option. This will open another menu containing rest of
the available and applicable commands. Select “assertTitle Sign in – Google Accounts” option to verify the
page title.
36
As soon as we click on “assertTitle Sign in – Google Accounts” option, a test step would be included /appended
in the Selenium IDE editor.
Notice that for the ease of understanding, I have already created test credentials. I would strictly advise the
readers to create their own credentials instead of using these.
37
Step 8 – Click on the “Sign in” button to complete the login process.
User should be re-directed to the home page provided the credentials entered are correct.
Step 9 – At the end, we would end the recording session by tuning the record button into OFF state. Below is
the recorded script.
38
Post execution, all the test steps would be color coded in green for the successful run. The same would be
evitable from the test case pane.
For unsuccessful execution or test case failure, the failed test step would be highlighted in red. And the test case
pane would mark the test case execution as failure.
Step 1 – To save the test script, Click on the File menu and select “Save Test Case” option.
Step 2 – The system will prompt us to browse or enter the desired location to save our test case and to provide
the test script name. Furnish the test name as “Gmail_Login” and click on the “Save” button.
The test script can be found at the location provided in the above step. Notice that the test script is saved in
HTML format.
So to avoid failures while playing back these test scenarios, we can set the execution speed to be minimal. Refer
the following figure for the same.
“Execute this command” option can be used at times when we want to debug/see the behavior of a particular
test step.
“Execute this command” option can be used in the following four ways:
#1. Using Actions tab from the Menu bar
Steps to be followed:
Step 1 – Launch the web browser and open the target URL (“https://accounts.google.com”), Select the test step
that we desire to execute. Remember to open correct web page to mitigate the chances of failure.
Step 2 – Press “X” to execute the selected test step. Alternatively, one can use other ways too.
Step 3 – Notice that the selected test step is executed. The test step would be color coded in green for success or
red for failure. At the same time, the test step would be simulated into an action on the web browser.
Note that the user is responsible to bring the script before executing the test step and Firefox in context. There is
a probability of failure if the user has not opened the legitimate web page.
Start point can be used at times when we do not desire to execute the entire test script starting from the
beginning rather we customize the script to execute from a certain step.
Start point can be set and clear in the following three ways:
#1. Using Actions tab from the Menu bar
41
------------
As soon as the user has marked the test step to indicate the start point, an icon gets affixed to it.
Now whenever we execute the test script, it execution would be started from the start point i.e. fourth line (type
| id=Passwd | TestSelenium) of the test script.
Notes
There can be one and only one start point in a single script.
The start point can be cleared in the same way it was set.
User is responsible to bring the script after applying start point and Firefox in context. There is a
probability of failure if the user has not opened the legitimate web page.
Using Break point
42
Selenium IDE allows the user to specify break points within a test script. The break points indicate Selenium
IDE where to pause the test script.
Break points can be used at times when we desire to break the execution in smaller logical chunks to witness the
execution trends.
Break point can be set and clear in the following three ways:
Using Actions tab from the Menu bar
Right click the test step and select “Toggle Breakpoint”.
Using short cut key (“B”)
As soon as the user has marked the test step to indicate the break point, an icon gets affixed to it.
Now whenever we execute the test script, the execution pauses at the break point i.e. fourth line (type |
id=Passwd | TestSelenium) of the test script.
In the above test script, the execution pauses at the line “assertTitle | Sign in – Google Accounts”. After
explicitly executing this test step, the control moves to the next test step in sequence “type | id=Email |
TestSelenium1607@gmail.com”. Thus, user needs to explicitly execute this test step. The similar trend is
followed for rest of the subsequent steps.
43
Thus, this feature lets the user to spend more time executing each step and reviewing the outcomes of the
previously executed test step.
Notes
There can be as many break points as you wish in a single script.
The break point can be cleared in the same way it was set.
Using Find Button
One of the most crucial aspects of Selenium IDE test scripts is to find and locate web elements within a web
page. At times, there are web elements which have analogous properties associated with them, thus making it
challenging for a user to identify a particular web element uniquely.
To address this issue, Selenium IDE provides Find button. The Find Button is used to ascertain that locator
value provided in the Target test box is indeed correct and identifies the designated web element on the GUI.
Let us consider the above created Selenium IDE test script. Select any command and notice the target text box.
Click on the Find button present just beside the Target text box.
Notice that the corresponding web element would be highlighted in yellow with a fluorescent green border
around it. If no or wrong web element is highlighted, then the user is required to rectify the issue and would
need to impose some other locator value.
Thus, this procedure makes the user assured about the target value being used and that it corresponds to the
correct web element on the GUI.
44
Selenium IDE supports conversion test scripts into set of programming languages from a default type (HTML).
The converted test scripts cannot be played back using Selenium IDE until and unless it is reverted back to
HTML. Thus the conversion is beneficial and constructive only when we are executing it from other tools of
Selenium Suite.
Step 1 – Click on the options tab under the menu bar and select the programming language format under format
option in order to convert the test script into our desired format.
Step 2 – As soon as we select our Desired Programming language format (“Java / JUnit4 / WebDriver” in our
case), a prompt box appears which says “Changing format is now marked experimental! If you continue,
recording and playback may not work, your changes may be lost and you may have to copy and paste the test in
a text editor to save. It is better to make a copy of your test cases before you continue. Do you still want to
proceed?” Click “OK” to continue.
45
Mark that editing or modifying Selenium IDE test scripts from Source View is not advisable. If done so, the
tool might introduce several repercussions. Several known bugs are already associated with it.
Command
Target
Value
Actions
Accessors
Assertions
Actions
Actions are those commands which interact directly with the application by either altering its state or by
pouring some test data.
For Example, “type” command lets the user to interact directly with the web elements like text box. It allows
them to enter a specific value in the text box and as when the value is entered; it is showed on the UI as well.
Another example is “click” command. “click” command lets the user to manipulate with the state of the
application.
In case of failure of an action type command, the test script execution halts and rest of the test steps would not
be executed.
Accessors
46
Accessors are those commands which allows user to store certain values to a user defined variable. These stored
values can be later on used to create assertions and verifications.
For example, “storeAllLinks” reads and stores all the hyperlinks available within a web page into a user defined
variable. Remember the variable is of array type if there are multiple values to store.
Assertions
Assertions are very similar to Accessors as they do not interact with the application directly. Assertions are used
to verify the current state of the application with an expected state.
Forms of Assertions:
#1. assert – the “assert” command makes sure that the test execution is terminated in case of failure.
#2. verify – the “verify” command lets the Selenium IDE to carry on with the test script execution even if the
verification is failed.
#3. waitFor – the “waitFor” command waits for a certain condition to be met before executing the next test
step. The conditions are like page to be loaded, element to be present. It allows the test execution to proceed
even if the condition is not met within the stipulated waiting period.
Commonly used Selenium IDE commands
#Argu
Command Description
ments
47
#Argu
Command Description
ments
48
open
assertTitle / VerifyTitle
AssertForElementPresent / VerifyForElementPresent
AssertForTextPresent / VerifyForTextPresent
type / typeAndWait / sendKeys
click /clickAt / clickAndWait
waitForPageToLoad
waitForElementPresent
chooseOkOnNextConfirmation / chooseCancelOnNextConfirmation
Next Tutorial #4: There is another tool which plays a very important role in assisting us to create effective test
scripts known as “Firebug”. Firebug helps us in inspecting the properties of web elements and web pages. Thus
the next tutorial is comprised of installation of Firebug and its usability. We would also create a test script
manually using firebug and Selenium IDE.
Note: Do not miss the next tutorial because of its great importance with respect to our forthcoming tutorials on
WebDriver.
As usual let us know your queries in comments below.
49
Tutorial #4 – Creating script using Firebug and its installation
In the previous tutorial, we learned how to create automated test scripts using Selenium IDE and its recording
feature. We also flipped through populous features of Selenium IDE. We aimed at harbingering the reader with
the most vital features and commands of Selenium IDE.
Just a reminder – this is our 4th tutorial in free Selenium training series.
Now that you are accustomed and capable of creating automated scripts using recording mode of Selenium IDE,
let us move ahead with another tool which plays a very important role in assisting us to create effective test
scripts known as “Firebug”. Firebug helps us in inspecting the properties of web elements and web pages.
Take a note that the content of this tutorial is not only applicable in context of Selenium IDE; rather it can be
applied to each and every tool of Selenium suite. Thus I would preferably be using term Selenium instead of
Selenium IDE.
In this tutorial lets learn how to use Firebug add-on for creating Selenium scripts. In the process we will also
learn how to install Firebug.
Introduction to Firebug
Firebug is a Mozilla Firefox add-on. This tool helps us in identifying or to be more particular inspecting HTML,
CSS and JavaScript elements on a web page. It helps us identifying the elements uniquely on a webpage. The
elements can be found uniquely based on their locator types which we would be discussing later in this tutorial.
Step -1: Launch the Mozilla Firefox browser and navigate to this Firebug add-on download page. The URL
takes us to Firefox add-ons section.
Step -2: Click on the “Add to Firefox” button present on the webpage. Refer the following figure for the same.
50
Step-3: As soon as we click on the “Add to Firefox” button, a security alert box would appear, click on the
“Allow” button now.
Step-4: Now Firefox downloads the add-on in the backdrop and a progress bar is displayed.
Step-5: As soon as the process completes, software installation window appears. Now click on the “Install
Now” button.
Step-6: As soon as the installation completes, a pop up appears saying that the firebug has been installed
successfully. Now choose to close this pop up.
Note: Unlike Selenium IDE, we are not required to restart the Firefox to reflect the firebug installation, rather it
comes readily.
Step-7: Now to launch firebug, we can opt either of the following ways:
51
Press F12
Click on the firebug icon present in the extreme top-right corner of the Firefox window.
Click on Firefox menu bar -> Web Developer -> firebug -> Open Firebug.
Step-8: Now the firebug can be seen at the bottom of the Firefox window.
Now that we have downloaded and installed firebug, let’s move ahead with the types of locators that we would
be creating using firebug.
Let us follow a progressive approach and understand the process step by step.
Scenario:
Open “https://accounts.google.com”.
Assert Title of the application
Enter an invalid username and invalid password and submit the details to login.
Step 1 – Launch the Firefox and open Selenium IDE from the menu bar.
Step 2 – Enter the address of application under test (“https://accounts.google.com”) inside the Base URL
textbox.
Step 3 – By default, the Record button is in ON state. Remember to tune it OFF state so as to disable the
recording mode. Notice if the recording mode is in ON state, it may result in recording our interactions with the
web browser.
52
Step 6 – Select the empty test step within the Editor.
Step 7 – Type “open” in the command text box present in the Editor Pane. The “open” command opens the
specified URL in the web browser.
53
Recommendation: While typing commands in the command text box, user can leverage the feature of auto
selection. Thus, as soon as the user types a sequence of characters, the matching suggestions would be auto
populated.
User can also click on the dropdown available within the command text box to look at all the commands
provided by Selenium IDE.
Step 8 – Now, motion towards the Firebug section within the web browser, expand “head” section of the
HTML code. Notice the HTML tag <title>. Thus to assert the title of the webpage, we would require the value
of the <title> tag.
Copy the title of the webpage which is “Sign in – Google Accounts” in our case.
Step 9 – Select the second empty test step within the Editor.
54
Step 10 – Type “assertTitle” in the command text box present in the Editor Pane. The “assertTitle” command
returns the current page title and compares it with the specified title.
------------
Step 11 – Paste the title copied in step 8 into the Target field of the second.
55
Step 12 – Now select the third empty test step in the Editor Pane
Step 13 – Type “type” command within the command text box. The “type” command enters a value in the
specified web element on to the GUI.
56
Step 14 – Now switch to the web browser, bring the mouse cursor to the “Email” textbox within the login form
and press a right click.
Choose “Inspect Element with Firebug”option. Notice that the Firebug automatically highlights the
corresponding HTML code for the web element i.e. “Email Textbox”.
Step 15 – The HTML code in the above illustration manifests the distinct property attributes belonging to the
“Email” text box. Notice that there are four properties (ID, type, placeholder and name) that uniquely identify
the web element on the web page. Thus it’s up to the user to choose one or more than one property to identify
the web element.
Thus, in this case, we choose ID as the locator. Copy the ID value and paste it in the Target field of the third test
step prefixed with “id=” to indicate Selenium IDE to locate a web element having ID as “Email”.
57
Make a note that Selenium IDE is case sensitive, thus type the attribute value carefully and precisely the same
as it is displayed in the HTML code.
Step 16 – Click on the Find button to verify if the locator selected finds and locates the designated UI element
on the web page.
Step 17 – Now, the next step is to enter the test data in the Value textbox of the third test step within the Editor
Pane. Enter “InvalidEmailID” in the Value textbox. User can alter the test data as and when it is desired.
Step 18 – Now select the fourth empty test step in the Editor Pane
Step 19 – Type “type” command within the command text box.
Step 20 – Now switch to the web browser, bring the mouse cursor to the “Password” textbox within the login
form and press a right click.
58
Choose “Inspect Element with Firebug”option.
Step 21 – The HTML code below manifests the distinct property attributes belonging to the “Password” text
box. Notice that there are four properties (ID, type, placeholder and name) that uniquely identify the web
element on the web page. Thus it’s up to the user to choose one or more than one property to identify the web
element.
Thus, in this case, we choose ID as the locator. Copy the ID value and paste it in the Target field of the third test
step prefixed with “id=”.
Step 22 – Click on the Find button to verify if the locator tabbed finds and locates the designated UI element on
the web page.
Step 23 – Now, the next step is to enter the test data in the Value textbox of the fourth test step within the
Editor Pane. Enter “InvalidPassword” in the Value textbox. User can alter the test data as and when it is desired.
59
Step 24 – Now select the fifth empty test step in the Editor Pane
Step 25 – Type “click” command within the command text box. The “click” command clicks on a specified
web element within the web page.
Step 26 – Now switch to the web browser, bring the mouse cursor to the “Sign in” button within the login form
and press a right click.
Choose “Inspect Element with Firebug”option.
Step 27 – The HTML code below manifests the distinct property attributes belonging to the “Sign in” button.
Choose ID as the locator. Copy the ID value and paste it in the Target field of the third test step prefixed with
“id=”.
60
Step 28 – Click on the Find button to verify if the locator picked finds and locates the designated UI element on
the web page.
The test script is completed now. Refer the following illustration to view the finished test script.
Step 29 – Play back the created test script and Save it in the same way we did in the previous tutorial.
Conclusion
61
In this tutorial, we introduced yet another script creation tool or rather a tool that aids to script creation.
Firebug surprisingly has a great potential to locate web elements on a web page. Thus the user can leverage the
tool’s capabilities in creating effective and efficient automation test scripts manually.
Next Tutorial #5: Moving ahead in the next tutorial, we would have a look at the various types of locators in
Selenium and their accessibility technique to build test scripts. In the meantime reader can start building
his/her automation test scripts using Firebug.
Have you used Firebug for inspecting HTML elements or for creating scripts? Do you find it useful? Please
share your experience in comments
62
Tutorial #5 – Locator Types: ID, ClassName, Name, Link Text, Xpath
How to Identify Web Elements Using Selenium Xpath and Other Locators –
Selenium Tutorial #5
In the previous tutorial, we introduced you with another automation testing tool named as Firebug. We also
created our own automation script manually using Firebug and its capabilities. We also learned to affix desired
modifications into our script.
Moving ahead, in this tutorial we would have a look at the various types of locators in Selenium and their
accessibility technique to build test scripts. Thus this tutorial is comprised of the detailed introduction to
various types of locators.
This is our 5th tutorial in Selenium Tutorial series.
What is Locator?
Locator can be termed as an address that identifies a web element uniquely within the webpage. Locators are
the HTML properties of a web element which tells the Selenium about the web element it need to perform
action on.
There is a diverse range of web elements. The most common amongst them are:
Text box
Button
Drop Down
Hyperlink
Check Box
Radio Button
Types of Locators
Identifying these elements has always been a very tricky subject and thus it requires an accurate and effective
approach. Thereby, we can assert that more effective the locator, more stable will be the automation script.
Essentially every Selenium command requires locators to find the web elements. Thus, to identify these web
elements accurately and precisely we have different types of locators.
63
Now let’s understand further by exercising each of them independently.
Before we start with the locators, let me take a moment to introduce the application under test. We would be
using “https://accounts.google.com/” for locating different types of web elements using different locator types.
Using ID as a Locator
The best and the most popular method to identify web element is to use ID. The ID of an each element is
alleged to be unique.
In this sample, we would access “Email” text box present in the login form at gmail.com.
64
Step 4: Hover on the web element (Email textbox in our case) on which we desire to perform some action. In
the firebug section, one can see the corresponding html tags being highlighted.
Step 5: Be cognizant about the ID attribute and take a note of it. Now we need to verify if the ID indentified is
able to find the element uniquely and flawlessly.
Syntax: id = id of the element
In our case, the id is “Email”.
Alternative approach:
Instead of following step 2 to 4, we can directly locate / inspect the web element by right clicking on the web
element (Email Textbox) whose locator value we need to inspect and clicking on the option “Inspect Element
with Firebug”. Thus, this click event triggers the expansion of firebug section and the corresponding html tag
would be highlighted.
65
Verify the locator value
Assuming that the browser is open and is re-directed to “https://accounts.google.com/”.
66
Step 5: In order to verify further, user can also execute “type” command against the given target by providing
some value in the “Value” field. If the execution of the command enters the specified value in the Email text
box that means the identified locator type is correct and accessible.
Using ClassName as a Locator
There is only a subtle difference between using ID as a locator and using classname as a locator.
In this sample, we would access “Need Help?” hyperlink present at the bottom of the login form at gmail.com.
67
Using name as a Locator
Locating a web element using name is very much analogous to previous two locator types. The only difference
lies in the syntax.
In this sample, we would access “Password” text box present in the login form at gmail.com.
In this sample, we would access “Create an account” link present at the bottom of the login form at gmail.com.
68
Syntax: link = link text of the element
In our case, the link text is “Create an account”.
The fundamental behind locating elements using Xpath is the traversing between various elements across the
entire page and thus enabling a user to find an element with the reference of another element.
69
Xpath can be created in two ways:
Relative Xpath
Relative Xpath begins from the current location and is prefixed with a “//”.
Absolute Xpath
Absolute Xpath begins with a root path and is prefixed with a “/”.
Key Points:
The success rate of finding an element using Xpath is too high. Along with the previous statement,
Xpath can find relatively all the elements within a web page. Thus, Xpaths can be used to locate
elements having no id, class or name.
Creating a valid Xpath is a tricky and complex process. There are plug-ins available to generate Xpath
but most of the times, the generated Xpaths fails to identify the web element correctly.
While creating xpath, user should be aware of the various nomenclatures and protocols.
Selenium Xpath Examples
Xpath Checker
Creating Xpath becomes a little simpler by using Xpath Checker. Xpath Checker is a firefox add-on to
automatically generate Xpath for a web element. The add-on can be downloaded and installed like any other
plug-in. The plug-in can be downloaded from “https://addons.mozilla.org/en-US/firefox/addon/xpath-checker/”.
As soon as the plug-in is installed, it can be seen in the context menu by right clicking any element whose xpath
we want to generate.
70
Click on the “View Xpath” to see the Xpath expression of the element. An editor window would appear with
the generated Xpath expression. Now user has the liberty to edit and modify the generated Xpath expression.
The corresponding results would be updated cumulatively.
Note that the Xpath Checker is available for other browsers as well.
But re-iterating the fact, that most of the times, the generated Xpaths fails to identify the web element rightly.
Thus, it is recommended to create our own Xpath following the pre defined rules and protocols.
In this sample, we would access “Google” image present at the top of the login form at gmail.com.
71
Conclusion
Here are the cruxes of this article.
Locators are the HTML properties of a web element which tells the Selenium about the web element on
which it needs to perform actions.
There is a wide range of web elements that a user may have to interact with on a regular basis. Some of
them are: Text box, Button, Drop Down, Hyperlink, Check Box, and Radio Button.
With the varied range of web elements comes a vast province of strategies/approaches to locate these
web elements.
Some of the extensively used locator types are: ID, ClassName, Link Text, Xpath, CSS Selectors and
Name.
Note: Owing to the fact that creating CSS Selector and Xpath requires a lot of efforts and practice, thus the
process is only exercised by more sophisticated and trained users.
72
Tutorial #6 – Locator Types: CSS Selector
How to Use CSS Selector for Identifying Web Elements for Selenium Scripts
– Selenium Tutorial #6
In our previous Selenium tutorialwe learned different types of locators. We also learned how to use: ID,
ClassName, Name, Link Text, and Xpath locators for identifying web elements in a web page.
In continuation with that, today we will learn how to use CSS Selector as a Locator. This is our 6th tutorial in
our free Selenium Training series.
Using CSS Selector as a Locator:
CSS Selector is combination of an element selector and a selector value which identifies the web element within
a web page. The composite of element selector and selector value is known as Selector Pattern.
Selector Pattern is constructed using HTML tags, attributes and their values. The central theme behind the
procedure to create CSS Selector and Xpath are very much similar underlying the only difference in their
construction protocol.
Like Xpath, CSS selector can also locate web elements having no ID, class or Name.
So now gearing ahead, let us discuss the primitive types of CSS Selectors:
CSS Selector: ID
In this sample, we would access “Email” text box present in the login form at Gmail.com.
The Email textbox has an ID attribute whose value is defined as “Email”. Thus ID attribute and its value can be
used to create CSS Selector to access the email textbox.
73
Verify the locator value
Step 1: Type “css=input#Email” i.e. the locator value in the target box in the Selenium IDE and click on the
Find button. Notice that the Email Text box would be highlighted.
Syntax
css=<HTML tag><#><Value of ID attribute>
HTML tag – It is tag which is used to denote the web element which we want to access.
# – The hash sign is used to symbolize ID attribute. It is mandatory to use hash sign if ID attribute is
being used to create CSS Selector.
Value of ID attribute – It is the value of an ID attribute which is being accessed.
The value of ID is always preceded by a hash sign.
Note: Also applicable for other types of CSS Selectors
While specifying CSS Selector in the target text box of Selenium IDE, always remember to prefix it
with “css=”.
The sequence of the above artifacts is inalterable.
If two or more web elements have the same HTML tag and attribute value, the first element marked in
the page source will be identified.
CSS Selector: Class
In this sample, we would access “Stay signed in” check box present below the login form at gmail.com.
74
The “Stay signed in” check box has a Class attribute whose value is defined as “remember”. Thus Class
attribute and its value can be used to create CSS Selector to access the designated web element.
Locating an element using Class as a CSS Selector is very much similar to using ID, the lone difference lies in
their syntax formation.
Syntax
css=<HTML tag><.><Value of Class attribute>
. – The dot sign is used to symbolize Class attribute. It is mandatory to use dot sign if Class attribute is
being used to create CSS Selector.
The value of Class is always preceded by a dot sign.
CSS Selector: Attribute
In this sample, we would access “Sign in” button present below the login form at gmail.com.
The “Sign in” button has a type attribute whose value is defined as “submit”. Thus type attribute and its value
can be used to create CSS Selector to access the designated web element.
75
Step 1: Type “css=input[type=’submit’]” i.e. the locator value in the target box in the Selenium IDE and click
on the Find Button. Notice that the “Sign in” button would be highlighted.
Syntax
css=<HTML tag><[attribute=Value of attribute]>
Attribute – It is the attribute we want to use to create CSS Selector. It can value, type, name etc. It is
recommended to choose an attribute whose value uniquely identifies the web element.
Value of attribute – It is the value of an attribute which is being accessed.
CSS Selector: ID/Class and attribute
In this sample, we would access “Password” text box present in the login form at gmail.com.
The “Password” text box has an ID attribute whose value is defined as “Passwd”, type attribute whose value is
defined as “password”. Thus ID attribute, type attribute and their values can be used to create CSS Selector to
access the designated web element.
Syntax
css=<HTML tag><. Or #><value of Class or ID attribute><[attribute=Value of attribute]>
76
CSS Selector: Sub-string
CSS in Selenium allows matching a partial string and thus deriving a very interesting feature to create CSS
Selectors using sub strings. There are three ways in which CSS Selectors can be created based on mechanism
used to match the sub string.
Types of mechanisms
All the underneath mechanisms have symbolic significance.
Match a prefix
Match a suffix
Match a sub string
Let us discuss them in detail.
Match a prefix
It is used to correspond to the string with the help of a matching prefix.
Syntax
css=<HTML tag><[attribute^=prefix of the string]>
^ – Symbolic notation to match a string using prefix.
Prefix – It is the string based on which match operation is performed. The likely string is expected to
start with the specified string.
For Example: Let us consider “Password textbox”, so the corresponding CSS Selector would be:
css=input#Passwd[name^=’Pass’]
Match a suffix
It is used to correspond to the string with the help of a matching suffix.
Syntax
css=<HTML tag><[attribute$=suffix of the string]>
# – Symbolic notation to match a string using suffix.
Suffix – It is the string based on which match operation is performed. The likely string is expected to
ends with the specified string.
For Example: Lets again consider “Password textbox”, so the corresponding CSS Selector would be:
css=input#Passwd[name$=’wd’]
Match a sub string
It is used to correspond to the string with the help of a matching sub string.
Syntax
77
css=<HTML tag><[attribute*=sub string]>
* – Symbolic notation to match a string using sub string.
Sub string – It is the string based on which match operation is performed. The likely string is expected
to have the specified string pattern.
For Example: Lets again consider “Password textbox”, so the corresponding CSS Selector would be:
css=input#Passwd[name$=’wd’]
CSS Selector: Inner text
Inner text helps us identify and create CSS Selector using a string pattern that the HTML Tag manifests on the
web page.
Consider, “Need help?” hyperlink present below the login form at gmail.com.
The anchor tag representing the hyperlink has a text enclosed within. Thus this text can be used to create CSS
Selector to access the designated web element.
Syntax
css=<HTML tag><:><contains><(text)>
Owing to the fact that creating CSS Selector and Xpath requires a lot of efforts and practice, thus the process is
only exercised by more sophisticated and trained users.
Next Tutorial #7: Proceeding ahead with our next tutorial, we would take the opportunity to introduce you with
an extension of locating strategies. Thus, in the next tutorial, we would study the mechanism to locate web
elements on Google Chrome and Internet Explorer.
We are covering Selenium Locators in more details as it is important part of Selenium Script creation.
78
Tutorial #7 – Locating elements in Google Chrome and IE
This is tutorial #7 in our Selenium Online Training Series. If you want to check all Selenium tutorials in this
series please check this page.
In the previous tutorial, we tried to shed light on various types of locators in Selenium and their locating
mechanisms to build test scripts. The tutorial was primary consist of the brief introduction of different locator
types like ID, Classes, Xpaths, Link texts, CSS Selectors etc. and their identification.
Proceeding ahead with our next tutorial, we would take the opportunity to introduce you with an extension of
locating strategies. Thus, in the next tutorial, we would study the mechanism to locate web elements on
Google Chrome and Internet Explorer.
As we all are well aware of the fact that there is rapid growth in the internet user base, thus stakeholders and
programmers are building web applications which are likely to work on most of the browsers. Thus, imagine a
situation where your web application doesn’t support Firefox but works well for Chrome and Internet Explorer.
Now how are you going to automate such an application using Selenium? Or to be specific how are you going
to locate web elements in Chrome and Internet Explorer. Thus the answer lies ahead in this tutorial.
Like firebug in Firefox, Google Chrome has its own developer tool that can be used to identify and locate web
elements on the web page. Unlike firebug, user is not required to download or install any separate plugin; the
developer tool comes readily bundled with Google Chrome.
Follow the below steps to locate web elements using Chrome’s Developer tool:
Step #1: The primary step is to launch the Google Chrome’s Developer tool. Press F12 to launch the tool. The
user would be able to see something like the below screen.
79
Take a note that “Element” tab is highlighted in the above screenshot. Thus, element tab is the one which
displays all the HTML properties belonging to the current web page. Navigate to the “Element” tab if it is not
opened by default on the launch.
You can also launch developer tool by right clicking anywhere within the web page and by selecting “Inspect
element” which is very similar to that of firebug’s inspection.
Step #2: The next step is to locate the desired object within the web page. One way to do the same is to right
click on the desired web element and inspect. The HTML property belonging to that web element would be
highlighted in the developer tool. Another way is to hover through the HTML properties and the matching web
element would be highlighted. Thus, in this way user can locate ids, class, links etc.
80
We have already discussed about Xpaths in the last tutorial. We also discussed about its creation strategy. Here
we would base our discussion to check the validity of the created Xpath in Chrome’s Developer tool.
Step #1: For creating Xpath in Developer tool, open the console tab.
Step #2: Type the created Xpath and enclose it in $x(“//input[@id=’Email’]”)
------------
Step #3: Press the enter key to see all the matching HTML elements with the specified Xpath. In our case, there
is only one matching HTML element. Hover on that HTML element and the corresponding web element would
be highlighted on the web page.
In this way, all the Xpaths can be created and checked for their validity within the console.
Information related to CSS corresponding to the web element can be found within the Chrome’s Developer tool.
Refer the screenshot below:
81
Step #1: The primary step is to launch the IE Developer tool. Press F12 to launch the tool. The user would be
able to see something like the below screen.
Take a note that “HTML” tab is highlighted in the above screenshot. Thus, HTML tab is the one which displays
all the HTML properties belonging to the current web page. Expand the HTML tab to view the properties of all
the web elements belonging to the current web page.
Step #2: The next step is to locate the desired object within the web page. One way to this is to select the
HTML element and the matching web element would be highlighted. Thus, in this way user can locate ids,
class, links etc. Check out in the below screenshot in which Email Textbox would be highlighted as soon as we
select the corresponding HTML property.
Another way to locate the web element is to click on the “Find” button present in the top menu and by clicking
on the desired web element within the web page. As a result, the corresponding HTML properties would be
highlighted.
82
Thus, by using the developer tool, user can find ids, classes, tag names and can create Xpaths to locate web
elements.
Like Chrome’s Developer tool, IE developer tool has a separate section that displays CSS related information.
Checkout the below screenshot.
Conclusion
In this tutorial, we shed light on the basic element locating strategies using Developer’s tool for Google Chrome
and Internet Explorer.
Next Tutorial #8: Proceeding ahead with our next tutorial, we would take the pleasure to introduce you with a
more advanced tool named as WebDriver. WebDriver is one of the most compelling automation testing tools.
So our next tutorial onwards, we would route and base our discussions around WebDriver and all its nitty gritty.
83
Selenium WebDriver:
Selenium WebDriver
• Tutorial #8 – Selenium WebDriver Introduction (Must Read)
• Tutorial #9 – Selenium WebDriver Installation with eclipse
• Tutorial #10 – My first Selenium WebDriver script (Must Read)
• Tutorial #11 – Introduction to JUnit
• Tutorial #12 – Introduction to TestNG (Must Read)
• Tutorial #13 – Handling Drop-downs
• Tutorial #14 – Looping and Conditional commands
• Tutorial #15 – Explicit and Implicit Waits
• Tutorial #16 – Handling Alerts/popups
• Tutorial #17 – Commonly used commands
• Tutorial #18 – Handling Web Tables, Frames, Dynamic Elements
• Tutorial #19 – Exception Handling
84
Tutorial #8 – Selenium WebDriver Introduction (Must Read)
Introduction
WebDriver is one of the most powerful and popular tools of Selenium toolkit. WebDriver comes as an extended
version to Selenium RC with superfluous advantages and addresses many of its limitations. WebDriver extends
its support to many latest browsers and platforms unlike Selenium IDE. WebDriver also doesn’t require
Selenium server to be started prior to execution of the test scripts unlike Selenium RC.
Selenium RC in aggregation with WebDriver API is known as Selenium 2.0. Selenium was so developed in
order to support dynamic web pages and Ajax calls. It also supports various drivers to exercise web based
mobile testing.
Architecture
WebDriver is a web-based testing tool with a subtle difference with Selenium RC. Since, the tool was built on
the fundamental where an isolated client was created for each of the web browser; no JavaScript Heavy lifting
was required as we discussed in our very first tutorial.
WebDriver makes direct calls to the Web browser and the entire test script is executed in this fashion.
WebDriver uses the browsers support and capabilities to automation.
85
Unlike Selenium RC, Selenium WebDriver doesn’t essentially require Selenium Server to be started before
launching the test script execution. User can leverage the benefit and may or may not require Selenium Server if
he/she desires to perform the test execution on the same machine where the browser is residing.
WebDriver supports diverse range of web browsers and their versions. It supports all the conventional browsers
in addition to some unique and rare browsers like HtmlUnit browser unlike Selenium RC and Selenium IDE.
86
HtmlUnit Browser executes the test scripts analogous to other browsers except the fact that it runs in the
headless mode i.e. GUI-less mode and the user won’t be able to view the test script execution. Said that the test
script execution transpires in headless mode, thus the execution speed takes a roll and quickens the execution.
WebDriver also supports web based mobile testing. Thus it provides AndroidDriver and IphoneDriver to back
web based mobile testing.
Speed
When compared to other tools of Selenium suite, WebDriver turns out to be the fastest tool amongst all. The
communication is not channelized via any external intervention; rather the tool directly communicates with the
browser same as that of any user. Thus, WebDriver takes advantage of the browser’s native compatibility
towards automation.
87
Other tools from Selenium suite like Selenium RC don’t communicate directly with the web browser. Client
libraries (test scripts written in any programming language) communicate with Selenium Remote Control
Server and Remote Control communicates with a Selenium Core (JavaScript Program) which in turn
communicates with the web browser. Hence, this sort of twisted communication results as a hindrance on
execution speed.
With the advent of mobile era, WebDriver API has also matured and introduced some of the key technologies to
enter this horizon. WebDriver enables user to perform web based mobile testing. It provides two of the
essentials drivers to perform web based mobile testing.
AndriodDriver
IphoneDriver
Moreover, WebDriver API is fairly simple and easy. It doesn’t include repetitious commands. On the contrary,
Selenium RC embodies many of the tautological commands.
Conclusion
88
In this tutorial, we tried to make you acquainted with Selenium WebDriver by outlining its architecture, features
and limitations.
About the author: Shruti Shrivastava is currently working as a Senior Test Engineer with 4+ years of
automation testing experience. She is an ISTQB certified professional and also an active blogger, always
interested in solving testing related problems.
We also have two more authors on this Selenium tutorial’s series to make it complete, useful and relevant.
If you have any specific requests/queries about this or any other tutorial in this Selenium online training
series, let us know in comments.
89
Tutorial #9 – Selenium WebDriver Installation with eclipse
In the previous tutorial, we introduced the basic architecture and features of WebDriver. This is 9th tutorial
in Selenium Tutorial Training Series.
In this tutorial, we would be discussing about the installation procedure to get started with WebDriver
initiating from the scratch. We would also be discussing about the diverse range of drivers provided by
WebDriver, each catering to different testing and environmental needs.
To be able to use WebDriver for scripting, there are some pre-requisites that need to be in place like the basic
environment setup. In this series, we would be using Java as a programming language within our sample
examples. Thus let us kick start with the Java installation.
Java Installation
Step 1: Go to Oracle official site – “JAVA download”, download Java Platform, Standard Edition. All the
recent releases are available on the page.
Step 2: As soon as you click on the Download button, following screen would appear. Accept the License
agreement for Java installation and choose amongst the various catalogued Java Development Kit’s. Select the
one that best suits your system configuration.
90
Remember to download JDK (Java development kit). The kit comes with a JRE (Java Runtime environment).
Thus the user isn’t required to download and install the JRE separately.
91
Step 2: As soon as we click on the download link, the user is re-directed to the fresh page securing information
about the current download. Click on the download icon and you are done.
It may take a few minutes before you can download the complete zip folder.
Step 3: Once downloaded, copy the folder and place it in the desired location on your file system.
Step 4: Extract the zipped folder, a folder named as eclipse can be seen. The folder embodies all the required
application and source files.
92
Step 5: Launch the eclipse IDE using “eclipse.exe” residing inside the eclipse folder. Refer the above
illustration for the same.
Step 6: The application will prompt you to specify the workspace location. Workspace is that location where all
your eclipse projects will be residing. Enter/Browse the desired location or the user can simply opt for the
default location and click on the OK button.
Configuring WebDriver
As we would be using Java as the programming language for this series and in order to create test scripts in
java, we would have to introduce language- specific client drivers. Thus, let us begin with the downloading of
Selenium Java Client Libraries.
93
It may take a few minutes before you can download the complete zipped folder.
Step 2: Once downloaded, copy the folder and place it in the desired location on your file system.
Step 3: Extract the zipped folder, a folder named as “Selenium-2.41.0.zip“can be seen. The folder embodies all
the required jar files which enable users to create test scripts in Java.
Thus these libraries can be configured in Eclipse IDE.
Step 2: Provide a user defined name for your Java Project. Let us provide the name as Learning_Selenium and
Click on the Finish Button. The newly created project can be viewed at the left side of the screen in the package
explorer panel.
Step 3: Create a new Java class named as “First_WebdriverClass” under the source folder by right clicking on it
and navigating to New -> class.
94
Step 4: Now let us configure the libraries into our Java project. For this, select the project and Right click on it.
Select “Properties” within the listed options. The following screen appears, Select “Java Build Path” from the
options.
Step 5: By default, “Libraries” tab is opened. If not, click on the “Libraries” tab. Then, click on the “Add
External Jars…” button. Browse to the location where we have saved the extracted folder for Java Client
Libraries.
Step 6: Select all the JAR files present in the “selenium-java-2.41.0” folder and click on open button within the
dialog box. The properties dialog box should look like the below illustration.
Step 7: Click on the “OK” button within the dialog box so as to complete the configuration part of Selenium
Libraries in our java project.
95
The project will look like the following:
Available Drivers
There are a number of driver classes available in WebDriver, each catering a specific web browser. Each
browser has a different driver implementation in WebDriver.
In WebDriver, a few of the browsers can be automated directly where as some of the web browsers require an
external entity to be able to automate and execute the test script. This external entity is known as Driver Server.
Thus, user is required to download the Driver Server for different web browsers.
Notice that there is a separate Driver Server for each of the web browser and user cannot use one Driver Server
for web browsers other than the one it is designated for.
Below is the list of available web browsers and their corresponding Server Drivers.
Conclusion
In this tutorial, we accustomed you with all the environment setup and installation to be done prior to creation
of WebDriver test scripts.
Prior to the creation of WebDriver based test scripts, few utilities and packages are required to be
installed.
Install JDK (Java Development Kit). Remember, the user is not supposed to install JRE separately
because it is distributed bundled with the kit.
96
Download Eclipse IDE. User is only required to download the package and he/she is good to go. No
other installation is required with Eclipse.
Download Java Client Libraries to be able to create test script in java programming language.
Launch eclipse using eclipse.exe. Select the workspace where you would want to save the projects.
Create a new java project in the eclipse. Create a new java class within the project.
Configure the eclipse by importing jars files for Java Client Drivers.
In WebDriver, a few of the browsers can be automated directly where as some of the web browsers
require an external Driver Server.
Firefox and HTML Unit are the only browsers that cannot be automated directly. Thus they do not
require any separate Driver Server. All other commonly known web browsers like Chrome, Safari,
Internet Explorer etc. requires Driver Servers.
Next Tutorial #10 => Now that we are done with the entire setup and installation, in the next tutorial we would
create our own WebDriver test script using Java.
A remark for the readers: While our next tutorial of the Selenium tutorials series is in the processing mode,
install the packages mentioned in this tutorial and the required utilities to get started. Most of the WebDriver
related packages can be found at the Selenium’s official website.
Let us know if you face any issues in installation process.
97
Tutorial #10 – My first Selenium WebDriver script (Must Read)
In the previous two tutorials, we made you acquainted with the basic architecture and features of
WebDriver and the infrastructure required to get started with Selenium WebDriver. Assuming that you all might
have set up the system with all the necessary utilities and packages, we will move further with the
implementation of our first WebDriver test script.
Therefore, motioning ahead with the consequent Selenium WebDriver tutorial, we would be creating
WebDriver script. We would also scatter the light on the basic and commonly used WebDriver commands.
We would also learn about the locating strategies of UI elements and their inclusion in the test scripts. We
would also study Get Commands in the detail.
Script Creation
For script creation, we would be using “Learning_Selenium” project created in the previous tutorial and
“gmail.com” as the application under test (AUT).
Scenario:
Launch the browser and open “Gmail.com”.
Verify the title of the page and print the verification result.
Enter the username and Password.
Click on the Sign in button.
Close the web browser.
Step 1: Create a new java class named as “Gmail_Login” under the “Learning_Selenium” project.
Step 2: Copy and paste the below code in the “Gmail_Login.java” class.
1 import org.openqa.selenium.By;
2 import org.openqa.selenium.WebDriver;
3 import org.openqa.selenium.WebElement;
4 import org.openqa.selenium.firefox.FirefoxDriver;
5
6 public class Gmail_Login {
7 /**
8 * @param args
9 */
10 public static void main(String[] args) {
11
12 // objects and variables instantiation
13 WebDriver driver = new FirefoxDriver();
14 String appUrl = "https://accounts.google.com";
98
15
16 // launch the firefox browser and open the application url
17 driver.get(appUrl);
18
19 // maximize the browser window
20 driver.manage().window().maximize();
21
22 // declare and initialize the variable to store the expected title of the webpage.
23 String expectedTitle = " Sign in - Google Accounts ";
24
25 // fetch the title of the web page and save it into a string variable
26 String actualTitle = driver.getTitle();
27
28 // compare the expected title of the page with the actual title of the page and print the result
29 if (expectedTitle.equals(actualTitle))
30 {
31 System.out.println("Verification Successful - The correct title is displayed on the web page.");
32 }
33 else
34 {
35 System.out.println("Verification Failed - An incorrect title is displayed on the web page.");
36 }
37
38 // enter a valid username in the email textbox
39 WebElement username = driver.findElement(By.id("Email"));
40 username.clear();
41 username.sendKeys("TestSelenium");
42
43 // enter a valid password in the password textbox
44 WebElement password = driver.findElement(By.id("Passwd"));
45 password.clear();
46 password.sendKeys("password123");
47
48 // click on the Sign in button
49 WebElement SignInButton = driver.findElement(By.id("signIn"));
50 SignInButton.click();
51
52 // close the web browser
53 driver.close();
54 System.out.println("Test script executed successfully.");
55
56 // terminate the program
57 System.exit(0);
58 }
59 }
99
The above code is equivalent to the textual scenario presented earlier.
Code Walkthrough
Import Statements:
1 import org.openqa.selenium.WebDriver;
2 import org.openqa.selenium.firefox.FirefoxDriver;
3 import org.openqa.selenium.WebElement;
4 import org.openqa.selenium.By;
Object Instantiation
WebDriver driver = new FirefoxDriver();
We create a reference variable for WebDriver interface and instantiate it using FirefoxDriver class. A default
Firefox profile will be launched which means that no extensions and plugins would be loaded with the Firefox
instance and that it runs in the safe mode.
100
The getTitle() method is used to fetch the title of the current web page. Thus, the fetched title can be loaded to a
string variable.
Comparison between Expected and Actual Values:
1 if (expectedTitle.equals(actualTitle))
2 {
3 System.out.println("Verification Successful - The correct title is displayed on the web page.");
4 }
5 else
6 {
7 System.out.println("Verification Failed - An incorrect title is displayed on the web page.");
8 }
The above code uses the conditional statement java constructs to compare the actual value and the expected
value. Based on the result obtained, the print statement would be executed.
WebElement Instantiation
WebElement username = driver.findElement(By.id(“Email”));
In the above statement, we instantiate the WebElement reference with the help
of “driver.findElement(By.id(“Email”))”. Thus, username can be used to reference the Email textbox on the
user interface every time we want to perform some action on it.
Clear Command
username.clear();
The clear() method/command is used to clear the value present in the textbox if any. It also clears the default
placeholder value.
sendKeys Command
username.sendKeys(“TestSelenium “);
The sendKeys() method/command is used to enter/type the specified value (within the parentheses ) in the
textbox. Notice that the sendKeys() method is called on the WebElement object which was instantiated with the
help of element property corresponding to the UI element.
The above block of code enters the string “TestSelenium” inside the Email textbox on the Gmail application.
sendKeys is one of the most popularly used commands across the WebDriver scripts.
Click Command
SignInButton.click();
Like sendKeys(), click() is another excessively used command to interact with the web
elements. Click() command/method is used to click on the web element present on the web page.
The above block of code clicks on the “Sign in” button present on the Gmail application.
101
Notes:
Unlike sendKeys() method, click() methods can never be parameterized.
At times, clicking on a web element may load a new page altogether. Thus to sustain such cases, click()
method is coded in a way to wait until the page is loaded.
Close the Web Browser
driver.close();
The close() is used to close the current browser window.
Test Execution
The test script or simply the java program can be executed in the following ways:
#1. Under the Eclipse’s menu bar, there is an icon to execute the test script. Refer the following figure.
Make a note that only the class which is selected would be executed.
#2. Right click anywhere inside the class within the editor, select “Run As” option and click on the “Java
Application”.
#3. Another shortcut to execute the test script is – Press ctrl + F11.
At the end of the execution cycle, the print statement “Test script executed successfully.” can be found in the
console.
102
paste the target value within the WebDriver code. The types of locators and the locating strategies are pretty
much the same except for the syntax and their application.
In WebDriver, web elements are located with the help of the dynamic finders
(findElement(By.locatorType(“locator value”))).
driver.findElement(By.id(“Email”));
103
Locator Types and their Syntax
Conclusion
In this tutorial, we developed an automation script using WebDriver and Java. We also discussed the various
components that constitute a WebDriver script.
104
Next tutorial #11: Before diving deep into Frameworks we will see details about JUnit – an open source unit
testing tool. Most of the programmers use JUnit as it is easy and does not take much effort to test. This tutorial
will give an insight about JUnit and its usage in selenium script.
A remark for the readers: While our next tutorial of the Selenium series is in the processing mode, readers
can start creating their own basic WebDriver scripts. For more advance scripts and concepts, we will have
various other Selenium WebDriver tutorials coming up in this series.
Let us know in comments if you have any problem creating or executing the WebDriver scripts.
105
Tutorial #11 – Introduction to JUnit
This tutorial will give an insight about JUnit and its usage in selenium script. This is tutorial #11 in
our comprehensive Selenium tutorials series.
Basically JUnit is an open source unit testing tool and used to test small/large units of code. To run the JUnit
test you don’t have to create class object or define main method. JUnit provide assertion library which is used to
evaluate the test result. Annotations of JUnit are used to run the test method. JUnit is also used to run the
Automation suite having multiple test cases.
Adding JUnit library in Java project
First we will learn how to add JUnit library in your Java project:
106
Step #4: Select Junit4->Finish
107
Step #5: Click OK.
There are many frameworks like Data Driven Framework, Keyword Driven Framework, and Hybrid
Framework which use Junit tool as test runner and which will help to start the batch execution and reporting.
108
#1. @Test
@Test annotation is used to run a Junit test.
Example:
1 @Test
2 public void junitTest()
3{
4 System.out.println("Running Junit test");
5 Assert.assertEquals(1,1);
6}
#2. @Before:
@Before annotation is used to run any specific test before each test.
1 public class Junttest {
2 @Before
3 public void beforeTest(){
4 System.out.println("Running before test");
5}
6
7 @Test
8 public void junitTest(){
9 System.out.println("Running Junit test");
10 }
11 }
Output:
Running before test
Running Junit test
Example of before annotation using two junit test method.
109
13 public void secondJunitTest(){
14 System.out.println("Running second Junit test");
15 }
16 }
Output:
Running before test
Running Junit test
Running before test
Running second Junit test
Before running junitTest method beforeTest method will run. Similarly before running secondJuntiTest again
beforeTest method will run and produces output like above.
#3. @BeforeClass
This method executes once before running all test. The method has to be a static method. Initialization of
properties files, databases etc are done in beforeClass method.
Output:
Executed before class method
Running Junit test
Running second Junit test
#4. @After
This method executes after each test.
110
3 public void junitTest(){
4 System.out.println("Running Junit test");
5}
6
7 @After
8 public void afterTest(){
9 System.out.println("Running after method");
10 }
11 }
Output:
Running Junit test
Running after method
#5. @AfterClass
Like @BeforeClass, @AfterClass executes once after executing all test methods. Like @BeforeClass method,
@AfterClass method has to be a static method.
111
#6. Parameterized Junit class:
Parameterized class is used to run same scenario with multiple dataset.
@Parameters annotation tag is used to pass multiple data. Here, we have taken 2*2 dimensional array and the
data can be visualized like below:
1 @RunWith(Parameterized.class)
2 public class Junttest {
3 public String name;
4 public int age;
5 public Junttest(String name,int age){
6 this.name=name;
7 this.age=age;
8}
9
10 @Test
11 public void testMethod(){
12 System.out.println("Name is: "+name +" and age is: "+age);
13 }
14
15 @Parameters
16 public static Collection<Object[]> parameter(){
17 Object[][] pData=new Object[2][2];
18 pData[0][0]="Tom";
19 pData[0][1]=30;
20 pData[1][0]="Harry";
21 pData[1][1]=40;
22 return Arrays.asList(pData);
23 }
24 }
JUnit Assertions
JUnit assertEquals: This checks if the two values are equal and assertion fails if both values are not equal.
This compares Boolean, int, String, float, long, char etc.
Syntax:
Assert.assertEqual(“excepted value”, ”actual value”);
112
Example:
Assert.assertEqual(“ABC”,”ABC”); //Both the strings are equal and assertion will pass.
Assert.assertEqual(“ABC”,”DEF”); //Assertion will fail as both the strings are not equal.
Assert.assertEqual(“Strings are not equal”, “ABC”,”DEF”); //message will be thrown if equal condition is not
satisfied.
Below is the example of use of JUnit assertion in selenium:
1 String username=driver.findElement(By.id(“username”)).getText();
2 String password=driver.findElement(By.id(“password”)).getText();
3 Assert.assertEqual(“Mismatch in both the string”, username, password);
In above example assertion will fail as both the strings are not equal. One is text of username field and other is
the text of password field.
JUnit assertTrue: Returns true if the condition is true and assertion fails if the condition is false.
Assert.assertTrue(“message”, condition);
Assert.assertTrue(“Both the strings are not equal”, (“HelloWorld”).equals(“HelloWorld”));
Here assertion will pass as both the strings match. It will print message if the assertion fails.
JUnit assertFalse: Returns true if the condition is false and assertion fails if the condition is true.
Assert.assertFalse(“message”, condition);
Assert.assertFalse(“Both the strings are equal”, (“Hello”).equals(“HelloWorld”));
There will not be any assertion error as the condition is false.
Conclusion:
Most of the programmers use Junit as it is easy and does not take much effort to test. A simple green or red bar
will show the actual result of the test. Junit makes life easy as it has its own set of libraries and annotations.
Here we have also described commonly used annotations used with selenium scripts and framework.
More detail about framework and use of Junit annotations will be discussed in upcoming tutorial which is
dedicated exclusively for framework design using Junit. This tutorial will help us in designing the framework
using Junit.
Next Tutorial #12: In next tutorial we would discuss all about TestNG, its features and its applications.
TestNG is an advance framework designed in a way to leverage the benefits by both the developers and testers.
113
Tutorial #12 – Introduction to TestNG (Must Read)
In the last few tutorials, we shed light on the basic and commonly used WebDriver commands. We also learned
about the locating strategies of UI elements and their inclusion in the test scripts. And therefore, we developed
our very first WebDriver Automation Test Script.
Moving ahead with this tutorial, we would discuss all about TestNG, its features and its applications.
TestNG is an advance framework designed in a way to leverage the benefits by both the developers and
testers. For people already using JUnit, TestNG would seem no different with some advance features. With the
commencement of the frameworks, JUnit gained an enormous popularity across the Java applications, Java
developers and Java testers, with remarkably increasing the code quality.
See also => JUnit Tutorial and its usage in Selenium scripts
Despite being an easy to use and straightforward framework, JUnit has its own limitations which give rise to the
need of bringing TestNG into the picture. TestNG was created by an acclaimed programmer named as “Cedric
Beust”. TestNG is an open source framework which is distributed under the Apache software License and is
readily available for download.
Talking about our requirement to introduce TestNG with WebDriver is that it provides an efficient and effective
test result format that can in turn be shared with the stake holders to have a glimpse on the
product’s/application’s health thereby eliminating the drawback of WebDriver’s incapability to generate test
reports. TestNG has an inbuilt exception handling mechanism which lets the program to run without terminating
unexpectedly.
Both TestNG and JUnit belong to the same family of Unit Frameworks where TestNG is an extended version to
JUnit and is more extensively used in the current testing era.
Features of TestNG
Support for annotations
Support for parameterization
Advance execution methodology that do not require test suites to be created
Support for Data Driven Testing using Dataproviders
Enables user to set execution priorities for the test methods
Supports threat safe environment when executing multiple threads
Readily supports integration with various tools and plug-ins like build tools (Ant, Maven etc.),
Integrated Development Environment (Eclipse).
114
Facilitates user with effective means of Report Generation using ReportNG
TestNG versus JUnit
There are various advantages that make TestNG superior to JUnit. Some of them are:
So now let us get started with the installation and implementation part.
Step 2: Enter the keyword “TestNG” in the search textbox and click on “Go” button as shown below.
115
Step 3: As soon as the user clicks on the “Go” button, the results matching to the search string would be
displayed. Now user can click on the Install button to install TestNG.
Step 4: As soon as the user clicks on the Install button, the user is prompted with a window to confirm the
installation. Click on “Confirm” button.
116
Step 5: In the next step, the application would prompt you to accept the license and then click on the “Finish”
button.
Step 6: The installation is initiated now and the progress can be seen as following:
Upon restart, user can verify the TestNG installation by navigating to “Preferences” from “Window” option in
the menu bar. Refer the following figure for the same.
117
Creation of Sample TestNG project
Let us begin with the creation of TestNG project in eclipse IDE.
Step 1: Click on the File option within the menu -> Click on New -> Select Java Project.
Step 2: Enter the project name as “DemoTestNG” and click on “Next” button. As a concluding step, click on
the “Finish” button and your Java project is ready.
Step 3: The next step is to configure the TestNG library into the newly created Java project. For the same, Click
on the “Libraries” tab under Configure Build Path. Click on “Add library” as shown below.
118
Step 4: The user would be subjected with a dialog box promoting him/her to select the library to be configured.
Select TestNG and click on the “Next” button as shown below in the image. In the end, click on the “Finish”
button.
The TestNG is now added to the Java project and the required libraries can be seen in the package explorer
upon expanding the project.
119
Add all the downloaded Selenium libraries and jars in the project’s build path as illustrated in the previous
tutorial.
Step 1: Expand the “DemoTestNG” project and traverse to “src” folder. Right click on the “src”package and
navigate to New -> Other..
Step 2: Expand TestNG option and select “TestNG” class option and click on the “Next” button.
120
Step 3: Furnish the required details as following. Specify the Source folder, package name and the TestNG
class name and click on the Finish button. As it is evident from the below picture, user can also check various
TestNG notations that would be reflected in the test class schema. TestNG annotations would be discussed later
in this session.
------------
121
The above mentioned TestNG class would be created with the default schema.
Now that we have created the basic foundation for the TestNG test script, let us now inject the actual test code.
We are using the same code we used in the previous session.
Scenario:
Launch the browser and open “gmail.com”.
Verify the title of the page and print the verification result.
Enter the username and Password.
Click on the Sign in button.
Close the web browser.
Code:
1 package TestNG;
2 import org.openqa.selenium.By;
3 import org.openqa.selenium.WebDriver;
4 import org.openqa.selenium.WebElement;
5 import org.openqa.selenium.firefox.FirefoxDriver;
6 import org.testng.Assert;
7 import org.testng.annotations.Test;
8
9 public class DemoTestNG {
10 public WebDriver driver = new FirefoxDriver();
11 String appUrl = "https://accounts.google.com";
12
13 @Test
14 public void gmailLogin() {
15 // launch the firefox browser and open the application url
16 driver.get("https://gmail.com");
17
18 // maximize the browser window
19 driver.manage().window().maximize();
20
122
21 // declare and initialize the variable to store the expected title of the webpage.
22 String expectedTitle = " Sign in - Google Accounts ";
23
24 // fetch the title of the web page and save it into a string variable
25 String actualTitle = driver.getTitle();
26 Assert.assertEquals(expectedTitle,actualTitle);
27
28 // enter a valid username in the email textbox
29 WebElement username = driver.findElement(By.id("Email"));
30 username.clear();
31 username.sendKeys("TestSelenium");
32
33 // enter a valid password in the password textbox
34 WebElement password = driver.findElement(By.id("Passwd"));
35 password.clear();
36 password.sendKeys("password123");
37
38 // click on the Sign in button
39 WebElement SignInButton = driver.findElement(By.id("signIn"));
40 SignInButton.click();
41
42 // close the web browser
43 driver.close();
44 }
45 }
=> Right click anywhere inside the class within the editor or the java class within the package explorer, select
“Run As” option and click on the “TestNG Test”.
123
TestNG result is displayed into two windows:
Console Window
TestNG Result Window
Refer the below screencasts for the result windows:
124
HTML Reports
TestNG comes with a great capability of generating user readable and comprehensible HTML reports for the
test executions. These reports can be viewed in any of the browser and it can also be viewed using Eclipse’s
build –in browser support.
To generate the HTML report, follow the below steps:
Step 1: Execute the newly created TestNG class. Refresh the project containing the TestNG class by right
clicking on it and selecting “Refresh” option.
Step 2: A folder named as “test-output” shall be generated in the project at the “src” folder level. Expand the
“test-output” folder and open on the “emailable-report.html” file with the Eclipse browser. The HTML file
displays the result of the recent execution.
125
Step 3: The HTML report shall be opened with in the eclipse environment. Refer the below image for the same.
Refresh the page to see the results for fresh executions if any.
Setting Priority in TestNG
Code Snippet
1 package TestNG;
2 import org.testng.annotations.*;
3 public class SettingPriority {
4
5 @Test(priority=0)
6 public void method1() {
7 }
8
9 @Test(priority=1)
10 public void method2() {
11 }
12
13 @Test(priority=2)
14 public void method3() {
15 }
126
16 }
Code Walkthrough
If a test script is composed of more than one test method, the execution priority and sequence can be set using
TestNG annotation “@Test” and by setting a value for the “priority” parameter.
In the above code snippet, all the methods are annotated with the help @Test and the priorities are set to 0, 1
and 2. Thus the order of execution in which the test methods would be executed is:
Method1
Method2
Method3
Support for Annotations
There are number of annotations provided in TestNG and JUnit. The subtle difference is that TestNG provides
some more advance annotations to JUnit.
TestNG Annotations:
Following is the list of the most useful and favorable annotations in TestNG:
Annotation Description
127
Annotation Description
Note: Many of the aforementioned annotations can be exercised in JUnit 3 and JUnit 4 framework also.
Conclusion
Through this tutorial, we tried to make you acquainted with a java based testing framework named as TestNG.
We started off the session with the installation of the framework and moved with the script creation and
advance topics. We discussed all the annotations provided by TestNG. We implemented and executed our first
TestNG test script using annotations and assert statements.
Article summary:
TestNG is an advance framework designed in a way to leverage the benefits by both the developers and
testers.
TestNG is an open source framework which is distributed under the Apache software License and is
readily available for download.
TestNG is considered to be superior to JUnit because of its advance features.
Features of TestNG
Support for Annotations
Advance execution methodology that do not require test suites to be created
128
Support for parameterization
Support for Data Driven Testing using Dataproviders
Setting execution priorities for the test methods
Supports threat safe environment when executing multiple threads
Readily supports integration with various tools and plug-ins like build tools (Ant, Maven etc.),
Integrated Development Environment (Eclipse).
Facilitates user with effective means of Report Generation using ReportNG
Advantages of TestNG over JUnit
Added advance and easy annotations
Execution patterns can be set
Concurrent execution of test scripts
Test case dependencies can be set
TestNG is freely available and can be easily installed in the Eclipse IDE using Eclipse Market.
Upon installation, TestNG would be available as a library within the Eclipse environment.
Create a new Java Project and configure the build path using TestNG library.
Create a new TestNG class by expanding the created TestNG project and traverse to its “src” folder.
Right click on the “src” package and navigate to New -> Other. Select TestNG class option.
@Test is one of the annotations provided by TestNG. This annotation lets the program execution to
know that method annotated as @Test is a test method. To be able to use different TestNG annotations,
we need to import the package “import org.testng.annotations.*”.
There is no need of main() method while creating test scripts using TestNG.
We use Assert class while comparing expected and the actual value. Assert class is used to perform
various verifications. To be able to use different assertions, we are required to import
“import org.testng.Assert”.
If a test script is composed of more than one test methods, the execution priority and sequence can be set
using TestNG annotation “@Test” and by setting a value for the “priority” parameter.
TestNG has a capability of generating human readable test execution reports automatically. These
reports can be viewed in any of the browser and it can also be viewed using Eclipse’s built – in browser
support.
Next Tutorial #13: Moving ahead with the upcoming tutorials in the Selenium series, we would concentrate on
handling the various types of web elements available on the web pages. Therefore, in the next tutorial, we
would concentrate our focus on “dropdowns” and will exercise their handling strategies. We would also
discuss about WebDriver’s Select class and its methods to select values in the dropdowns.
A remark for the readers: While our next tutorial of the Selenium series is in the processing mode, readers can
start creating their own basic WebDriver scripts using TestNG framework.
For more advance scripts and concepts, include as many annotations and assertions in your TestNG classes and
execute them using TestNG environment. Also analyze the HTML reports generated by TestNG.
129
Tutorial #13 – Handling Drop-downs
In the previous tutorial, we studied about the various types of assert statements available in Java based unit
testing framework and their applications with specimens. Re-iterating the fact that being an “Automation Test
Engineer”, assertions play a very decisive and significant role in developing test scripts.
Moving ahead with the few upcoming tutorials in the Selenium series, we would concentrate on handling the
various types of web elements available on the web pages. Therefore, in this tutorial, we would
consider “dropdowns” and exercise their handling strategies.
Before moving towards problem statement and its resolution, let us take a moment to introduce and create an
understanding regarding the application under test. As a sample, we have created a dummy HTML
page consisting of multiple and assorted web elements.
The elementary web elements those constitute the web page are:
Hyperlink
Button
Dropdown
Please take a reference of the following webpage aforementioned above:
Hyperlink: The two hyperlinks namely “Google” and “abodeQA” have been provided that re-directs the
user to “https://www.google.co.in/” and “http://www.abodeqa.com/” respectively on the click event.
Dropdown: The three dropdowns have been created for selecting colors, fruits and animals with a value
already set to default.
Button: A “try it” button has been created to show up the pop up box having Ok and Cancel button upon
click event.
Subsequent is the HTML code used to create the above mentioned webpage:
1 <!DOCTYPE html>
2 <html>
3 <head><title> Testing Select Class </title>
4 <body>
5 <div id="header">
6 <ul id="linkTabs">
7 <li>
8 <a href="https://www.google.co.in/">Google</a>
9 </li>
10 <li>
11 <a href="http://abodeqa.wordpress.com/">abodeQA</a>
12 </li>
13 </ul>
14 </div>
15 <div class="header_spacer"></div>
16 <div id="container">
17 <div id="content" style="padding-left: 185px;">
18 <table id="selectTable">
19 <tbody>
20 <tr>
21 <td>
22 <div>
23 <select id="SelectID_One">
24 <option value="redvalue">Red</option>
25 <option value="greenvalue">Green</option>
26 <option value="yellowvalue">Yellow</option>
27 <option value="greyvalue">Grey</option>
28 </select>
29 </div>
30 </td>
31 <td>
32 <div>
33 <select id="SelectID_Two">
34 <option value="applevalue">Apple</option>
131
35 <option value="orangevalue">Orange</option>
<option value="mangovalue">Mango</option
36
>
37 <option value="limevalue">Lime</option>
38 </select>
39 </div>
40 </td>
41 <td>
42 <div>
43 <select id="SelectID_Three">
44 <option value="selectValue">Select</option>
45 <option value="elephantvalue">Elephant</option>
46 <option value="mousevalue">Mouse</option>
47 <option value="dogvalue">Dog</option>
48 </select>
49 </div>
50 </td>
51 </tr>
52 <tr>
53 <td>
54 <!DOCTYPE html>
55 <html>
56 <body>
57 <p>Click the button to display a confirm box.</p>
58 <button onclick="myFunction()">Try it</button>
59 <script>
60 function myFunction()
61 {
62 confirm("Press a button!");
63 }
64 </script>
65 </body>
66 </html>
67 </td>
68 </tr>
69 </tbody>
70 </table>
71 </div>
72 </div>
73 </body>
74 </html>
Scenario to be automated
Launch the web browser and open the webpage
Click on the “Google” hyperlink
Navigate back to the original web page
132
Select the “Green” in color dropdown
Select the “Orange” in the fruit dropdown
Select the “Elephant” in the animal dropdown
WebDriver Code using Selenium Select Class
Please take a note that, for script creation, we would be using “Learning_Selenium” project created in the
former tutorial.
Step 1: Create a new java class named as “HandlingDropDown” under the “Learning_Selenium” project.
Step 2: Copy and paste the below code in the “HandlingDropDown.java” class.
Below is the test script that is equivalent to the above mentioned scenario:
1 import static org.junit.Assert.*;
2 import org.junit.After;
3 import org.junit.Before;
4 import org.junit.Test;
5 import org.openqa.selenium.By;
6 import org.openqa.selenium.WebDriver;
7 import org.openqa.selenium.firefox.FirefoxDriver;
8 import org.openqa.selenium.support.ui.Select;
9
10 /**
11 * class description
12 */
13
14 public class HandlingDropDown {
15 WebDriver driver;
16
17 /**
18 * Set up browser settings and open the application
19 */
20
21 @Before
22 public void setUp() {
23 driver=new FirefoxDriver();
24
25 // Opened the application
26 driver.get("file:///F:/Work/Blogs/testingstuff/DemoWebAlert.html");
27 driver.manage().window().maximize();
28 }
29
30 /**
31 * Test to select the dropdown values
32 * @throws InterruptedException
33 */
133
34
35 @Test
36 public void testSelectFunctionality() throwsInterruptedException {
37
38 // Go to google
39 driver.findElement(By.linkText("Google")).click();
40
// navigate back to previous
41
webpage
42 driver.navigate().back();
43 Thread.sleep(5000);
44
45 // select the first operator using "select by value"
46 Select selectByValue = newSelect(driver.findElement(By.id("SelectID_One")));
47 selectByValue.selectByValue("greenvalue");
48 Thread.sleep(5000);
49
50 // select the second dropdown using "select by visible text"
51 Select selectByVisibleText = new Select (driver.findElement(By.id("SelectID_Two")));
52 selectByVisibleText.selectByVisibleText("Lime");
53 Thread.sleep(5000);
54
55 // select the third dropdown using "select by index"
56 Select selectByIndex = newSelect(driver.findElement(By.id("SelectID_Three")));
57 selectByIndex.selectByIndex(2);
58 Thread.sleep(5000);
59 }
60
61 /**
62 * Tear down the setup after test completes
63 */
64
65 @After
66 public void tearDown() {
67 driver.quit();
68 }
69 }
Code Walkthrough
Import Statements
import org.openqa.selenium.support.ui.Select – Import this package prior to the script creation. The
package references to the Select class which is required to handle the dropdown.
Object Instantiation for Select class
Select selectByValue = new Select(driver.findElement(By.id(“SelectID_One”)));
134
We create a reference variable for Select class and instantiate it using Select class and the identifier for the drop
down.
The identifier or the locator value for the drop down can be found using the techniques discussed in the initial
tutorials (by using Selenium IDE and firebug).
Take a notice that the identifier for a dropdown can be found as below:
Step 1: Most or almost all the dropdowns elements are defined in the <Select> tag having multiple values
(values that can be set into the dropdown) that are defined under the <option> tags.
135
In the above java command, we select the third value in the drop down using the selectByIndex() method and
parameterizing it with the index value of the element which is desired to be selected in the dropdown.
Take a note that the index value starts with “0”.
Conclusion
In this tutorial, we tried to make you acquainted with the WebDriver’s Select class that is used to handle
dropdown elements present on the web page. We also briefed you about the methods that can be used to
populate the value in the dropdown.
136
Tutorial #14 – Looping and Conditional commands
How to check visibility of web elements using various types of looping and conditional commands in
WebDriver:
Previously in the series, we discussed about WebDriver’s Select class which is primarily used to handle web
elements like dropdowns and selecting various options under the dropdowns.
Moving ahead in the Selenium series, we would be discussing about the various types of looping and
conditional commands in WebDriver like isSelected(), isEnabled() and isDispalyed(). These methods are used
to determine the visibility scope for the web elements.
So let us start with a brief introduction – WebDriver has a W3C specification that details out the information
about the different visibility preferences based out on the types of the web elements upon which the actions are
to be performed.
WebDriver facilitates the user with the following methods to check the visibility of the web elements. These
web elements can be buttons, dropboxes, checkboxes, radio buttons, labels etc.
isDisplayed()
isSelected()
isEnabled()
For an improved understanding, let us discuss the aforementioned methods with code examples.
As a specimen, we would be using the “google.com” as an application under test and the “Learning_Selenium”
project created in the previous tutorials for script generation.
Scenario to be automated
1. Launch the web browser and open the application under test – http://google.com
2. Verify the web page title
3. Verify if the “Google Search” button is displayed
4. Enter the keyword in the “Google Search” text box by which we would want to make the request
5. Verify that the “Search button” is displayed and enabled
6. Based on visibility of the Search button, click on the search button
WebDriver Code
Step 1: Create a new java class named as “VisibilityConditions” under the “Learning_Selenium” project.
Step 2: Copy and paste the below code in the “VisibilityConditions.java” class.
Below is the test script that is equivalent to the above mentioned scenario:
137
1 import org.openqa.selenium.By;
2 import org.openqa.selenium.WebDriver;
3 import org.openqa.selenium.WebElement;
4 import org.openqa.selenium.firefox.FirefoxDriver;
5
6 public class VisibilityConditions {
7
8 /**
9 * @param args
10 */
11
12 public static void main(String[] args) {
13
14 // objects and variables instantiation
15 WebDriver driver = new FirefoxDriver();
16 String appUrl = "https://google.com";
17
18 // launch the firefox browser and open the application url
19 driver.get(appUrl);
20
21 // maximize the browser window
22 driver.manage().window().maximize();
23
24 // declare and initialize the variable to store the expected title of the webpage.
25 String expectedTitle = "Google";
26
27 // fetch the title of the web page and save it into a string variable
28 String actualTitle = driver.getTitle();
29
30 // compare the expected title of the page with the actual title of the page and print the result
31 if (expectedTitle.equals(actualTitle))
32 {
33 System.out.println("Verification Successful - The correct title is displayed on the web page.");
34 }
35 else
36 {
37 System.out.println("Verification Failed - An incorrect title is displayed on the web page.");
38 }
39
40 // verify if the “Google Search” button is displayed and print the result
41 booleansubmitbuttonPresence=driver.findElement(By.id("gbqfba")).isDisplayed();
42 System.out.println(submitbuttonPresence);
43
44 // enter the keyword in the “Google Search” text box by which we would want to make the request
45 WebElement searchTextBox = driver.findElement(By.id("gbqfq"));
138
46 searchTextBox.clear();
47 searchTextBox.sendKeys("Selenium");
48
49 // verify that the “Search button” is displayed and enabled
50 boolean searchIconPresence = driver.findElement(By.id("gbqfb")).isDisplayed();
51 boolean searchIconEnabled = driver.findElement(By.id("gbqfb")).isEnabled();
52
53 if (searchIconPresence==true && searchIconEnabled==true)
54 {
55 // click on the search button
56 WebElement searchIcon = driver.findElement(By.id("gbqfb"));
57 searchIcon.click();
58 }
59
60 // close the web browser
61 driver.close();
62 System.out.println("Test script executed successfully.");
63
64 // terminate the program
65 System.exit(0);
66 }
67 }
Code Walkthrough
Following are the ways in which we ascertain the presence of web elements on the web page.
boolean submitbuttonPresence=driver.findElement(By.id(“gbqfba”)).isDisplayed();
isDispalyed()
isDisplayed() is the method used to verify presence of a web element within the webpage. The method is
designed to result a Boolean value with each success and failure. The method returns a “true” value if the
specified web element is present on the web page and a “false” value if the web element is not present on the
web page.
Thus the above code snippet verifies for the presence of submit button on the google web page and returns a
true value if the submit button is present and visible else returns a false value if the submit button is not present
on the web page.
isEnabled()
139
isEnabled() is the method used to verify if the web element is enabled or disabled within the webpage. Like
isDisplayed() method, it is designed to result a Boolean value with each success and failure. The method returns
a “true” value if the specified web element is enabled on the web page and a “false” value if the web element is
not enabled (state of being disabled) on the web page.
Thus the above code snippet verifies if the submit button is enabled or not and returns a Boolean value
depending on the result.
The isEnabled() method is significant in scenarios where we want to ascertain that only if “Condition A” is
fulfilled, then the element(principally button) is enabled. Refer the following illustration for the same.
In the above figure, Register button button is enabled only when the agreement checkbox is selected.
Akin to above methods, we have a method referenced as “isSelected()” which tests if the specified web element
is selected or not.
Thus the above code snippet verifies if the male radio button is selected or not and returns a Boolean value
depending on the result. Refer the following image for the same.
Conclusion
140
In this tutorial, we tried to make you acquainted with the WebDriver’s looping and conditional operations.
These conditional methods often deal with almost all types of visibility options for web elements.
Article Summary:
WebDriver has a W3C specification that details out the information about the different visibility
preferences based out on the types of the web elements.
isDisplayed() is the method used to verify presence of a web element within the webpage. The method
returns a “true” value if the specified web element is present on the web page and a “false” value if the
web element is not present on the web page.
isDisplayed() is capable to check for the presence of all kinds of web elements available.
isEnabled() is the method used to verify if the web element is enabled or disabled within the webpage.
isEnabled() is primarily used with buttons.
isSelected() is the method used to verify if the web element is selected or not. isSelected() method is
pre-dominantly used with radio buttons, dropdowns and checkboxes.
Next Tutorial #15: While working on web applications, often we are re-directed to different web pages by
refreshing the entire web page and re-loading the new web elements. At times there can be Ajax calls as well.
Thus, a time lag can be seen while reloading the web pages and reflecting the web elements. Thus, our next
tutorial in-line is all about dealing with such time lags by using implicit and explicit waits.
Note for the Readers: Till then, the reader can automate and test the visibility scope for the web elements using
WebDriver’s methods.
141
Tutorial #15 – Explicit and Implicit Waits
In the previous tutorial, we tried to make you acquainted with the various WebDriver’s looping and conditional
operations. These conditional methods often deal with almost all types of visibility options for web elements.
Moving ahead in this free Selenium training series, we will discuss about different types of waits provided by
the WebDriver. We will also discuss about various types of navigation options available in WebDriver.
Waits help the user to troubleshoot issues while re-directing to different web pages by refreshing the entire web
page and re-loading the new web elements. At times there can be Ajax calls as well. Thus, a time lag can be
seen while reloading the web pages and reflecting the web elements.
Users are often found navigating through various web pages back and forth. Thus, navigate()
commands/methods provided by the WebDriver helps the user to simulate the real time scenarios by navigating
between the web pages with reference to the web browser’s history.
WebDriver equips the user with two genesis of waits in order to handle the recurring page loads, web
element loads, appearance of windows, pop ups and error messages and reflection of web elements on the web
page.
Implicit Wait
Explicit Wait
Let us discuss each of them in details considering practical approach.
Key Notes
Implicit wait is a single line of a code and can be declared in the setup method of the test script.
When compared to Explicit wait, Implicit wait is transparent and uncomplicated. The syntax and
approach is simpler than explicit wait.
Being easy and simple to apply, implicit wait introduces a few drawbacks as well. It gives rise to the test script
execution time as each of the command would be ceased to wait for a stipulated amount of time before
resuming the execution.
142
Thus, in order to trouble shoot this issue, WebDriver introduces Explicit waits where we can explicitly apply
waits whenever the situation arises instead of forcefully waiting while executing each of the test step.
Import Statements
import java.util.concurrent.TimeUnit – To be able to access and apply implicit wait in our test scripts, we are
bound to import this package into our test script.
Syntax
drv.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
Include the above line of code into your test script soon after instantiation of WebDriver instance variable.
Thus, this is all what is required to set an implicit wait into your test script.
Code Walkthrough
The implicit wait mandates to pass two values as parameters. The first argument indicates the time in the
numeric digits that the system needs to wait. The second argument indicates the time measurement scale. Thus,
in the above code, we have mentioned the “30” seconds as default wait time and the time unit has been set to
“seconds”.
WebDriver introduces classes like WebDriverWait and ExpectedConditions to enforce Explicit waits into the
test scripts. In the ambit of this discussion, we will use “gmail.com” as a specimen.
Scenario to be automated
1. Launch the web browser and open the “gmail.com”
2. Enter a valid username
3. Enter a valid password
4. Click on the sign in button
5. Wait for Compose button to be visible after page load
WebDriver Code using Explicit wait
Please take a note that for script creation, we would be using “Learning_Selenium” project created in the former
tutorials.
Step 1: Create a new java class named as “Wait_Demonstration” under the “Learning_Selenium” project.
Step 2: Copy and paste the below code in the “Wait_Demonstration.java” class.
Below is the test script that is equivalent to the above mentioned scenario.
143
1 import static org.junit.Assert.*;
2 import java.util.concurrent.TimeUnit;
3 import org.junit.After;
4 import org.junit.Before;
5 import org.junit.Test;
6 import org.openqa.selenium.By;
7 import org.openqa.selenium.WebDriver;
8 import org.openqa.selenium.WebElement;
9 import org.openqa.selenium.firefox.FirefoxDriver;
10 import org.openqa.selenium.support.ui.ExpectedConditions;
11 import org.openqa.selenium.support.ui.WebDriverWait;
12
13 public class Wait_Demonstration {
14
15 // created reference variable for WebDriver
16 WebDriver drv;
17 @Before
18 public void setup() throws InterruptedException {
19
20 // initializing drv variable using FirefoxDriver
21 drv=new FirefoxDriver();
22 // launching gmail.com on the browser
23 drv.get("https://gmail.com");
24 // maximized the browser window
25 drv.manage().window().maximize();
26 drv.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
27 }
28
29 @Test
30 public void test() throws InterruptedException {
31
32 // saving the GUI element reference into a "username" variable of WebElement type
33 WebElement username = drv.findElement(By.id("Email"));
34
35 // entering username
36 username.sendKeys("shruti.shrivastava.in");
37
38 // entering password
39 drv.findElement(By.id("Passwd")).sendKeys("password");
40
41 // clicking signin button
42 drv.findElement(By.id("signIn")).click();
43
44 // explicit wait - to wait for the compose button to be click-able
45 WebDriverWait wait = newWebDriverWait(drv,30);
144
46
47 wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//div[contains(text(),'COMPOSE')]")));
48 // click on the compose button as soon as the "compose" button is visible
49 drv.findElement(By.xpath("//div[contains(text(),'COMPOSE')]")).click();
50 }
51
52 @After
53 public void teardown() {
54 // closes all the browser windows opened by web driver
55 drv.quit();
56 }
57 }
Import Statements
import org.openqa.selenium.support.ui.ExpectedConditions
import org.openqa.selenium.support.ui.WebDriverWait
Import above packages prior to the script creation. The packages refer to the Select class which is
required to handle the dropdown.
Object Instantiation for WebDriverWait class
WebDriverWait wait = new WebDriverWait(drv,30);
We create a reference variable “wait” for WebDriverWait class and instantiate it using WebDriver instance and
maximum wait time for the execution to layoff. The maximum wait time quoted is measured in “seconds”.
Expected Condition
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//div[contains(text(),'COMPOSE')]")));
drv.findElement(By.xpath("//div[contains(text(),'COMPOSE')]")).click();
The above command waits for a stipulated amount of time or an expected condition to occur whichever occurs
or elapses first.
Thus to be able to do this, we use the “wait” reference variable of WebDriverWait class created in the previous
step with ExpectedConditions class and an actual condition which is expected to occur. Therefore, as soon as
the expected condition occurs, the program control would move to the next execution step instead of forcefully
waiting for the entire 30 seconds.
In our specimen, we wait for the “compose” button to be present and loaded as a part of home page load and
thus, then we move forward with calling the click command on the “compose” button.
145
ExpectedConditions class provides a great help to deal with scenarios where we have to ascertain for a
condition to occur before executing the actual test step.
ExpectedConditions class comes with a wide range of expected conditions that can be accessed with the help of
the WebDriverWait reference variable and until() method.
146
The above command requires no parameters and takes back the user to the previous webpage in the web
browser’s history.
#2) navigate().forward()
This command lets the user to navigate to the next web page with reference to the browser’s history.
Sample code:
driver.navigate().forward();
The above command requires no parameters and takes forward the user to the next webpage in the web
browser’s history.
#3) navigate().refresh()
This command lets the user to refresh the current web page there by reloading all the web elements.
Sample code:
driver.navigate().refresh();
The above command requires no parameters and reloads the web page.
#4) navigate().to()
This command lets the user to launch a new web browser window and navigate to the specified URL.
Sample code:
driver.navigate().to(“http://google.com”);
The above command requires a web URL as a parameter and then it opens the specified URL on a freshly
launched web browser.
Conclusion
In this tutorial, we tried to make you acquainted with the WebDriver’s waits. We discussed and exercised both
the explicit and the implicit waits. At the same time, we also discussed about the different navigate commands.
147
ExpectedConditions class comes with a wide range of expected conditions that can be accessed with the
help of the WebDriverWait reference variable and until() method.
Navigate() methods/commands are used to simulate the user behavior while navigating between various
web pages back and forth.
Next Tutorial #16: Coming on to the next tutorial in the list, we would make the users familiar with various
types of alerts that may appear while accessing web sites and their handling approaches in WebDriver. The
types of alerts that we would be focusing on are majorly – windows based alert pop ups and web based alert pop
ups. As we know that handling windows based pop ups is beyond WebDriver’s capabilities, thus we would also
exercise some third party utilities to handle window pop ups.
Note for the Readers: Till then, the readers can automate the scenarios having various page loads and dynamic
elements popping up on to the screen using the various expected conditions and navigate commands.
148
Tutorial #16 – Handling Alerts/popups
Efficient Ways to Handle Windows and Web based Alerts/Popups in Selenium WebDriver:
In the previous tutorial, we focused our discussion on different types of waits provided by the WebDriver. We
also discussed about various types of navigation options available in WebDriver.
Moving ahead in the Selenium WebDriver Tutorials, we will discuss about different types of alerts available
while testing web applications and their handling strategies.
What is Alert box/ Pop up box/ confirmation Box/ Prompt/ Authentication Box?
It is nothing but a small box that appears on the display screen to give you some kind of information or to warn
you about a potentially damaging operation or it may even ask you for the permissions for the operation.
Example: Let us consider a real life example for a better understanding; Let us assume that we uploaded a
photograph on any of these popular social networking sites. Later on, i wish to delete the uploaded photograph.
So in order to delete, i clicked on the delete button. As soon as I click on the delete button, the system warns me
against my action, prompting – Do you really want to delete the file? So now we have an option to either accept
this alert or reject it.
So ahead in the session, let’s see how do we reject or accept the alerts depending on their types. Starting
with the web based pop ups.
Web Based Popups
149
Let us see how do we handle them using WebDriver.
There are the four methods that we would be using along with the Alert interface.
1) void dismiss() – The dismiss() method clicks on the “Cancel” button as soon as the pop up window appears.
2) void accept() – The accept() method clicks on the “Ok” button as soon as the pop up window appears.
3) String getText() – The getText() method returns the text displayed on the alert box.
4) void sendKeys(String stringToSend) – The sendKeys() method enters the specified string pattern into the
alert box.
Let us move ahead and look at the actual implementation.
Explanation of Application under Test
We have designed a web page in a way to include a few fundamental types of web elements. This is the same
application we introduced while discussing Select class earlier in this series.
Hyperlink: The two hyperlinks namely “Google” and “abodeQA” have been provided that re-directs the
user to “http://www.google.com/” and “http://www.abodeqa.com/” respectively on the click event.
Dropdown: The three hyperlinks have been created for selecting colors, fruits and animals with a value
set to default.
Button: A “try it” button has been created to show up the pop up box having OK and Cancel buttons
upon click event.
(Click on image to view enlarged)
Subsequent is the HTML code used to create the above mentioned webpage:
1 <!DOCTYPE html></pre>
2 <html>
3 <head><title> Testing Select Class </title>
4 <body>
5 <div id="header">
150
6 <ul id="linkTabs">
7 <li>
8 <a href="https://www.google.com/">Google</a>
9 </li>
10 <li>
11 <a href="http://abodeqa.wordpress.com/">abodeQA</a>
12 </li>
13 </ul>
14 </div>
15 <div class="header_spacer"></div>
16 <div id="container">
17 <div id="content" style="padding-left: 185px;">
18 <table id="selectTable">
19 <tbody>
20 <tr>
21 <td>
22 <div>
23 <select id="SelectID_One">
24 <option value="redvalue">Red</option>
25 <option value="greenvalue">Green</option>
26 <option value="yellowvalue">Yellow</option>
27 <option value="greyvalue">Grey</option>
28 </select>
29 </div>
30 </td>
31 <td>
32 <div>
33 <select id="SelectID_Two">
34 <option value="applevalue">Apple</option>
35 <option value="orangevalue">Orange</option>
<option value="mangovalue">Mango</option
36
>
37 <option value="limevalue">Lime</option>
38 </select>
39 </div>
40 </td>
41 <td>
42 <div>
43 <select id="SelectID_Three">
44 <option value="selectValue">Select</option>
45 <option value="elephantvalue">Elephant</option>
46 <option value="mousevalue">Mouse</option>
47 <option value="dogvalue">Dog</option>
48 </select>
49 </div>
151
50 </td>
51 </tr>
52 <tr>
53 <td>
54
55 <!DOCTYPE html>
56 <html>
57 <body>
58 <p>Click the button to display a confirm box.</p>
59 <button onclick="myFunction()">Try it</button>
60
61 <script>
62 function myFunction()
63 {
64 confirm("Press a button!");
65 }
66 </script>
67 </body>
68 </html>
69 </td>
70 </tr>
71 </tbody>
72 </table>
73 </div>
74 </div>
75 </body>
76 </html>
Scenario to be automated
1. Launch the web browser and open the webpage
2. Click on the “Try it” button
3. Accept the alert
4. Click on the “Try it” button again
5. Reject the alert
WebDriver Code using Select Class
Please take a note that for script creation, we would be using “Learning_Selenium” project created in the former
tutorial.
Step 1: Create a new java class named as “DemoWebAlert” under the “Learning_Selenium” project.
Step 2: Copy and paste the below code in the “DemoWebAlert.java” class.
Below is the test script that is equivalent to the above mentioned scenario.
1 import org.junit.After;
152
2 import org.junit.Before;
3 import org.junit.Test;
4 import org.openqa.selenium.Alert;
5 import org.openqa.selenium.By;
6 import org.openqa.selenium.WebDriver;
7 import org.openqa.selenium.firefox.FirefoxDriver;
8
9 /**
10 * class description
11 */
12
public class DemoWebAlert
13
{
14 WebDriver driver;
15 /**
16 * Constructor
17 */
18 public DemoWebAlert() {
19 }
20
21 /**
22 * Set up browser settings and open the application
23 */
24
25 @Before
26 public void setUp() {
27 driver=newFirefoxDriver();
28 // Opened the application
29 driver.get("file:///F:/Work/Selenium/Testing-Presentation/DemoWebPopup.htm");
30 driver.manage().window().maximize();
31 }
32
33 /**
34 * Test to check Select functionality
35 * @throws InterruptedException
36 */
37
38 @Test
39 public void testWebAlert() throwsInterruptedException {
40 // clicking on try it button
41 driver.findElement(By.xpath("//button[contains(text(),'Try it')]")).click();
42 Thread.sleep(5000);
43
44 // accepting javascript alert
45 Alert alert = driver.switchTo().alert();
153
46 alert.accept();
47
48 // clicking on try it button
49 driver.findElement(By.xpath("//button[contains(text(),'Try it')]")).click();
50 Thread.sleep(5000);
51
52 // accepting javascript alert
53 driver.switchTo().alert().dismiss();
54
55 // clicking on try it button
56 driver.findElement(By.xpath("//button[contains(text(),'Try it')]")).click();
57 Thread.sleep(5000);
58
59 // accepting javascript alert
60 System.out.println(driver.switchTo().alert().getText());
61 driver.switchTo().alert().accept();
62 }
63
64 /**
65 * Tear down the setup after test completes
66 */
67
68 @After
69 public void tearDown() {
70 driver.quit();
71 }
72 }
Code Walk-through
Import Statements
Import org.openqa.selenium.Alert – Import this package prior to the script creation The package references to
the Alert class which is required to handle the web based alerts in WebDriver.
Object Creation for Alert class
Alert alert = driver.switchTo().alert();
We create a reference variable for Alert class and references it to the alert.
Switch to Alert
Driver.switchTo().alert();
The above command is used to switch the control to the recently generated pop up window.
Accept the Alert
alert.accept();
The above command accepts the alert thereby clicking on the Ok button.
154
Reject the Alert
alert.dismiss();
The above command closes the alert thereby clicking on the Cancel button and hence the operation should not
proceed.
Window Based Pop Ups
At times while automating, we get some scenarios, where we need to handle pop ups generated by windows like
a print pop up or a browsing window while uploading a file.
Handling these pop-ups have always been a little tricky as we know Selenium is an automation testing tool
which supports only web application testing, that means, it doesn’t support windows based applications and
window alert is one of them. However Selenium alone can’t help the situation but along with some third party
intervention, this problem can be overcome.
There are several third party tools available for handling window based pop-ups along with the selenium.
Before moving ahead, let us take a moment to have a look at the application under test (AUT).
155
Scenario to be automated
1. Launch the web browser and open the application – “gmail.com”
2. Enter valid username and password
3. Click on the sign in button
4. Click on the a compose button
5. Click on the attach icon
6. Select the files to be uploaded with the window based pop up.
WebDriver Code using Robot Class
Please take a note that for script creation, we would be using “Learning_Selenium” project created in the former
tutorial.
Step 1: Create a new java class named as “DemoWindowAlert” under the “Learning_Selenium” project.
Step 2: Copy and paste the below code in the “DemoWindowAlert.java” class.
Below is the test script that is equivalent to the above mentioned scenario.
1 import java.awt.Robot;</pre>
2 import java.awt.event.KeyEvent;
3 import org.junit.After;
4 import org.junit.Before;
5 import org.junit.Test;
6 import org.openqa.selenium.By;
7 import org.openqa.selenium.WebDriver;
8 import org.openqa.selenium.firefox.FirefoxDriver;
9
10 public class DemoWindowAlert {
11 WebDriver driver;
12 @Before
13
14 public void setUp()
15 {
16 driver=new FirefoxDriver();
17 driver.get("https://gmail.com");
18 driver.manage().window().maximize();
19 }
20
21 @Test
22 public void testWindowAlert() throws Exception{
23
24 // enter a valid email address
25 driver.findElement(By.id("Email")).sendKeys("TestSelenium1607@gmail.com");
26
27 // enter a valid password
156
28 driver.findElement(By.id("Passwd")).sendKeys("TestSelenium");
29
30 // click on sign in button
31 driver.findElement(By.id("signIn")).click();
32 Thread.sleep(30000);
33
34 // click on compose button
35 driver.findElement(By.xpath("//div[@class='z0']//div[contains(text(),'COMPOSE')]")).click();
36
37 // click on attach files icon
38 driver.findElement(By.xpath("//div[contains(@command,'Files')]//div[contains(@class,'aaA')]")).click();
39
40 // creating instance of Robot class (A java based utility)
41 Robot rb =new Robot();
42
43 // pressing keys with the help of keyPress and keyRelease events
44 rb.keyPress(KeyEvent.VK_D);
45 rb.keyRelease(KeyEvent.VK_D);
46 Thread.sleep(2000);
47
48 rb.keyPress(KeyEvent.VK_SHIFT);
49 rb.keyPress(KeyEvent.VK_SEMICOLON);
50 rb.keyRelease(KeyEvent.VK_SEMICOLON);
51 rb.keyRelease(KeyEvent.VK_SHIFT);
52
53 rb.keyPress(KeyEvent.VK_BACK_SLASH);
54 rb.keyRelease(KeyEvent.VK_BACK_SLASH);
55 Thread.sleep(2000);
56
57 rb.keyPress(KeyEvent.VK_P);
58 rb.keyRelease(KeyEvent.VK_P);
59
60 rb.keyPress(KeyEvent.VK_I);
61 rb.keyRelease(KeyEvent.VK_I);
62
63 rb.keyPress(KeyEvent.VK_C);
64 rb.keyRelease(KeyEvent.VK_C);
65 Thread.sleep(2000);
66
67 rb.keyPress(KeyEvent.VK_ENTER);
68 rb.keyRelease(KeyEvent.VK_ENTER);
69 Thread.sleep(2000);
70 }
71
72 @After
157
73 public void tearDown()
74 {
75 driver.quit();
76 }
77 }
Code Walk-through
Import Statements
import java.awt.Robot – Import this package prior to the script creation The package references to the Robot
class in java which is required simulate keyboard and mouse events.
import java.awt.event.KeyEvent – The package allows the user to use keyPress and keyRelease events of
keyboard.
Object Creation for Robot class
Robot rb =new Robot();
We create a reference variable for Robot class and instantiate it.
KeyPress and KeyRelease Events
rb.keyPress(KeyEvent.VK_D);
rb.keyRelease(KeyEvent.VK_D);
The keyPress and keyRelease methods simulate the user pressing and releasing a certain key on the keyboard
respectively.
Conclusion
In this tutorial, we tried to make you acquainted with the WebDriver’s Alert class that is used to handle web
based pop ups. We also briefed you about the Robot class that can be used to populate the value in the window
based alert with the help of keyPress and keyRelease events.
Article summary:
Alerts are a small box that appears on the display screen to give you some kind of information or to
warn you about a potentially damaging operation or it may even ask you for the permissions for the
operation.
There are popularly two types of alerts–
Windows based alert pop ups
Web based alert pop ups
Prior to the actual scripting, we need to import a package to be able to create a WebDriver script for
handling a dropdown and making the Select class accessible.
WebDriver offers the users with a very efficient way to handle these pop ups using Alert interface.
void dismiss() – The dismiss() method clicks on the “Cancel” button as soon as the pop up window
appears.
void accept() – The accept() method clicks on the “Ok” button as soon as the pop up window appears.
158
String getText() – The getText() method returns the text displayed on the alert box.
void sendKeys(String stringToSend) – The sendKeys() method enters the specified string pattern into the
alert box.
Handling window based pop-ups have always been a little tricky as we know Selenium is an
automation testing tool which supports only web application testing, that means, it doesn’t support
windows based applications and window alert is one of them.
Robot class is a java based utility which emulates the keyboard and mouse actions and can be
effectively used to handling window based pop up with the help of keyboard events.
The keyPress and keyRelease methods simulate the user pressing and releasing a certain key on the
keyboard respectively.
Next Tutorial #17: In the upcoming tutorial, we would discuss about the various other commonly used
WebDriver commands. We would shed light on topics like exception handling and iframe handling. We would
also discuss about the get commands provided in WebDriver.
We would explain these topics with quick examples in order to make them understandable for the readers to
exercise these concepts in their day to day scripting.
Note for the Readers: Till then, stay tuned and automate the web pages having web based and window based
pop ups using WebDriver utility – “Alert class” and Java utility – “Robot Class”.
Feel free to post your queries/comments about this or any other previous tutorials in comments below.
159
Tutorial #17 – Commonly used commands
In the last tutorial, we discussed about the different types of alertsencountered while testing web based
applications and their effective ways of handling. We discussed both the types of alerts i.e. “Web-based alerts”
and “Window-based alerts” at length. We also made you acquainted with yet another Java based utility named
as “Robot Class” to handle windows-based pop up.
Advancing ahead in this Selenium WebDriver tutorial series, we would be pressing on various commonly and
routinely used Selenium WebDriver commands. We will precisely and briefly discuss each of these
Selenium commands so as to make you capable of using these commands effectively whenever the situation
arises. Selenium WebDriver Commands:
Just to have a rough idea, we would be discussing the following Selenium WebDriver commands and their
different versions:
1. get() methods
2. Locating links by linkText() and partialLinkText()
3. Selecting multiple items in a drop dropdown
4. Submitting a form
5. Handling iframes
6. close() and quit() methods
7. Exception Handling
#1) get() Methods
WebDriver
Usage
command
driver.get("https://google.com");
160
WebDriver
Usage
command
driver.getClass();
driver.getCurrentUrl();
boolean result =
driver.getPageSource().contains("String to
find");
String Text =
driver.findElement(By.id("Text")).getText();
161
WebDriver
Usage
command
driver.findElement(By.id("findID")).
getAttribute("value");
162
15 for (String winHandle : d.getWindowHandles())
16 {
17 dvr.switchTo().window(winHandle);
18
19 // Close the delete window as it is not needed
20 if (close && dvr.getTitle().equals("Demo Delete Window"))
21 {
22 dvr.findElement(By.name("ok")).click();
23 }
24 }
25 return true;
26 }
27 return false;
28 }
29 };
#2) Locating links by linkText() and partialLinkText()
Let us access “google.com” and “abodeqa.com” using linkText() and partialLinText() methods of WebDriver.
The above mentioned links can be accessed by using the following commands:
driver.findElement(By.linkText(“Google”)).click();
driver.findElement(By.linkText(“abodeQA”)).click();
The command finds the element using link text and then click on that element and thus the user would be re-
directed to the corresponding page.
The above mentioned links can also be accessed by using the following commands:
driver.findElement(By.partialLinkText(“Goo”)).click();
driver.findElement(By.partialLinkText(“abode”)).click();
The above two commands find the elements based on the substring of the link provided in the parenthesis and
thus partialLinkText() finds the web element with the specified substring and then clicks on it.
163
1. Single select dropdown: A dropdown that allows only single value to be selected at a time.
2. Multi select dropdown: A dropdown that allows multiple values to be selected at a time.
Consider the HTML code below for a dropdown that can select multiple values at the same time.
1 <select id="SelectID_One" multiple="">
<option value="redvalue">Red</option
2
>
3 <option value="greenvalue">Green</option>
4 <option value="yellowvalue">Yellow</option>
5 <option value="greyvalue">Grey</option>
6 </select>
The code snippet below illustrates the multiple selections in a drop down.
1 // select the multiple values from a dropdown
2 Select selectByValue = newSelect(driver.findElement(By.id("SelectID_One")));
3 selectByValue.selectByValue("greenvalue");
4 selectByValue.selectByVisibleText("Red");
5 selectByValue.selectByIndex(2);
#4) Submitting a form
Most or almost all the websites have forms that need to be filled and submitted while testing a web application.
User may come across several types of forms like Login form, Registration form, File Upload form, Profile
Creation form etc.
164
In WebDriver, user is leveraged with a method that is specifically created to submit a form. The user can also
use click method to click on the submit button as a substitute to submit button.
Check out the code snippet below against the above “new user” form:
1 // enter a valid username
2 driver.findElement(By.<em>id</em>("username")).sendKeys("name");
3
4 // enter a valid email address
5 driver.findElement(By.<em>id</em>("email")).sendKeys("name@abc.com");
6
7 // enter a valid password
8 driver.findElement(By.<em>id</em>("password")).sendKeys("namepass");
9
10 // re-enter the password
11 driver.findElement(By.<em>id</em>("passwordConf")).sendKeys("namepass");
12
13 // submit the form
14 driver.findElement(By.<em>id</em>("submit")).submit();
Thus, as soon as the program control finds the submit method, it locates the element and triggers
the submit() method on the found web element.
An inline frame acronym as iframe is used to insert another document with in the current HTML document or
simply a web page into another web page by enabling nesting.
165
Consider the following HTML code having iframe within the webpage:
1 <html>
2 <head><title>Software Testing Help - iframe session</title>
</head
3
>
<body
4
>
5 <div>
6 <iframe id="ParentFrame">
7 <iframe id="ChildFrame">
8 <input type="text" id="Username">UserID</input>
9 <input type="text" id="Password">Password</input>
10 </iframe>
11 <button id="LogIn">Log In</button>
12 </iframe>
13 </div>
14 </body>
15 </html>
The above HTML code illustrates the presence of an embedded iframe into another iframe. Thus, to be able to
access the child iframe, user is required to navigate to the parent iframe first. After performing the required
operation, user may be required to navigate back to the parent iframe to deal with the other element of the
webpage.
It is impossible if a user tries to access the child iframe directly without traversing to the parent iframe first.
Select iframe by id
driver.switchTo().frame(“ID of the frame“);
Locating iframe using tagName
While locating an iframe, user might face some trouble if the iframe is not attributed with standard properties. It
becomes a complex process to locate the frame and switch to it. To buckle down the situation, user is leveraged
to locate an iframe using tagName method similar to the way we find any other web element in WebDriver.
driver.switchTo().frame(driver.findElements(By.tagName(“iframe”).get(0));
The above command locates the first web element with the specified tagName and switches over to that iframe.
“get(0) is used to locate the iframe with the index value.” Thus, in lines with our HTML code, the above code
syntax would lead the program control to switch to “ParentFrame”.
166
b) frame(Name of Frame)
driver.switchTo().frame(“name of the frame”);
c) frame(WebElement element)
Select Parent Window
driver.switchTo().defaultContent();
The above command brings the user back to the original window i.e. out of both the iframes.
a) close(): WebDriver’s close() method closes the web browser window that the user is currently working on or
we can also say the window that is being currently accessed by the WebDriver. The command neither requires
any parameter nor does it return any value.
b) quit(): Unlike close() method, quit() method closes down all the windows that the program has opened.
Same as close() method, the command neither requires any parameter nor does it return any value.
Refer the below code snippets:
driver.close(); // closes only a single window that is being accessed by the WebDriver instance currently
driver.quit(); // closes all the windows that were opened by the WebDriver instance
#7) Exception Handling
Exceptions are the conditions or situations that halt the program execution unexpectedly.
With respect to Java code that we implement while automating a web application can be enclosed within a
block that that is capable of providing a handling mechanism against the erroneous conditions.
Catching an exception
To catch an exception, we use the below block of code
1 try{
2 // Protected block
3 // implement java code for automation
4}
5 catch (ExceptionName e)
6{
167
7 // catch block - Catches the exceptions generated in try block without halting the program execution
8}
If any exception occurs in the try block/protected block, then the execution controls checks for a catch block for
the matching exception type and passes the exception to it without breaking the program execution.
In the above code, exception is likely to be caught in the first catch block if the exception type matches. If the
exception type does not match, then the exception is traversed to the second catch block and third catch block
and so on until the all catch blocks are visited.
Next Tutorial #18: In the upcoming tutorial, we would discuss about Web tables, frames and dynamic
elements which are essential part of any web project. We will also cover the exception handling important
topic in more details in one of the upcoming Selenium Tutorials.
Note for the Readers: Till then, stay tuned and automate the web pages and use the above documented
commands.
169
Tutorial #18 – Handling Web Tables, Frames, Dynamic Elements
In last Selenium WebDriver tutorial we learned various commonly and routinely used Selenium WebDriver
commandsincluding important topics like handling iframe and exceptions in Selenium scripts.
Moving ahead in our comprehensive series of tutorials on Selenium, in this tutorial we would discuss
about handling Web tables, iframe and dynamic elements which are essential part of any web project.
This tutorial consists of 3 different topics and their handling mechanisms in selenium script.
1. Web Tables/HTML tables
2. Frames
3. Dynamic elements
#1) Web Tables/HTML Tables
In this module we will learn about the web tables or html tables in a web page, tags available in html and how to
handle web tables dynamically.
Web tables are basically group of elements that are logically stored in a row and column format. It is used to
organize similar information in a web page.
Approach #1:
Below is the xpath of one of the cell in html table. Let’s say “firstname”
//div[@id=’main’]/table[1]/tbody/tr[1]/th[1]
tr[1] defines first row and th[1] defines first column.
If number of rows and columns are always constant, let’s say our html table will always have 5 rows and 3
columns.
Except row and column number, each component of xpath remains the same. So you can iterate using “for
loop” for each row and column as mentioned above.
Approach #2:
First approach is best suitable for the table which doesn’t change its dimensions and always remains the same.
Above approach will not be a perfect solution for dynamically changing web tables.
Step 1: First get the entire html table and store this in a variable ‘htmltable’ of type web element.
Step 2: Get all the rows with tag name ‘tr’ and store all the elements in a list of web elements. Now all the
elements with tag ‘tr’ are stored in ‘rows’ list.
Step 3: Loop through each row and get the list of elements with tag ‘th’. ‘rows.get(0)’ will give first row
and ‘findElements(By.tagName(“th”))’ will give list of columns for the row.
Step 4: Iterate using ‘columns.getsize()’ and get the details of each cell.
Note: Above approach will be best suitable if the table dimensions changes dynamically.
This concludes the topic how to handle web tables in selenium. Next we will learn about handling an element
inside frame.
#2) Frames:
In this section we will learn about the frames in a web page and how to identify the frames. Also we will find
out how we can handle a frame in selenium WebDriver.
Many developers like to place elements inside frame. Frame is just like a container where few elements can be
grouped.
Identification of a frame:
Different ways to know if the element is present inside a frame or not
#1. Right click on the element. Check if “This Frame” option is available. If This frame option is available, it
means that the element is inside a frame.
#2. View page source of the web page and check if any tag is available for ‘iframe’.
172
Verify Number of frames in a webpage:
All the frames are having tag name as “iframe”.
List<WebElement> frameList=driver.findElements(By.tagName(“iframe”));
System.out.println(frameList.size());
In above example: frameList will have all the list of frames and frameList.size() will give the number of
frames.
Handling an element inside frame:
If an element is inside a frame then control has to switch to frame first and then start operating on the elements.
173
driver.findElement(//*[@id=’username’]).sendKeys(“username”);
driver.findElement(//*[@id=’pass’]).sendKeys(“password”);
Here, we have learned how to handle an element inside frame and next we will cover about the different ways
to handle dynamic element.
In few scenarios, element attributes change dynamically. It can be ‘id’, ’name’ etc.
Example: let’s say ‘id’ of a username field is ‘username_123’ and the xpath will be
//*[@id=’username_123′] but when you open the page again the ‘id’ of ‘username’ field might have changed
and the new value may be ‘username_234’.
In this case the test will fail because the selenium could not find the xpath you have passed earlier as the id of
the field has changed to some other value.
For example: if id of ‘login’ field changes dynamically and there is no constant value to use contains method.
Solution: Use of sendKeys.
Selenium provides different api to use function keys. For example tab key, enter keys, F5 etc.
Step 1: Enter password
driver.findElement(By.id(“password”)).sendKeys(“password”));
174
Step 2: Use key functions to navigate to element.
driver.findElement(By.id(“password”)).sendKeys(Keys.ENTER));
or
driver.findElement(By.id(“password”)).sendKeys(Keys.TAB));
Conclusion:
Web tables, frames and dynamic elements are essential part of any web project. It is always desirable to write
effective code to handle web tables and dynamic elements.
Understanding the construction of generic xpath which is very helpful while handling dynamic elements. In
case of a frame, your script has to switch the frame and then operate on the element.
Next tutorial #19: In next Selenium tutorial we will learn about types of exceptions and how to handle
exceptions in java in Selenium scripts.
Please post your queries related to Web tables, frames and handling dynamic element if you have any.
175
Tutorial #19 – Exception Handling
In last WebDriver tutorial we learned about 3 different types of important web elements like Web Tables,
Frames and Dynamic elementsand their handling mechanisms in selenium script
Before moving ahead with Framework tutorials in this Selenium training series, here in this tutorial we will
learn about types of exceptions and how to handle exceptions in java and Selenium scripts.
Developers/testers use exception handling framework to handle exception in selenium scripts.
Example: When selenium script fails due to wrong locator, then developer should be able to understand the
reason for failure and this can be achieved easily if the exception is handled properly in the program.
Below we have described the types of exceptions and the different ways how we can use exception handling
framework in selenium scripts.
Exceptions are events due to which java program ends abruptly without giving expected output. Java provides a
framework where user can handle exceptions.
176
#1) Checked Exception: Checked exception is handled during compile time and it gives compilation error if it
is not caught and handled during compile time.
Example: FileNotFoundException, IOException etc.
#2) Unchecked Exception: In case of unchecked exception, compiler does not mandate to handle. Compiler
ignores during compile time.
Example: ArrayIndexoutOfBoundException
#3) Error: When a scenario is fatal and program cannot recover then JVM throws an error. Errors cannot be
handled by try catch block. Even if user tries to handle error by using Try catch block, it cannot recover from
error.
Example: Assertion error, OutOfMemoryError etc.
Exception handling:
Try and Catch block:
try-catch blocks are generally used to handle exceptions. Type of exceptions is declared in catch block which is
expected to come. When an exception comes in try block, immediately control moves to catch block.
Example:
1 try {
2 br = new BufferedReader(new FileReader("Data"));
3 } catch(IOException ie)
4 {
5 ie.printStackTrace();
6 }
There can be multiple catch blocks for one try block depending upon type of exception.
Example:
1 try {
2 br = new BufferedReader(new FileReader("Data"));
3 } catch(IOException ie)
4 {
5 ie.printStackTrace();
6 } catch(FileNotFoundException file){
7 file.printStackTrace();
8 }
throws Exception:
throws keyword in java is used to throw an exception rather than handling it. All checked exceptions can be
thrown by methods.
Example:
1 public static void main(String[] args) throws IOException
2{
3 BufferedReader br=new BufferedReader(newFileReader("Data"));
177
4 while ((line = br.readLine()) != null)
5 {
6 System.out.println(line);
7 }
8}
finally block:
finally block executes irrespective of execution of try catch block and it executes immediately after try/catch
block completes.
Basically file close, database connection etc. can be closed in finally block.
Example:
1 try {
2 br = new BufferedReader(new FileReader("Data"));
3 } catch(IOException ie)
4 {
5 ie.printStackTrace();
6 }
7 Finally {
8 br.close();
9 }
In the above example, BufferReader stream is closed in finally block. br.close() will always execute irrespective
of execution of try and catch block.
Note: finally block can exist without any catch block. It is not necessary to have a catch block always.
There can be many catch blocks but only one finally block can be used.
Throwable: Throwable is parent class for error and exception. Generally it is difficult to handle errors in java. If
programmer is not sure about the type of error and exception, then it is advised to use Throwable class which
can catch both error and exception.
Example:
1 try {
2 br = new BufferedReader(new FileReader("Data"));
3 } catch (Throwable t)
4 {
5 t.printStackTrace();
6 }
Exceptions in Selenium WebDriver:
Selenium has its own set of exceptions. While developing selenium scripts, programmer has to handle or throw
those exceptions. Below are few examples of exceptions in selenium.
Examples:
ElementNotVisibleException: If selenium tries to find an element but element is not visible within page
178
NoAlertPresentException: If user tries to handle an alert box but alert is not present.
NoSuchAttributeException: While trying to get attribute value but attribute is not available in DOM.
NoSuchElementException: This exception is due to accessing an element which is not available in the page.
WebDriverException: Exception comes when code is unable to initialize WebDriver.
Conclusion:
Exception handling is the essential part of every java program as well as selenium script. We can build robust
and optimal code by handling exception in smart ways. And it is also a best practice to handle exceptions in
script which will give you a better report when program fails due to any reason.
Here we have tried to cover the process and framework of exception handling which is required to be
implemented in selenium scripts.
Remember it is not mandatory to always handle exception in try-catch block. You can also throw an exception
depending upon the requirement in script.
Next Tutorial #20: In the upcoming tutorial, we would discuss about the various types of testing frameworks
available. We would also study about the pros and cons of using a fledged framework approach in automation
testing. We would discuss in detail about Test data driven framework.
Please post your queries, related to handling exception in Selenium WebDriver, if you have any
179
Selenium Framework
• Tutorial #20 – Most popular Test Automation frameworks(Must Read)
• Tutorial #21 – Selenium Framework Creation & Accessing Test Data from Excel (Must Read)
• Tutorial #22 – Creating Generics and Testsuite
• Tutorial #23 – Using Apache ANT
• Tutorial #24 – Setting up Selenium Maven Project
• Tutorial #25 – Using Hudson Continuous integration tool
180
Tutorial #20 – Most popular Test Automation frameworks(Must Read)
Most Popular Test Automation Frameworks with Pros and Cons of Each –
Selenium Tutorial #20
In the last few Selenium tutorials, we discussed about various commonly and popularly used commands in
WebDriver, handling web elements like Web Tables, Framesand handling exceptions in Selenium scripts.
We discussed each of these commands with sample code snippets and examples so as to make you capable of
using these commands effectively whenever you are encountered with similar situations. Amongst the
commands we discussed in the previous tutorial, few of them owe utmost importance.
As we move ahead in the Selenium series, we would concentrate our focus towards Automation Framework
creation in the next few upcoming tutorials. We would also shed light on various aspects of an Automation
framework, types of Automation frameworks, benefits of using a framework and the basic components that
constitutes an Automation framework.
What is Framework?
A framework is considered to be a combination of set protocols, rules, standards and guidelines that can be
incorporated or followed as a whole so as to leverage the benefits of the scaffolding provided by the
Framework.
Keep a check on the maximum capacity of the elevator and do not get onto an elevator if the maximum
capacity has reached.
Press the alarm button in case of any emergency or trouble.
Allow the passenger to get off the elevator if any before entering the elevator and stand clear off the
doors.
In case of fire in the building or if there is any haphazard situation, avoid the use of elevator.
Do not play or jump inside the elevator.
Do not smoke inside the elevator.
Call for the help/assistance if door doesn’t open or if the elevator doesn’t work at all. Do not try to open
the doors forcefully.
181
There can be many more rules or sets of guidelines. Thus, these guidelines if followed, makes the system more
beneficial, accessible, scalable and less troubled for the users.
Now, as we are talking about “Test Automation Frameworks”, let us move our focus towards them.
Test Automation Framework
A “Test Automation Framework” is scaffolding that is laid to provide an execution environment for the
automation test scripts. The framework provides the user with various benefits that helps them to develop,
execute and report the automation test scripts efficiently. It is more like a system that has created specifically to
automate our tests.
In a very simple language, we can say that a framework is a constructive blend of various guidelines, coding
standards, concepts, processes, practices, project hierarchies, modularity, reporting mechanism, test data
injections etc. to pillar automation testing. Thus, user can follow these guidelines while automating application
to take advantages of various productive results.
The advantages can be in different forms like ease of scripting, scalability, modularity, understandability,
process definition, re-usability, cost, maintenance etc. Thus, to be able to grab these benefits, developers are
advised to use one or more of the Test Automation Framework.
Moreover, the need of a single and standard Test Automation Framework arises when you have a bunch of
developers working on the different modules of the same application and when we want to avoid situations
where each of the developer implements his/her approach towards automation.
Note: Take a note that a testing framework is always application independent that is it can be used with any
application irrespective of the complications (like Technology stack, architecture etc.) of application under
test. The framework should be scalable and maintainable.
Advantage of Test Automation framework
1. Reusability of code
2. Maximum coverage
3. Recovery scenario
4. Low cost maintenance
5. Minimal manual intervention
6. Easy Reporting
Types of Test Automation Framework
Now that we have a basic idea of what is an Automation Framework, in this section we would harbinger you
with the various types of Test Automation Frameworks those are available in the market place. We would also
try shed lights over their pros and cons and usability recommendations.
182
There is a divergent range of Automation Frameworks available now days. These frameworks may differ from
each other based on their support to different key factors to do automation like reusability, ease of maintenance
etc.
Let us discuss the few most popularly used Test Automation Frameworks:
1. Module Based Testing Framework
2. Library Architecture Testing Framework
3. Data Driven Testing Framework
4. Keyword Driven Testing Framework
5. Hybrid Testing Framework
6. Behavior Driven Development Framework
(click on image to view enlarged)
These modules are separated by an abstraction layer in such a way that the changes made in the sections of the
application doesn’t yields affects on this module.
183
Pros:
1. The framework introduces high level of modularization which leads to easier and cost efficient
maintenance.
2. The framework is pretty much scalable
3. If the changes are implemented in one part of the application, only the test script representing that part
of the application needs to be fixed leaving all the other parts untouched.
Cons:
1. While implementing test scripts for each module separately, we embed the test data (Data with which
we are supposed to perform testing) into the test scripts. Thus, whenever we are supposed to test with a
different set of test data, it requires the manipulations to be made in the test scripts.
#2) Library Architecture Testing Framework
The Library Architecture Testing Framework is fundamentally and foundationally built on Module Based
Testing Framework with some additional advantages. Instead of dividing the application under test into test
scripts, we segregate the application into functions or rather common functions can be used by the other parts of
the application as well. Thus we create a common library constituting of common functions for the application
under test. Therefore, these libraries can be called within the test scripts whenever required.
The basic fundamental behind the framework is to determine the common steps and group them into functions
under a library and call those functions in the test scripts whenever required.
184
Example: The login steps can be combined into a function and kept into a library. Thus all the test scripts those
require to login the application can call that function instead of writing the code all over again.
Pros:
1. Like Module Based Framework, this framework also introduces high level of modularization which
leads to easier and cost efficient maintenance and scalability too.
2. As we create common functions that can be efficiently used by the various test scripts across the
Framework. Thus, the framework introduces a great degree of re-usability.
Cons:
1. Like Module Based Framework, the test data is lodged into the test scripts, thus any change in the test
data would require changes in the test script as well.
2. With the introduction of libraries, the framework becomes a little complicated.
#3) Data Driven Testing Framework
While automating or testing any application, at times it may be required to test the same functionality multiple
times with the different set of input data. Thus, in such cases, we can’t let the test data embedded in the test
script. Hence it is advised to retain test data into some external data base outside the test scripts.
Data Driven Testing Framework helps the user segregate the test script logic and the test data from each other.
It lets the user store the test data into an external database. The external databases can be property files, xml
files, excel files, text files, CSV files, ODBC repositories etc. The data is conventionally stored in “Key-Value”
pairs. Thus, the key can be used to access and populate the data within the test scripts.
Note: The test data stored in an external file can belong to the matrix of expected value as well as matrix of
input values.
185
Example:
Let us understand the above mechanism with the help of an example.
Step 1: First and the foremost step are to create an external file that stores the test data (Input data and Expected
Data). Let us consider an excel sheet for instance.
Step 2: The next step is to populate the test data into Automation test Script. For this purpose several API’s can
be used to read the test data.
1 public void readTD(String TestData, String testcase) throws Exception {
2 TestData=readConfigData(configFileName,"TestData",driver);
3 testcase=readConfigData(configFileName,"testcase",driver);
4 FileInputStream td_filepath = new FileInputStream(TestData);
5 Workbook td_work =Workbook.getWorkbook(td_filepath);
6 Sheet td_sheet = td_work.getSheet(0);
7 if(counter==0)
8 {
9 for (int i = 1,j = 1; i <= td_sheet.getRows()-1; i++){
10 if(td_sheet.getCell(0,i).getContents().equalsIgnoreCase(testcase)){
11 startrow = i;
12 arrayList.add(td_sheet.getCell(j,i).getContents());
13 testdata_value.add(td_sheet.getCell(j+1,i).getContents());}}
14 for (int j = 0, k = startrow +1; k <= td_sheet.getRows()-1; k++){
15 if(td_sheet.getCell(j,k).getContents()==""){
16 arrayList.add(td_sheet.getCell(j+1,k).getContents());
17 testdata_value.add(td_sheet.getCell(j+2,k).getContents());}}
18 }
19 counter++;
20 }
The above method helps to read the test data and the below test step helps the user to type in the test data on the
GUI.
element.sendKeys(obj_value.get(obj_index));
186
Pros:
1. The most important feature of this framework is that it considerably reduces the total number of scripts
required to cover all the possible combinations of test scenarios. Thus lesser amount of code is required
to test a complete set of scenarios.
2. Any change in the test data matrix would not hamper the test script code.
3. Increases flexibility and maintainability
4. A single test scenario can be executed altering the test data values.
Cons:
1. The process is complex and requires an extra effort to come up with the test data sources and reading
mechanisms.
2. Requires proficiency in a programming language that is being used to develop test scripts.
#4) Keyword Driven Testing Framework
The Keyword driven testing framework is an extension to Data driven Testing Framework in a sense that it not
only segregates the test data from the scripts, it also keeps the certain set of code belonging to the test script into
an external data file.
These set of code are known as Keywords and hence the framework is so named. Key words are self-guiding as
to what actions needs to be performed on the application.
The keywords and the test data are stored in a tabular like structure and thus it is also popularly regarded as
Table driven Framework. Take a notice that keywords and test data are entities independent of the automation
tool being used.
In the above example keywords like login, clickLink and verifyLink are defined within the code.
Depending upon the nature of application keywords can be derived. And all the keywords can be reused
187
multiple times in a single test case. Locator column contains the locator value that is used to identify the web
elements on the screen or the test data that needs to be supplied.
All the required keywords are designed and placed in base code of the framework.
Pros:
1. In addition to advantages provided by Data Driven testing, Keyword driven framework doesn’t require
the user to possess scripting knowledge unlike Data Driven Testing.
2. A single keyword can be used across multiple test scripts.
Cons:
1. The user should be well versed with the Keyword creation mechanism to be able to efficiently leverage
the benefits provided by the framework.
2. The framework becomes complicated gradually as it grows and a number of new keywords are
introduced.
#5) Hybrid Testing Framework
As the name suggests, the Hybrid Testing Framework is a combination of more than one above mentioned
frameworks. The best thing about such a setup is that it leverages the benefits of all kinds of associated
frameworks.
In the above example, keyword column contains all the required keywords used in the particular test case and
data column drives all the data required in the test scenario. If any step does not need any input then it can be
left empty.
188
#6) Behavior Driven Development Framework
Behavior Driven Development framework allows automation of functional validations in easily readable and
understandable format to Business Analysts, Developers, Testers, etc. Such frameworks do not necessarily
require the user to be acquainted with programming language. There are different tools available for BDD like
cucumber, Jbehave etc. Details of BDD framework are discussed later in Cucumber tutorial. We have also
discussed details on Gherkin language to write test cases in
Cucumber.
Components of Automation Testing Framework
(click on image to view enlarged)
Though the above pictorial representation of a framework is self-explanatory but we would still highlight a few
points.
1. Object Repository: Object Repository acronym as OR is constituted of the set of locators types
associated with web elements.
2. Test Data: The input data with which the scenario would be tested and it can be the expected values
with which the actual results would be compared.
3. Configuration File/Constants/ Environment Settings: The file stores the information regarding the
application URL, browser specific information etc. It is generally the information that remains static
throughout the framework.
189
4. Generics/ Program logics/ Readers: These are the classes that store the functions which can be
commonly used across the entire framework.
5. Build tools and Continuous Integration: These are the tools that aids to the frameworks capabilities to
generate test reports, email notifications and logging information.
Conclusion
The frameworks illustrated above are the most popular frameworks used by the testing fraternity. There are
various other frameworks also in the place. For all the further tutorials we would base on the Data Driven
Testing Framework.
In this tutorial, we discussed about the basics of an Automation Framework. We also discussed about the types
of frameworks available in the market.
Next Tutorial #21: In the next tutorial, we would briefly introduce you with the sample framework, the MS
Excel which would store the test data, excel manipulations etc.
Till then feel free to ask your queries about automation frameworks.
190
Tutorial #21 – Selenium Framework Creation & Accessing Test Data from Excel (Must Read)
In the last tutorial, we familiarized you with the basics of test automation Frameworks, its components and
types. The frameworks illustrated in the previous tutorial were a few amongst the most popular frameworks
used by the testing fraternity.
We briefly discussed about Module based Frameworks, Library Architecture based framework, Keyword driven
framework, Data driven Framework and Hybrid Framework. There are various other frameworks also in the
place.
Please take a note that we would be adopting Data Driven Test Automation Framework for the rest of our
tutorials.
In the current tutorial in this series, we would make you acquainted with a sample framework, the Excels
which would store the test data and their Excel manipulations. On the same lines, we would move forward
and introduce new strategies and resources to mature our framework.
So let’s learn:
Framework creation strategy using a sample project
Access the test data stored in the external data source
Moving ahead, we would start with the description of the project hierarchy that we would be creating in order to
segregate the various project components.
Refer the below image for the project hierarchy created for the sample project. The below java project can be
easily created within the eclipse the way we have created the projects in the earlier tutorials.
191
Selenium Project Folder Structure – Walkthrough
#1) src – The folder contains all the test scripts, generics, readers and utilities. All these resources are nothing
but the simple java classes. Under the source (src) folder, we have created a hierarchy of folders.
a) test – The “test” folder is constituted of majorly two ingredients – testsuite and the folders representing the
various modules of the application under test. Thus, each of these folders contains the test scripts specific to the
module to which it is associated. Testsuite is a logical combination of more than one test scripts. Thus, the user
can mark an entry of any of the test script within the testsuite that he/she desires to execute in the subsequent
runs.
b) utilities – The “utilities” folder is constituted of various generics, constants, Readers and classes for
implementing user defined exceptions. Each of the folders under utilities has got its own significance.
Excel Reader – A generic and common class has been created to read the test data (input parameters
and expected results) from the Excel sheets
192
EnvironmentConstants – The folder are integration of the java classes that stores the static variables
referencing to the paths and other environmental details. These details can be Application URL, URL to
the Databases, Credentials for Databases, and URL to any third party tool being used. The disparate
application URLs can be set for different environments (dev, prod, test, master, slave etc).
DataSetters – The folder incorporates the classes that implement the getters and setters of the test data
fetched from the Excels. To lode multiple sets of Test data, we create ArrayLists.
UserRoles – The folder accommodates the classes that take care of the Role based access criteria if any
for instinct users.
FunctionLibrary – The folder is constituted of the classes which contain functions and methods that
can be shared and used amongst the multiple classes. Very often, we are suppose to perform certain
procedures prior and aftermath to the actual test execution like login to the application, setting up
environments, activities related to rolls, data manipulations, writing results, methods those generate
pre/post-conditions to other methods. Since we tend to perform these activities for all or most of the test
script. Thus it is always recommended to create a separate class for such activities instead of coding
them repeatedly in each of the test script.
PreConditionalMethods
PostConditionalMethods
Very often, we are suppose to perform certain procedures prior and aftermath to the actual test execution like
login to the application, setting up environments, activities related to user rolls, data manipulations, writing
results, methods those generate pre/post-conditions to other methods. Since we tend to perform these activities
for all or most of the test script, thus it is always recommended to create a separate class for such activities
instead of coding them repeatedly in each of the test script.
CommonMethods
Like Pre and post conditions, there may be methods and functions those can be used by more than one test
script. Thus, these methods are grouped together in a class. The testscript can access these methods using the
object of the common class.
#2) excelFiles – The excel files are considered to be the data source/data providers for test script execution.
These files store the test data into key value pairs. Make a note that we create a separate excel sheet for each of
the test script i.e. each test script has its own test data file. The name of the test script and the corresponding test
data files/ excel sheet has been kept same for the traceability perspective. Check out the sample test data format
below:
Test Data Format
193
Each of the columns represents a key and each of the rows represents a test data/value. Specify the multiple
rows in order to execute the same test script with multiple data sets.
Mark that the test data formats are solely user defined. Thus based on your requirements, you can customize the
test data files.
#3) library – The folder acts as a repository/artifactory for all the required jar files, libraries, drivers etc to
successfully build the test environment and to execute the test scripts. Refer the following figure to check out
the libraries we would be employing within our project.
#4) logs – The folder contains a .txt file that stores the logging information upon each execution.
#5) testMaterial – The folder contains the actual test data that needs to be uploaded if any. This folder would
come into picture when we come across test scenarios where the user is required to upload files, documents,
pictures, reports etc.
#6) build.xml – The xml file is used by the “Ant Server” to automate the entire build process.
#7) log4j.xml – This xml file is used by a Java based utility named as “Log4j” to generate the execution logs.
Note: We would study more about the logs, user defined exceptions and Ant in detail in the upcoming tutorials.
So don’t panic if you get confused between the notions.
Now, as we move forward let us understand the phenomenon where we access the excel files and populate
the test data into our test scripts.
In order to comprehend the process easily, we would break down the process into the following steps.
194
Step 2: The next step is to download a standard java based API/Library named as “Java excel Library” (jxl) to
be able to access the already created generic methods for Excel Manipulation.
Step 3: Create a generic excel reader class named as “ExcelReader.java”. Copy the below code in the
ExcelReader.java.
1 package Utilities;
2 import java.io.File;
3 import java.io.IOException;
4 import java.util.Hashtable;
5 import jxl.Sheet;
6 import jxl.Workbook;
7 import jxl.read.biff.BiffException;
8
9 /**
10 * This is a utility class created to read the excel test data file before performing the test steps.
11 * This class loads the excel file and
12 * reads its column entries.
13 *
14 */
15
16 public class ExcelReader {
17 /**
18 * The worksheet to read in Excel file
19 */
20
21 public static Sheet wrksheet;
22 /**
23 * The Excel file to read
24 */
25
26 public static Workbook wrkbook = null;
27 /**
195
28 * Store the column data
29 */
30
31 public static Hashtable<String, Integer> dict = new Hashtable<String, Integer>();
32 /**
33 * Create a Constructor
34 *
35 * @param ExcelSheetPath
36 * @throws BiffException
37 * @throws WeblivException
38 */
39
40 public ExcelReader(String ExcelSheetPath) throws IOException, BiffException {
41
42 // Initialize
43 try {
44 wrkbook = Workbook.getWorkbook(new File(ExcelSheetPath));
45 wrksheet = wrkbook.getSheet("Sheet1");
46 } catch (IOException e) {
47 throw newIOException();
48 }
49 }
50 /**
51 * Returns the Number of Rows
52 *
53 * @return Rows
54 */
55
56 public static int RowCount() {
57 return wrksheet.getRows();
58 }
59 /**
60 * Returns the Cell value by taking row and Column values as argument
61 *
62 * @param column
63 * @param row
64 * @return Cell contents
65 */
66
196
67 public static String ReadCell(int column, int row) {
68 returnwrksheet.getCell(column, row).getContents();
69 }
70 /**
71 * Create Column Dictionary to hold all the Column Names
72 */
73 public static void ColumnDictionary() {
74 // Iterate through all the columns in the Excel sheet and store the
75 // value in Hashtable
76 for (int col = 0; col < wrksheet.getColumns(); col++) {
77 dict.put(ReadCell(col, 0), col);
78 }
79 }
80 /**
81 * Read Column Names
82 *
83 * @param colName
84 * @return value
85 */
86
87 public static int GetCell(String colName) {
88 try {
89 int value;
90 value = ((Integer) dict.get(colName)).intValue();
91 returnvalue;
92 } catch(NullPointerException e) {
93 return(0);
94 }
95 }
96 }
Step 4: Create a generic class –“CommonMethods.java”. Create a common method within the class that would
read the cells from the excel sheet using the methods implemented in ExcelReader.java.
1 /**
2 * Read the test data from excel file
3*
4 * @param data The TestData data object
5 */
6
7 public void readExcelData (TestData data) {
197
8 ArrayList<String> browser = new ArrayList<String>();
9 ArrayList<String> username = new ArrayList<String>();
10 ArrayList<String> password = new ArrayList<String>();
11 ArrayList<String> element1 = new ArrayList<String>();
12 ArrayList<String> element2 = new ArrayList<String>();
13 ArrayList<String> element3 = new ArrayList<String>();
14
15 // Get the data from excel file
16 for (int rowCnt = 1; rowCnt < ExcelReader.RowCount(); rowCnt++) {
17 browser.add(ExcelReader.ReadCell(ExcelReader.GetCell("Browser"), rowCnt));
18 username.add(ExcelReader.ReadCell(ExcelReader.GetCell("User ID"), rowCnt));
19 password.add(ExcelReader.ReadCell(ExcelReader.GetCell("Password"), rowCnt));
20 element1.add(ExcelReader.ReadCell(ExcelReader.GetCell("Element1"), rowCnt));
21 element2.add(ExcelReader.ReadCell(ExcelReader.GetCell("Element2"), rowCnt));
22 element3.add(ExcelReader.ReadCell(ExcelReader.GetCell("Element3"), rowCnt));
23 }
24 data.setBrowser(browser);
25 data.setLoginUser(username);
26 data.setPassword(password);
27 data.setElement1(element1);
28 data.setElement2(element2);
29 data.setElement3(element3);
30 }
Step 5: Create a new java class named as “TestData.java”. This class would act as a getter and setter for excel
data. Copy and paste the following code in the TestData.java class.
1 package Utilities.dataSetters;
2 import java.util.ArrayList;
3 public class TestData {
4 private ArrayList<String> loginUser = null;
5 private ArrayList<String> password = null;
6 private ArrayList<String> browser = null;
7 private ArrayList<String> element1 = null;
8 private ArrayList<String> element2 = null;
9 private ArrayList<String> element3 = null;
10 /**
11 * @return loginUser
12 */
13 public ArrayList<String> getLoginUser() {
14 return loginUser;
198
15 }
16 /**
17 * @param loginUser
18 */
19 public void setLoginUser(ArrayList<String> loginUser) {
20 this.loginUser = loginUser;
21 }
22 /**
23 * @return password
24 */
25 public ArrayList<String> getPassword() {
26 return password;
27 }
28 /**
29 * @param password
30 */
31 public void setPassword(ArrayList<String> password) {
32 this.password = password;
33 }
34 /**
35 * @return browser
36 */
37 public ArrayList<String> getBrowser() {
38 return browser;
39 }
40 /**
41 * @param browser
42 */
43 public void setBrowser(ArrayList<String> browser) {
44 this.browser = browser;
45 }
46 /**
47 * @return element1
48 */
49 public ArrayList<String> getElement1() {
50 return element1;
51 }
52 /**
53 * @param element1
199
54 */
55 public void setElement1(ArrayList<String> element1) {
56 this.element1 = element1;
57 }
58 /**
59 * @return element2
60 */
61 public ArrayList<String> getElement2() {
62 return element2;
63 }
64 /**
65 * @param element2
66 */
67 public void setElement2(ArrayList<String> element2) {
68 this.element2 = element2;
69 }
70 /**
71 * @return element3
72 */
73 public ArrayList<String> getElement3() {
74 return element3;
75 }
76 /**
77 * @param element3
78 */
79 public void setElement3(ArrayList<String> element3) {
80 this.element3 = element3;
81 }
82 }
Step 6: The next step is to create instances of “TestData.java” and “CommonMethods.java” java classes within
the test script in order to access and populate the test data. Refer the below code snippet for object initialization,
reading excel data and populating the values wherever required.
1 // Create Objects
2 public ExcelReader excelReaderObj;
3 CommonMethods commonMethodobj = new CommonMethods();
4 TestData td = new TestData();
5
6 // Load the excel file for testing
7 excelReaderObj = new ExcelReader(Path of the excel);
8
200
9 // Load the Excel Sheet Col in to Dictionary for use in test cases
10 excelReaderObj.ColumnDictionary();
11
12 // Get the data from excel file
13 commonMethodobj.readExcelData (td);
14
15 // Populate the username
16 driver.findElement(By.id("idofElement")).sendKeys(data.getLoginUser().get(0));
Therefore using the instance of testData.java class in conjunction with getters, any test data value can be
populated within the script.
Conclusion:
The tutorial mainly revolved around the notions like Framework Creation and Accessing test data from the
excels. We made you acquainted with the Framework creation strategy using a sample project. We briefly laid
light on the various components and aspects of our framework.
In order to access the test data stored in the external data source, we used a java based API – jxl. We also
created the sample code for reading and populating the excel data into the testscripts.
Next Tutorial #22: In the next tutorial, we would base our tutorial on the concepts of generics and their
accessibility mechanism. We would create a few sample generic methods and then access them within the test
scripts. We would also introduce you with the concept of Testsuite and the sample code development.
201
Tutorial #22 – Creating Generics and Testsuite
In the previous tutorial, we started off with the representation of the sample project hierarchy and various
framework components. We also discussed about the data source – “excels” used to store the test data and their
excel manipulations. We also discussed about the new strategies and resources to mature our framework.
Now we are moving ahead with advanced topics in this Selenium Training Series. In this session, we would
take the opportunity to discuss two important concepts that plays an important role to mature the framework.
We would discuss the concept of Generics and reusability aspects. We would also discuss about creation
and significance of Test suite.
For better understanding we would accompany the concepts with adequate examples and sample code.
Generics
By the literal notion, a generic is something that can act as a descriptive of an entire group or classes.
While automating applications, we come across various end to end scenarios. An end to end scenario may
consist of several trivial functionality. Thus, many of these functionality can act as common functionality to
more than one test script with slight or almost no modifications.
Hence, it is advisable to create a generic class consisting of methods that can be claimed as common and can be
shared among multiple test scripts instead of implementing the same code again and again for multiple test
scripts.
Take a note that generics also introduce the power of reusability in our framework. Reusability reduces time
taken for code, errors, bugs, maintenance etc. exceptionally.
Type of Generics
202
excels again and again in all the test scripts. Therefore, we induce the code once in the generic class and make a
call to it whenever required.
Step 1: Create a new java class “CommonMethods.java” that would act as a generic class consisting of
common methods preferably in the package other than where test scripts reside.
Step 2: The next step is to copy and paste the below code in the “CommonMethods.java” generic class. Number
of common methods can be implemented inside the periphery of this class. Below is the code snippet for login
functionality.
1 /**
2 * Login the Test application
3*
4 * @param username
5 * @param password
6 */
7 public void login(String username, String password) {
8 try {
9 // Enter User Name
10 WebElement userName = driver.findElement(By.id("loginID"));
11 userName.clear();
12 userName.sendKeys(username);
13 // Enter Password
14 WebElement passWord = driver.findElement(By.id("Password"));
15 passWord.clear();
16 passWord.sendKeys(password);
17 // Click on the Sign In Button
18 WebElement signin = driver.findElement(By.id("SignIn_button"));
19 signin.click();
20 driver.manage().window().maximize();
21 } catch (Exception e) {
22 e.printStackTrace();
23 }
24 }
Take a note that the aforementioned method is a parameterized method. Thus, the same method can be used to
test the login functionality with different sets of test data.
203
Step 3: The next step is to call the common method within the test script. The process is a two step process.
First we create the instance of the generic class within the test class and then we call the common method on the
created instance by passing the required arguments. In the code fragment below, we created an instance of
“TestScript1.java” class and called the login () method to login the application.
1 // Create Object of the generic class
2 toolsObj = new Tools();
3 // Login the test application by calling the common method
4 preTestObj.login(“username”, “password”);
Take a mention that the above code can be placed anywhere inside the test class. User can place the code in the
setup () method or in the test () method.
Testsuite
Test suite is an assortment of more than one test script grouped together for execution purpose. Thus, test suite
executes the number of specified test scripts unattended. Test suite has the capability to cite the test scripts to be
executed automatically; all that is required from the user is to mark an entry each for the individual test script
within the test suite. The entry is supposed to be the “class name” of the test script with “.class” extension or
simply the compiled form of our java class.
Below is the sample Test suite created in java. Take a note that Test suite is a java based class that belongs to
the family of JUnit. Thus, you may encounter several JUnit annotations in the code.
Code Snippet
1 package com.axway.webliv.tests;
2 import org.junit.AfterClass;
3 import org.junit.BeforeClass;
4 import org.junit.runner.JUnitCore;
5 import org.junit.runner.Result;
6 import org.junit.runner.RunWith;
7 import org.junit.runner.notification.Failure;
8 import org.junit.runners.Suite;
9 import com.axway.webliv.tests.MetaData.*;
204
10
11 @RunWith(Suite.class)
12 @Suite.SuiteClasses({
13
14 ChangeStatusBinarySphereTest.class,
15 ChangeStatusRestrictionTest.class,
ChangeStatusDocSphereTest.class
16
,
17 })
18
19 public class TestSuite {
20 /**
21 * Setup method to set system properties
22 */
23 @BeforeClass
24 public static void Setup() {
25 }
26 /**
27 * @param args
28 */
29 public static void main(String[] args) {
30 Result result = JUnitCore.runClasses(TestSuite.class);
31 System.out.println("TEST CASES RUN: " + result.getRunCount());
32 System.out.println("TEST CASES FAILED: " + result.getFailureCount());
33 for (Failure failure : result.getFailures()) {
34 System.out.println("\nTEST NAME: " + failure.getTestHeader());
35 System.out.println("\nERROR: " + failure.getMessage() + "\n");
36 System.out.println(failure.getTrace());
37 System.exit(1);
38 }
39 }
40 /**
41 * Report test results
42 */
43 @AfterClass
44 public static void TearDown() {
45 }
46 }
Code Walk-Through
A test suite is none other than a simple JUnit class having setup() and teardown() methods; the one’s we
discussed at length in our preceding tutorials. The only remarkable difference lies in its competence to execute
more than one test script in a single go.
Import Statements
205
1 import org.junit.AfterClass;
2 import org.junit.BeforeClass;
3 import org.junit.runner.JUnitCore;
4 import org.junit.runner.Result;
5 import org.junit.runner.RunWith;
6 import org.junit.runner.notification.Failure;
7 import org.junit.runners.Suite;
The above import statements are embedded in the class to be able to use various annotations provided by the
JUnit.
import org.junit.runner.JUnitCore;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
The above statements possess the underlying architecture to execute the test suite consisting of multiple test
classes.
import org.junit.runner.Result;
The import statement allows the user to store the test execution statuses and their manipulations.
import org.junit.AfterClass;
import org.junit.BeforeClass;
These import statements are used to identify and annotate setup() and teardown() methods. The setup() method
annotated with BeforeClass instructs the program control to execute the method before each of the test script
execution. Like setup(), teardown() method annotated with AfterClass tells the program control to execute the
method after each of the test script execution.
Class Entry
1 @RunWith(Suite.<strong>class</strong>)
2 @Suite.SuiteClasses({
3 ChangeStatusBinarySphereTest.<strong>class</strong>,
4 ChangeStatusRestrictionTest.<strong>class</strong>,
5 ChangeStatusDocSphereTest.<strong>class</strong>,
6 })
This section of the class allows the user to mark the entries of the test script to be executed in the next run.
Remember the entries are marked with “.class” extension i.e. in their compiled formats.
Execution – main ()
1 public static void main(String[] args) {
2 Result result = JUnitCore.runClasses(TestSuite.class);
3 System.out.println("TEST CASES RUN: " + result.getRunCount());
4 System.out.println("TEST CASES FAILED: " + result.getFailureCount());
206
5 for (Failure failure : result.getFailures()) {
6 System.out.println("\nTEST NAME: " + failure.getTestHeader());
7 System.out.println("\nERROR: " + failure.getMessage() + "\n");
8 System.out.println(failure.getTrace());
9 System.exit(1);
10 }
11 }
This part of the code deals with the execution. The program execution always initiates from the main().
The runClasses method of JUnitCore class is used to execute the test suite. The “Result class” and its methods
are used to determine the execution status in terms of Passed and Failed test cases.
Thus, user is leveraged to play around with the test suite class to be able to suffice his/her requirements.
Conclusion
In this tutorial, we tried to make you acquainted with the concept of generics and common methods. We also
discussed the benefits we get out generics like reusability. We also shared the practical approaches towards
creation of generics and their accessibility.
208
Tutorial #23 – Using Apache ANT
Apache ANT – a Tool for Automating Software Build Processes and its
Importance in Testing – Selenium Tutorial #23
In the last tutorial, we tried to make you acquainted with the concept of generics and common methods. We also
discussed the benefits we get out of generics like reusability. We also shared the practical approaches towards
creation of generics and their accessibility.
In the current tutorial in this Selenium automation series, we would shed light on a build tool named as
“Apache Ant”. We would broadly discuss its applicability and importance besides the practical approach.
Take a note that the tutorial is limited to testing aspects of using Apache Ant.
Apache Ant is a very popular and conventional build tool of our times. Ant is an open source java based build
tool provided by Apache Software Foundation freely distributed under GNU license. Apache Ant plays a
significant role in developer’s as well as Tester’s day to day work schedule. The tool has immense power to
build the development code into deployment utilities.
Ant is a tool that automates the software building process. Ant is not just limited to compilation of code,
rather packaging, testing and a lot more can be achieved in some simple steps.
The tool works on the principle of targets and dependencies defined in the XML files. Ant libraries are used to
build the applications. The libraries have a set of defined tasks to archive, compile, execute, document, deploy,
and test and many more targets. Moreover, Ant allows the user to create his/her own tasks by implementing
their own libraries.
Ant is primarily used with Java Applications but it can still be used for applications built on other languages
depending on the extended support.
The most important aspect of using Ant is that it doesn’t demands another set of code to be written in order to
build the application, rather the entire process is defined by targets which are none other than XML elements.
Ease of Use – The tool provides a wide range of tasks that almost fulfills all the build requirements of
the user.
Platform Independent – Ant is written in Java thus is a platform independent build tool. The only
requirement for the tool is JDK.
Extensibility – As the tool is written in Java and the source code is freely available, user is leveraged
with the benefit to extend the tool’s capabilities by writing java code for adding task in Ant Libs.
Prior to setting up environment for Ant, it is required to install and set JDK on to your system. I am assuming
that the JDK is already set and installed, Thus moving forward with the Ant Setup.
Create an environment variable for “ANT_HOME” and set the variable’s value to the location of Ant folder.
Refer the following screenshot for the same.
210
Edit the Path variable to append the location of the bin folder i.e. compiler location.
User can also verify for the successful Ant installation by typing in the “ant -version” command in the
command prompt. The user would be able to see the following screen for the successful installation.
211
Thus, no other installation is required to use Apache Ant in collaboration with Junit and Selenium WebDriver to
build, execute and report the test scripts.
Note: Take a note to necessarily add “ant-junit4.jar” jar file that can be found within the library folder of the
Ant’s software distribution.
Sample Build.xml
The next step is to create the project’s build file. Build file is nothing but a collection of xml elements. Worth
mentioning that one build file can relate to one and only one project i.e. one build file per project or vice versa.
Build file is customarily located at the project’s root/base folder but the user is leveraged to select the build’s
location driven by his/her wish. Moreover the user is free to rename the build file if he/she desires.
Each of the build file must have one project and at least one target element. Refer the sample build.xml
212
11 <include name="**/*.jar" />
12 </fileset>
13 </path>
14 <echo message="-----------------------------------------------------------------" />
15 <echo message="--------------------Selenium Learning Tests----------------------" />
16 <echo message="-----------------------------------------------------------------" />
17 <target name="init" description="Delete the binary folder and create it again">
18 <echo message="----------Delete the binary folder and create it again----------" />
19 <delete dir="${bin}" />
20 <!-- Create the time stamp -->
21 <tstamp>
22 <format property="lastUpdated"pattern="dd-MM-yyyy HH:mm:ss" />
23 </tstamp>
24 <!-- Create the build directory structure used by compile -->
25 <mkdir dir="${bin}" />
26 </target>
27 <target name="compile" depends="init"description="Compile the source files">
28 <echo message="----------Compile the source files----------" />
2 <javac source="1.7" srcdir="${src}"fork="true" destdir="${bin}" includeantruntime="false"debug="true" debuglevel="lin
9 es,vars,source">
30 <classpathrefid="Learning_Selenium.classpath" />
31 </javac>
32 </target>
33 <target name="exec" depends="compile"description="Launch the test suite">
34 <echo message="----------Launch the test suite----------" />
35 <delete dir="${report}" />
<mkdir dir="${report}" /
36
>
37 <mkdir dir="${report}/xml" />
38 <junit fork="yes"printsummary="withOutAndErr" haltonfailure="no">
39 <classpathrefid="Learning_Selenium.classpath" />
40 <formatter type="xml" />
41 <batchtest fork="yes"todir="${report}/xml">
42 <fileset dir="${src}"includes="**/com/TestSuite.java" />
43 </batchtest>
44 </junit>
45 </target>
46 <target name="junitReport" depends="exec"description="Generate the test report">
47 <echo message="----------Generate the test report----------" />
48 <junitreport todir="${report}">
49 <fileset dir="${report}/xml">
50 <include name="TEST-*.xml" />
51 </fileset>
52 <report format="frames"todir="${report}/html">
53 <param name="TITLE"expression="Selenium_Learning_Report" />
213
54 </report>
55 </junitreport>
56 </target>
57 </project>
Explanation of Build.xml
In the above xml code, we have created targets for the following goals:
1. Deleting and creating directories
2. Compiling the code
3. Executing the test classes
4. Generating the test reports
<target name=“exec” depends=“compile” description=“Launch the test suite”>
Sometimes it is required to execute a particular target only when some other target is executed successfully.
Take a note that the target are executed sequentially i.e. in order of sequence they are mentioned in the build
file. Also I would like to mention that a particular target is executed once and only once for the current build
execution. Thus, when the user is required to generate dependency between the target, he/she has to use depends
attribute. The value of the “depends” attribute shall be the name of the target on which it depends. A target can
depend on more than one target as well.
Built-in Tasks
Ant build file provides varieties of tasks. Few of them are discussed below:
214
File Tasks – File task are self explanatory.
1. <copy>
2. <concat>
3. <delete>
4. <get>
5. <mkdir>
6. <move>
7. <replace>
Compile Tasks
1. <javac> – Compiles source files within the JVM
2. <jspc> – Runs jsp compiler
3. <rmic> – Runs rmic compiler
Archive Tasks
1. <zip>, <unzip> – Creates a zipped folder
2. <jar>, <unjar> – Creates a jar file
3. <war>, <unwar> – Creates a war file for deployment
Testing Tasks
1. <junit> – Runs JUnit testing framework
2. <junitreport> – Generates the test report by converting JUnit generated XML test reports.
Property Tasks
1. <dirname> – Sets the property
2. <loadfile> – Loads a file into property
3. <propertyfile> – Creates a new property file
Misc. Tasks
1. <echo> – Echoes the text message to be printed either on the console or written within an external file.
2. <javadoc> – Generates the java based documentation using javadoc tool.
3. <sql> – Establishes a JDBC connection and hits dash of SQL commands.
Execution
The easiest section is to execute the test suite with Ant. To execute the test suite with Ant, Right click on
“build.xml” and select “Run As -> Ant Build” option. Thus, the option hits the execution. Refer the following
figure for the same.
215
After the entire execution is completed, Ant generates a test execution report for review inside the “Report”
folder.
The execution can also be initiated outside the eclipse by hitting the command on the command prompt. User is
expected to navigate to the directory where build.xml is kept and type “ant”.
Conclusion
In this tutorial, we laid emphasis on useful information related to Ant, its installation and various Ant tasks. Our
motive was to at least introduce you with the basic conceptual picture and its importance as a tool all together
with respect to testing. Hence, we discussed build.xml in detail describing the various components.
Briefing in the end, Ant is a tool that automates the software building process. Ant is not just limited to
compilation of code, rather packaging, testing and a lot more can be achieved in some simple steps.
Next Tutorial #24: We will learn about Maven – a build automation tool. Maven simplifies the code handling
and process of building the project. Most of the projects follow maven structure. We will learn how to use
Maven and Maven project setup for Selenium.
216
Tutorial #24 – Setting up Selenium Maven Project
Use of Maven Build Automation Tool and Maven Project Setup for Selenium
– Selenium Tutorial #24
In our last Selenium tutorial we learned a build tool named as “Apache Ant”. We also broadly discussed its
applicability and importance besides the practical approach.
In this Selenium Testing tutorial we will learn Maven – a build automation tool which is distributed under
Apache Software Foundation. It is mainly used for java projects. It makes build consistent with other project.
Maven is also used to manage the dependencies. For example if you are using selenium version 2.35 and any
later point of time you have to use some other version, then same can be managed easily by Maven. You will
find more examples of this later in this chapter. It works very effectively when there is huge number of Jar files
with different versions.
What is a build tool?
Build tool is used to setup everything which is required to run your java code independently. This can be
applied to your entire java project. It generates source code, compiling code, packaging code to a jar etc. Maven
provides a common platform to perform these activities which makes programmer’s life easier while handling
huge project.
Maven provides pom.xml which is the core to any project. This is the configuration file where all required
information’s are kept. Many of the IDEs (Integrated Development Environments) are available which makes it
easy to use. IDEs are available for tools like Eclipse , NetBeans, IntelliJ etc.
Maven stores all project jars. Library jar are in place called repository which could be central, local or remote
repository. Maven downloads the dependency jar from central repository. Most of the commonly used libraries
are available in http://repo1.maven.org/maven2/.
Downloaded libraries are stored in local repository called m2. Maven uses the libraries available in m2 folder
and if any new dependency added then maven downloads from central repository to local repository. If libraries
are not available in central repository then maven looks for remote repository. User has to configure the remote
repository in pom.xml to download from remote repository.
Below is the example of configuring a remote repository to pom.xml file. Provide id and url of the repository
where libraries are stored.
1 <repositories>
2 <repository>
3 <id>libraryId</id>
4 <url>http://comanyrepositryId</url>
5 </repository>
6 </repositories>
217
groupId: Generally groupId refers to domain id. For best practices company name is used as groupId. It
identifies the project uniquely.
artifactId: It is basically the name of the Jar without version.
version: This tag is used to create a version of the project.
Local repository: Maven downloads all the required dependencies and stores in local repository called
m2. More details regarding the same would be shared in the next topic.
Build Life Cycle:
Basic maven phases are used as below.
clean: deletes all artifacts and targets which are created already.
compile: used to compile the source code of the project.
test: test the compiled code and these tests do not require to be packaged or deployed.
package: package is used to convert your project into a jar or war etc.
install: install the package into local repository for use of other project.
Maven Setup:
Step 1: To setup Maven, download the maven’s latest version form Apache depending upon different OS.
Step 2: Unzip the folder and save it on the local disk.
Step 3: Create environment variable for MAVEN_HOME. Follow the below step:
Navigate to System Properties ->Advanced System Setting->Environment Variable ->System Variable ->New -
>Add path of Maven folder
218
Step 4: Edit path variable and provide the bin folder path.
Step 5: Now verify the maven installation using command prompt and don’t forget to setup JAVA_HOME
Use mvn –version to verify maven version and output comes like below.
219
Install maven IDE in Eclipse:
Maven provides IDE to integrate with eclipse. I am using eclipse Juno here.
Navigate to Help->Eclipse Marketplace-> Search maven ->Maven Integration for Eclipse ->INSTALL
Then right click on pom.xml and verify all the options are available like below.
220
Create Maven project:
Step 1: Navigate to File- new-others-Maven-Maven Project-Click Next
221
------------
Step 3: Provide Group Id and Artifact Id .You can change the version of Jar as per your wish. Here I am using
default name. Click Finish.
Step 4: After finish you will find the project structure is created like below. pom.xml is created which is used to
download all dependencies.
222
6 </project>
http://repo1.maven.org/maven2/org/seleniumhq/selenium/
Add following dependencies in pom.xml for selenium
1 <dependency>
2 <groupId>org.seleniumhq.selenium</groupId>
3 <artifactId>selenium-java</artifactId>
4 <version>2.41.0</version>
5 </dependency>
1 <dependency>
2 <groupId>junit</groupId>
3 <artifactId>junit</artifactId>
4 <version>4.4</version>
5 </dependency>
If you want to add other third party jar then add those dependencies in pom.xml
Step 6: Final pom.xml will be like below:
<project xmlns="http://maven.apache.org/POM/4.0.0"xmlns:xsi="http://www.w3.org/2001/XMLSchema-
1
instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
2 <modelVersion>4.0.0</modelVersion>
3 <groupId>com.softwaretestinghelp.test</groupId> <artifactId>com.softwaretestinghelp.selenium</artifactId>
4 <version>0.0.1-SNAPSHOT</version>
5 <dependencies>
6 <dependency>
7 <groupId>org.seleniumhq.selenium</groupId>
8 <artifactId>selenium-java</artifactId>
9 <version>2.41.0</version>
10 </dependency>
11 </dependencies>
12 </project>
Step 7: Maven will download all the dependency jars in to local repository called .m2.
M2 folder is basically inside Users->username->m2
All the jars will be placed in a folder called repository which is inside .m2 folder. Maven will create separate
folders for different version and different group id.
223
Step 8: If m2 folder does not populate in Maven dependencies, then you can populate those jars manually.
– Eclipse Windows ->Preference
– Navigate Java->Build Path->Classpath Variables
– Click New Button ->Define M2_REPO and provide the path of m2 folder.
224
Step 9: Upon successful setup you will find Maven Dependencies folder like below which will have the
required dependency jar for the project
225
For clean: mvn clean
For compile: mvn compile
For Install: mvn install
Below is the info which is displayed when you clean any project and shows “BUILD SUCCESS”.
There are many other build tools available in like ant. But it is better to use maven while dealing with different
versions and different dependencies. Maven even can manage the dependencies of dependencies. Other tools
may not provide such flexibility like maven. Please post your queries anything related to maven here.
Next Tutorial #25: In the upcoming tutorial, we would discuss about continuous integration tool known as
Hudson. We would study about its importance, role and benefits into Test Automation Framework. We would
look at the Hudson straight from the beginning, from its installation to its working.
226
Tutorial #25 – Using Hudson Continuous integration tool
In the last two tutorials, we discussed about the two most important build tools – ANT and Maven. We
discussed about their significance and practical importance.
In the current Selenium online training tutorial, we would discuss about a continuous integration tool known
as Hudson. We would study about its importance and benefits that we get out of any continuous integration
tool. We would look at the Hudson straight from the beginning, from its installation to its advance settings.
Continuous Integration
Many a times, we end up working in a project where a large bunch of developers and testers are working
together on different modules. Developers and Testers work on their modules thereby developing executables.
These work products are then integrated at regular intervals. Thus, every time we create a development code, it
needs to be integrated, tested and built to ensure that the code developed doesn’t break or introduces errors or
defects.
This process of building and testing the development work integrated at regular intervals is known
as Continuous Integration (CI). Continuous Integration lets you identify and address the defects or errors as
soon as possible in the development lifecycle i.e. closer to the time, they were introduced.
Continuous Integration system builds and tests the application as soon as the fresh/changed code is committed
to the Source Control Management system acronym as SCM. With its great benefits and impact over the
industries, it has become an integral part of Software Development life cycle and is mandatorily practiced.
227
Hudson supports a large range of tools and plugins.
Hudson:
Supports SCM tools like CVS, Subversion (SVN), Git etc.
Is capable of building ANT based projects, Maven based projects etc.
Is capable of executing shell scripts and Windows batch commands
Is capable of Sending reports, notifications etc via Email, SMS, Skype etc.
Hudson Installation
Pre-requisites
To be able to use Hudson, we need the following things to be in place before we get started:
For this tutorial, we would discuss installation by WAR file. Let us discuss the entire process step by step.
Step 1: Download the Hudson WAR file from the Hudson’s official website – “http://hudson-ci.org/”. Keep the
war file in the desired location in the local file system. This WAR file can be started directly via command
prompt or can be used in Servlet Container. The WAR is an executable file that has a Servlet Container
embedded in itself.
228
Step 2: The next step is to initialize the Hudson web user interface. For this, we need to open command prompt
and go to the folder where Hudson war is kept.
Type java -jar hudson-3.0.1.war –httpPort=8099
The above command would show that the Initial setup is required to be done on Hudson Dashboard. Refer the
below screen.
229
Note: It is advisable to start Hudson as a service on Windows or Linux machine.
Step 3: To be able to access the Hudson window, open your browser and launch Hudson.
Type “http://localhost:8099/” – This will open hudson window.
(Click to enlarge image)
230
Step 4: Select the desired plugins and click on the Finish button. Please be patient as it is likely to take a few
minutes to install all the plugins.
Note: There are several options available to provide support for SCM. Check mark the SCM option, you wish to
use.
Once, all the plugins have been installed, user can view the Hudson Dashboard.
Hudson Configuration
Now that the Hudson Dashboard is ready, the next step is to configure the Hudson. Let us again discuss the
entire process in steps:
231
Step 1: To configure the Hudson, click on the “Manage Hudson” link displayed in the left menu.
Step 2: Click on the “Configure System” link in the next step. Refer the following screenshot.
Step 3: As soon as you click on the Configure system link, numerous sections for connection parameters would
be should. Add an entry to JDK as shown in the following figure. User needs to provide the name of the JDK
installation and the location where java is installed. More than one Java instances can be added.
User can also install JDK automatically by checking a “Install automatically” checkbox.
Step 4: In the next step, add an entry to Ant as shown in the following figure. User needs to provide the name of
the Ant installation and the location where Ant is installed locally.
Like JDK and Ant, user can configure other connection parameters.
232
Note: Always remember to uncheck the “Install automatically” checkbox. The checkbox should be selected in
case if you wish to download the artifact from the internet.
Configuring Email Notification
Email Notification section is shown in the end of the same webpage. User needs to configure the following
fields:
Click on advanced button to see all the options related to Email Notification.
SMTP server: SMTP Server stores the information about SMTP Server i.e. the IP number or fully
qualified name of the server. For demonstration, In this tutorial, we will use Gmail’s SMTP server.
Default User E-mail Suffix: An email suffix can be provided in this field which could be suffixed with
the username and can be used to send the email notification.
System Admin E-mail Address: Admin E-mail Address is used as a sender email id from which all the
notifications would be sent.
Hudson URL: If you are likely to publish reports or build information within the Email Notification,
then Hudson URL needs to be provided. Hudson URL will be used to access the reports. A valid URL
needs to be provided, however if all the receivers are connected to the intranet, then the IP address of the
machine hosting Hudson can also be provided.
Use SMTP Authentication: Enabling this option lets the username and password field appear for
authentication purpose.
Use SSL: User can activate SSL by selecting this option to connect with the SMTP Server.
SMTP Port: User needs to provide the port number in this field which is used to communicate with the
mail Server. If no port numbers are specified, then default port numbers are assigned.
Charset: This field specifies the character set used to compose emails.
As we already mentioned that we would be using Gmail mail server to send email notification in this tutorial,
refer the following screenshots and make the necessary changes in the Email Notification section.
233
Click on the Save button in order to save all the newly made changes.
To create and configure a new Hudson Project, follow the steps ahead:
Click on the “New Job” option displayed in the left menu. The following page would open which displays the
options related to project creation and project styles.
There are numerous styles in which the project/job can be created. Take a note that project and job can be used
interchangeably as they both tend to mean the same thing.
234
Build a free-style software job: This is the most commonly used method to create a new Hudson Job.
Build multi-configuration job: This style of project is used to execute variety of jobs.
Monitor an external job: This style of project monitors an external job.
Copy existing job: In case if we have a project similar to an existing project, then this style can be
helpful. All you have to do is to specify the existing job’s name and the replica of this job would be
created.
However, for this tutorial, we would create a free style Hudson project. Type in the name of the job you wish to
create and click on the OK button. Clicking OK will land you to the Job’s configuration page as shown below:
235
Source Code Management: The section allows you to provide the settings related to Source Code
Management system. Select “None” if no SCM is being used. Take a note that the user would be able to
see only those SCM options whose plugin was installed at the time of Hudson installation. In order to
add more SCM to the Hudson, user can visit the Manage Plugins page and can install the required
plugins.
Build Triggers: This section lets the user decide how to initiate the build execution.
Build: This section lets the user provide the build mechanism settings.
Post-build Actions: This section lets the user provide settings to the post build actions that would be
executed once the build execution is completion.
Let us take a step ahead and configure the job with the necessary settings. User can leave the options under
“General Job Settings” and “Advanced Job Options” to their default state.
Step 1: Select “Subversion” option. As soon as the user selects Subversion, following options would appear.
Step 2: The next step is to provide the SVN’s “Repository URL”. As I have created a local repository, I would
provide a local repository URL. A local repository can be created using Tortoise SVN.
236
The next step is to configure the build triggers. Hudson allows you to set triggers to initiate the build execution
process automatically. User can configure the job to build automatically if any other project/job is built.
Alternatively, user can also set the build to execute periodically i.e. scheduling the build execution or user can
also schedule a build to look for fresh commits in the SCM and trigger execution if any or the user can also set
to initiate the build execute whenever there is an update in the maven dependencies provided your project is a
Maven based project.
To set these options, all you have to do is select the desired build trigger. User is also leveraged to select more
than one option at a time.
While selecting any of the above triggers, user might have to provide some additional information specific to
the trigger type.
Build after other jobs are built: The name of the jobs which can trigger the execution of this job should
be mentioned.
Build periodically: The schedule should be mentioned. There is a specific protocol that needs to be
followed to mention the schedule. More information on Schedule is shown below:
237
Poll SCM: User needs to specify the schedule. The field acts same as that of “Build periodically”.
Build when Maven dependencies have been updated by Maven 3 integration: This section doesn’t
require any input to be submitted.
More information can be found by expanding the Help icons.
If the user doesn’t desire to set any of these build triggers, he/she can decide to build the job/project manually.
All he/she has to do is to click on the “Build Now” link displayed in the left menu.
238
Each of the build steps has its own convention to define and invoke.
As we all know that the build execution statuses and reports are one of the most important artifacts or exit
criteria for a Software development life cycle. Therefore, Hudson lets you publish the build execution report,
generate documentations, generate executables/archives etc.
Test execution reports can be published and sent across to the stakeholders via Email. Results of this build can
trigger the execution of another build.
Post build Actions are many, let us take a moment to discuss the most basic ones.
239
#1. Aggregate downstream test results – The setting lets the user aggregate the test execution results of this
job and downstream jobs together to produce more impactful test results. All user needs to do is to provide the
name of the downstream job. In case if the user doesn’t wish to provide any downstream job but still wishes to
exploit the setting he can direct the Hudson to find all the downstream projects.
#2. Record fingerprints of files to track usage – The setting can be used by the user to track down where a
particular file was used.
#3. Publish JUnit test result report – The setting allows the user to publish the JUnit test report by reading
and understanding the custom report generated by JUnit. The JUnit test result report provides the user with a
web interface to view the created reports. These reports can be sent over the mails to the stakeholders. To
enable this option, all user is required to do is to provide the path to the custom report generated by JUnit.
#4. Archive the artifacts – This setting lets the user create artifacts which can be distributed for further use.
The artifact can be produced after every successful build. These artifacts can directly be accessed by the user
over the web interface. Artifacts can be release executables in the form of war files, jar files, zipped or tar
folders.
240
#5. Publish Javadoc – This setting lets you publish the java doc to customers and users on the Hudson web
interface provided your project generates the java doc. To enable this option, user is required to provide the
location of the Java Doc against Javadoc directory.
If user checks mark the option “Retain Javadoc for each successful build”, the newly generated Javadoc would
be saved in the specified folder. Thus, all the Javadocs corresponding to the successful build would be
maintained.
#6. Build other jobs – The setting lets the user trigger the execution of other jobs once this job is executed.
User can trigger execution of more than one job at the same time. The setting can be helpful to execute unit test
and integration test scenarios. User can even set the option to build other jobs even if this job fails (unstable).
#7. Publish Cobertura Coverage Report – Cobertura is a java based testing tool which analyzes the code
coverage of your project i.e. it assess the percentage of code covered by the tests. Thus the setting allows the
user to generate a report with Code coverage analysis. The setting requires a few parameters to be provided
before you can get a fully fledged testing report on code coverage. Take a note that this setting doesn’t come by
default i.e. it requires a plugin to be installed (Which we did at the time of installation as it is generally a part of
the suggested plugins).
#8. E-mail Notification – Email Notification is one of the most important post build action. The option lets the
user send the build notification email to the stakeholders (developers, testers, product owners etc.) by
configuring their email ids. Hudson can send the email when the build is unstable, successful, failed etc. User
can also set E-mail Notification triggers. The notification email can be send to more than one recipient at the
same time just by providing a white-space between their email ids. Refer the below screenshot to check how
these settings can be provided.
(Click on image to enlarge)
241
Notes:
1. User can anytime come back to this page and change the settings if required.
2. User can view the information about each option within the help icon associated with it.
3. User can add more post build actions with the help of plugins.
Conclusion:
In this tutorial, we made you acquainted with the concept of Continuous Integration. We also laid emphasis on
its importance during a Software Development life cycle especially in a developer’s or tester’s life.
Next Tutorial #26: Moving ahead in the series, we would discuss about some advanced Selenium
concepts that would directly or indirectly help in optimizing the Automation framework and brings more
visibility to the users. Thus, in the next tutorial, we would discuss about the logging feature, its potential,
debugging capabilities and much more.
242
Advanced Selenium
• Tutorial #26 – Logging in Selenium
• Tutorial #27 – Selenium Scripting Tips and Tricks
• Tutorial #28 – Database Testing using Selenium WebDriver
• Tutorial #29 – Selenium Grid Introduction (Must Read)
• Tutorial #30 – Automation Testing Using Cucumber and Selenium Part -1
• Tutorial #31 – Integration of Selenium WebDriver with Cucumber Part -2
243
Tutorial #26 – Logging in Selenium
Most Popular Test Automation Frameworks with Pros and Cons of Each – Selenium
Tutorial #20
In the last few Selenium tutorials, we discussed about various commonly and popularly used commands in
WebDriver, handling web elements like Web Tables, Framesand handling exceptions in Selenium scripts.
We discussed each of these commands with sample code snippets and examples so as to make you capable of
using these commands effectively whenever you are encountered with similar situations. Amongst the
commands we discussed in the previous tutorial, few of them owe utmost importance.
As we move ahead in the Selenium series, we would concentrate our focus towards Automation Framework
creation in the next few upcoming tutorials. We would also shed light on various aspects of an Automation
framework, types of Automation frameworks, benefits of using a framework and the basic components that
constitutes an Automation framework.
What is Framework?
A framework is considered to be a combination of set protocols, rules, standards and guidelines that can be
incorporated or followed as a whole so as to leverage the benefits of the scaffolding provided by the
Framework.
Keep a check on the maximum capacity of the elevator and do not get onto an elevator if the maximum
capacity has reached.
Press the alarm button in case of any emergency or trouble.
Allow the passenger to get off the elevator if any before entering the elevator and stand clear off the
doors.
In case of fire in the building or if there is any haphazard situation, avoid the use of elevator.
Do not play or jump inside the elevator.
Do not smoke inside the elevator.
Call for the help/assistance if door doesn’t open or if the elevator doesn’t work at all. Do not try to open
the doors forcefully.
244
There can be many more rules or sets of guidelines. Thus, these guidelines if followed, makes the system more
beneficial, accessible, scalable and less troubled for the users.
Now, as we are talking about “Test Automation Frameworks”, let us move our focus towards them.
Test Automation Framework
A “Test Automation Framework” is scaffolding that is laid to provide an execution environment for the
automation test scripts. The framework provides the user with various benefits that helps them to develop,
execute and report the automation test scripts efficiently. It is more like a system that has created specifically to
automate our tests.
In a very simple language, we can say that a framework is a constructive blend of various guidelines, coding
standards, concepts, processes, practices, project hierarchies, modularity, reporting mechanism, test data
injections etc. to pillar automation testing. Thus, user can follow these guidelines while automating application
to take advantages of various productive results.
The advantages can be in different forms like ease of scripting, scalability, modularity, understandability,
process definition, re-usability, cost, maintenance etc. Thus, to be able to grab these benefits, developers are
advised to use one or more of the Test Automation Framework.
Moreover, the need of a single and standard Test Automation Framework arises when you have a bunch of
developers working on the different modules of the same application and when we want to avoid situations
where each of the developer implements his/her approach towards automation.
Note: Take a note that a testing framework is always application independent that is it can be used with any
application irrespective of the complications (like Technology stack, architecture etc.) of application under
test. The framework should be scalable and maintainable.
Advantage of Test Automation framework
1. Reusability of code
2. Maximum coverage
3. Recovery scenario
4. Low cost maintenance
5. Minimal manual intervention
6. Easy Reporting
Types of Test Automation Framework
Now that we have a basic idea of what is an Automation Framework, in this section we would harbinger you
with the various types of Test Automation Frameworks those are available in the market place. We would also
try shed lights over their pros and cons and usability recommendations.
245
There is a divergent range of Automation Frameworks available now days. These frameworks may differ from
each other based on their support to different key factors to do automation like reusability, ease of maintenance
etc.
Let us discuss the few most popularly used Test Automation Frameworks:
1. Module Based Testing Framework
2. Library Architecture Testing Framework
3. Data Driven Testing Framework
4. Keyword Driven Testing Framework
5. Hybrid Testing Framework
6. Behavior Driven Development Framework
(click on image to view enlarged)
These modules are separated by an abstraction layer in such a way that the changes made in the sections of the
application doesn’t yields affects on this module.
246
Pros:
1. The framework introduces high level of modularization which leads to easier and cost efficient
maintenance.
2. The framework is pretty much scalable
3. If the changes are implemented in one part of the application, only the test script representing that part
of the application needs to be fixed leaving all the other parts untouched.
Cons:
1. While implementing test scripts for each module separately, we embed the test data (Data with which
we are supposed to perform testing) into the test scripts. Thus, whenever we are supposed to test with a
different set of test data, it requires the manipulations to be made in the test scripts.
#2) Library Architecture Testing Framework
The Library Architecture Testing Framework is fundamentally and foundationally built on Module Based
Testing Framework with some additional advantages. Instead of dividing the application under test into test
scripts, we segregate the application into functions or rather common functions can be used by the other parts of
the application as well. Thus we create a common library constituting of common functions for the application
under test. Therefore, these libraries can be called within the test scripts whenever required.
The basic fundamental behind the framework is to determine the common steps and group them into functions
under a library and call those functions in the test scripts whenever required.
247
Example: The login steps can be combined into a function and kept into a library. Thus all the test scripts those
require to login the application can call that function instead of writing the code all over again.
Pros:
1. Like Module Based Framework, this framework also introduces high level of modularization which
leads to easier and cost efficient maintenance and scalability too.
2. As we create common functions that can be efficiently used by the various test scripts across the
Framework. Thus, the framework introduces a great degree of re-usability.
Cons:
1. Like Module Based Framework, the test data is lodged into the test scripts, thus any change in the test
data would require changes in the test script as well.
2. With the introduction of libraries, the framework becomes a little complicated.
#3) Data Driven Testing Framework
While automating or testing any application, at times it may be required to test the same functionality multiple
times with the different set of input data. Thus, in such cases, we can’t let the test data embedded in the test
script. Hence it is advised to retain test data into some external data base outside the test scripts.
Data Driven Testing Framework helps the user segregate the test script logic and the test data from each other.
It lets the user store the test data into an external database. The external databases can be property files, xml
files, excel files, text files, CSV files, ODBC repositories etc. The data is conventionally stored in “Key-Value”
pairs. Thus, the key can be used to access and populate the data within the test scripts.
Note: The test data stored in an external file can belong to the matrix of expected value as well as matrix of
input values.
248
Example:
Let us understand the above mechanism with the help of an example.
Step 1: First and the foremost step are to create an external file that stores the test data (Input data and Expected
Data). Let us consider an excel sheet for instance.
Step 2: The next step is to populate the test data into Automation test Script. For this purpose several API’s can
be used to read the test data.
1 public void readTD(String TestData, String testcase) throws Exception {
2 TestData=readConfigData(configFileName,"TestData",driver);
3 testcase=readConfigData(configFileName,"testcase",driver);
4 FileInputStream td_filepath = new FileInputStream(TestData);
5 Workbook td_work =Workbook.getWorkbook(td_filepath);
6 Sheet td_sheet = td_work.getSheet(0);
7 if(counter==0)
8 {
9 for (int i = 1,j = 1; i <= td_sheet.getRows()-1; i++){
10 if(td_sheet.getCell(0,i).getContents().equalsIgnoreCase(testcase)){
11 startrow = i;
12 arrayList.add(td_sheet.getCell(j,i).getContents());
13 testdata_value.add(td_sheet.getCell(j+1,i).getContents());}}
14 for (int j = 0, k = startrow +1; k <= td_sheet.getRows()-1; k++){
15 if(td_sheet.getCell(j,k).getContents()==""){
16 arrayList.add(td_sheet.getCell(j+1,k).getContents());
17 testdata_value.add(td_sheet.getCell(j+2,k).getContents());}}
18 }
19 counter++;
20 }
The above method helps to read the test data and the below test step helps the user to type in the test data on the
GUI.
element.sendKeys(obj_value.get(obj_index));
249
Pros:
1. The most important feature of this framework is that it considerably reduces the total number of scripts
required to cover all the possible combinations of test scenarios. Thus lesser amount of code is required
to test a complete set of scenarios.
2. Any change in the test data matrix would not hamper the test script code.
3. Increases flexibility and maintainability
4. A single test scenario can be executed altering the test data values.
Cons:
1. The process is complex and requires an extra effort to come up with the test data sources and reading
mechanisms.
2. Requires proficiency in a programming language that is being used to develop test scripts.
#4) Keyword Driven Testing Framework
The Keyword driven testing framework is an extension to Data driven Testing Framework in a sense that it not
only segregates the test data from the scripts, it also keeps the certain set of code belonging to the test script into
an external data file.
These set of code are known as Keywords and hence the framework is so named. Key words are self-guiding as
to what actions needs to be performed on the application.
The keywords and the test data are stored in a tabular like structure and thus it is also popularly regarded as
Table driven Framework. Take a notice that keywords and test data are entities independent of the automation
tool being used.
In the above example keywords like login, clickLink and verifyLink are defined within the code.
Depending upon the nature of application keywords can be derived. And all the keywords can be reused
250
multiple times in a single test case. Locator column contains the locator value that is used to identify the web
elements on the screen or the test data that needs to be supplied.
All the required keywords are designed and placed in base code of the framework.
Pros:
1. In addition to advantages provided by Data Driven testing, Keyword driven framework doesn’t require
the user to possess scripting knowledge unlike Data Driven Testing.
2. A single keyword can be used across multiple test scripts.
Cons:
1. The user should be well versed with the Keyword creation mechanism to be able to efficiently leverage
the benefits provided by the framework.
2. The framework becomes complicated gradually as it grows and a number of new keywords are
introduced.
#5) Hybrid Testing Framework
As the name suggests, the Hybrid Testing Framework is a combination of more than one above mentioned
frameworks. The best thing about such a setup is that it leverages the benefits of all kinds of associated
frameworks.
In the above example, keyword column contains all the required keywords used in the particular test case and
data column drives all the data required in the test scenario. If any step does not need any input then it can be
left empty.
251
#6) Behavior Driven Development Framework
Behavior Driven Development framework allows automation of functional validations in easily readable and
understandable format to Business Analysts, Developers, Testers, etc. Such frameworks do not necessarily
require the user to be acquainted with programming language. There are different tools available for BDD like
cucumber, Jbehave etc. Details of BDD framework are discussed later in Cucumber tutorial. We have also
discussed details on Gherkin language to write test cases in
Cucumber.
Components of Automation Testing Framework
(click on image to view enlarged)
Though the above pictorial representation of a framework is self-explanatory but we would still highlight a few
points.
1. Object Repository: Object Repository acronym as OR is constituted of the set of locators types
associated with web elements.
2. Test Data: The input data with which the scenario would be tested and it can be the expected values
with which the actual results would be compared.
3. Configuration File/Constants/ Environment Settings: The file stores the information regarding the
application URL, browser specific information etc. It is generally the information that remains static
throughout the framework.
252
4. Generics/ Program logics/ Readers: These are the classes that store the functions which can be
commonly used across the entire framework.
5. Build tools and Continuous Integration: These are the tools that aids to the frameworks capabilities to
generate test reports, email notifications and logging information.
Conclusion
The frameworks illustrated above are the most popular frameworks used by the testing fraternity. There are
various other frameworks also in the place. For all the further tutorials we would base on the Data Driven
Testing Framework.
In this tutorial, we discussed about the basics of an Automation Framework. We also discussed about the types
of frameworks available in the market.
Next Tutorial #27: In the next tutorial, we would briefly introduce you with the sample framework, the MS
Excel which would store the test data, excel manipulations etc.
Till then feel free to ask your queries about automation frameworks.
253
Tutorial #27 – Selenium Scripting Tips and Tricks
In the previous tutorial, we discussed the technical implications while implementing logging in a framework.
We discussed log4j utility at length. We discussed the basic components those constitute log4j from a usability
perspective. With the Appenders and layouts, user is leveraged to choose the desired logging format/pattern and
the data source/location.
In the current 27th tutorial in this comprehensive free selenium online training series, we would shift our focus
towards a few trivial yet important topics that would guide us troubleshoot some recurrent problems. We may
or may not use them in daily scripting but they would be helpful in the long run.
We would discuss some advance concepts wherein we would deal with mouse and keyboard events,
accessing multiple links by implementing lists. So why not let’s just start and briefly discuss these topics with
the help of appropriate scenarios and code snippets.
JavaScript Executors
While automating a test scenario, there are certain actions those become an inherent part of test scripts.
That said, to be able to troubleshoot such situation, we shoulder JavaScript executors into the picture.
254
JavascriptExecutor interface is a part of org.openqa.selenium and implements java.lang.Object class.
JavascriptExecutor presents the capabilities to execute JavaScript directly within the web-browser. To be able to
execute the JavaScript, certain mechanisms in the form of methods along with a specific set of parameters are
provided in its implementation.
Methods
executeScript (String script, args)
As the method name suggests, it executes the JavaScript within the current window, alert, frame etc (the
window that the WebDriver instance is currently focusing on)
The parameters and import statement are common to both the executor methods.
Parameters
Script – the script to be executed
Argument – the parameters that the script requires for its execution (if any)
Import statement
To be able to use JavascriptExecutors in our test scripts, we need to import the package using the following
syntax:
import org.openqa.selenium.JavascriptExecutor;
Sample Code
#1) Clicking a web element
1 // Locating the web element using id
2 WebElement element = driver.findElement(By.id("id of the webelement"));
3
4 // Instantiating JavascriptExecutor
5 JavascriptExecutor js = (JavascriptExecutor)driver;
6
7 // Clicking the web element
255
8 js.executeScript("arguments[0].click();", element);
You may find various other ways of writing down the code for accessing JavascriptExecutors.
At times, we may come across elements of same type like multiple hyperlinks, images etc arranged in an
ordered or unordered list. Thus, it makes absolute sense to deal with such elements by a single piece of code and
this can be done using WebElement List. Refer the screenshot below to understand the elements I am talking
about.
256
In the above image, we see that the various service providers belong to an unordered list. Thus, verification of
click ability and visibility of these elements can be done by a single piece of code by using a list of elements.
Import statement
To be able to use WebElement list in our test scripts, we need to import the package using the following syntax:
import java.util.List;
Sample Code
1 // Storing the list
2 List <WebElement> serviceProviderLinks = driver.findElements(By.xpath("//div[@id='ServiceProvider']//ul//li"));
3
4 // Fetching the size of the list
5 int listSize = serviceProviderLinks.size();
6 for (int i=0; i<listSize; i++)
7{
8
9 // Clicking on each service provider link
10 serviceProviderLinks.get(i).click();
11
12 // Navigating back to the previous page that stores link to service providers
257
13 driver.navigate().back();
14 }
There are various requirements under which the lists can be used to verify the elements with suitable
implementation changes.
Thus, at times a necessity arises to deal with a problem by changing the conventional dealing strategy with a
more advance strategy. I have witnessed cases where I could not deal with alerts and pop up etc. by selenium
commands thus I had to opt for different java utilities to deal with it using keyboard strokes and mouse events.
Robot class is one such option to perform keyboard events and mouse events.
Let us understand the concept with the help of a scenario and its implementation.
Scenario:
Let us gather a situation where an unnecessary pop up appears on the screen which cannot be accepted or
dismissed using Alert Interface, thus the only wise option we are left with is to close down the window using
shortcut keys – “Alt + space bar + C”. Let us see how we close the pop up using Robot Class.
Before, initiating the implementation, we should import the necessary package to be able to use Robot class
within our test script.
Import Statement
import java.awt.Robot;
Sample Code
1 // Instantiating Robot class
2 Robot rb =new Robot();
3
4 // Calling KeyPress event
5 rb.keyPress(KeyEvent.VK_ALT);
6 rb.keyPress(KeyEvent.VK_SPACE);
7 rb.keyPress(KeyEvent.VK_C);
8
9 // Calling KeyRelease event
10 rb.keyRelease(KeyEvent.VK_C);
11 rb.keyRelease(KeyEvent.VK_SPACE);
258
12 rb.keyRelease(KeyEvent.VK_ALT);
Robot class can also be used to handle mouse events but let us here look at the selenium’s capabilities to handle
mouse events.
Thus, we would witness Action Interface to mouse hover on a drop down which then opens a list of options in
the next scenario.
Scenario:
1. Mouse Hover on the dropdown
2. Click on one of the items in the list options
Import Statement
import org.openqa.selenium.interactions.Actions;
Sample Code
1 // Instantiating Action Interface
2 Actions actions=<strong>new</strong> Actions(driver);
3
4 // howering on the dropdown
5 actions.moveToElement(driver.findElement(By.<em>id</em>("id of the dropdown"))).perform();
6
7 // Clicking on one of the items in the list options
8 WebElement subLinkOption=driver.findElement(By.id("id of the sub link"));
9 subLinkOption.click();
Conclusion
In this tutorial, we discussed some advance topics related to efficient scripting and to troubleshoot scenarios
where the user is required to handle mouse and keyboard events. We also discussed how to store more than one
web element in a list. I hope you would be able to troubleshoot these impediments if encountered.
Next Tutorial #28: For the upcoming tutorial in the series, we would discuss the concept of Database testing
using Selenium WebDriver. We would witness the mechanism of database connection, hitting selenium
queries and fetching the results through Selenium WebDriver Code.
259
Tutorial #28 – Database Testing using Selenium WebDriver
In our last Selenium tutorial we learned how to troubleshoot some recurrent problems in selenium scripts. We
discussed some advance concepts wherein we would deal with mouse and keyboard events, accessing multiple
links by implementing lists.
Moving ahead with our advance topics in Selenium training series, we would introduce you with the concept
of Database testing using Selenium WebDriver.
We would discuss the basic processes like database connection, executing queries, fetching data and
disconnecting database instances etc. We would also discuss various practical implications where we need
Database testing with automation testing in order to test the complete end-to-end scenarios.
Before moving ahead with the technical implications associated with Automated Database testing. Let us
discuss a few scenarios where we require performing Database testing along with the Automation Testing. But
before that, I would like to affirm here that Database testing is a very peculiar type of testing whereas Selenium
WebDriver is a tool used to simulate and automate user interactions with the Application UI.
So technically speaking we are not precisely performing Database Testing rather we are testing our application
in conjunction with Database in order to ensure that the changes are reflected at both the ends thereby
identifying defects early.
Absolutely all the web applications need a backend to store the Data. Databases like MySQL, Oracle, and SQL
Server are reasonably popular these days.
Now motioning back to the original topic, let us discuss a few scenarios to exemplify the demand of Database
testing along with Automation Testing.
260
connection with the Database using a third party API, execute queries to retrieve data from the dataset and then
asserting the data fetched from the Database with the actual data which is populated on the Application UI.
#3) Another user case is to perform associative Database Testing. Assume that we performed an operation on
the application’s UI, and we want to test the reflection in the Database. It may be a case that the impacted data
resides in various tables of the database due to association. Therefore it is always advisable to test data
reflection at all the impacted areas.
Selenium like I said simulates the user interactions with the application under test. It can simulate keyboard
events, mouse actions etc. But if the user desires to automate anything outside the vicinity of browser – web
application interactions, then selenium can’t be of much help. Thus we require other tools or capabilities to
perform end –to –end testing.
Thus, in all the above scenarios, we may require to perform Database Testing along with UI Automation. We
may check business logics by manipulating the data and verifying its reflection. We may also check the
technical aspects of the Database itself like soft delete, field validation etc.
Let us now move ahead with the actual implementation. Before developing Selenium WebDriver scripts to
extract data from the data source, let us create a test data in the database. For this tutorial, we would use
MySQL as a database.
Note: User can also find GUI based clients over the internet to connect with the database. To name a few, user
can download and install Query Browser or Work Bench.
Creation of new Database
The next step is to create the test database with few tables and records stored in those tables in order to make
connection with the database and execute queries.
261
Step 1) Type “show databases” to see all the already available databases
show databases;
Take a note that the database name as user is created and can be seen in the list of databases.
Step 3) Type “use user;” to select the newly created database. Also type “show tables;” to view all the tables
available within the user database.
use user;
show tables;
262
Take a note that Empty set is shown in the result of the “show tables;” query as there were no tables available
within the user database.
Step 4) Type the following command to create a table with 4 fields/columns (userId, userName, userAge,
userAddress).
create table userinfo
(
userId int,
userName varchar(255),
userAge int,
userAddress varchar(255)
);
263
The next step is to add some data records in the “userinfo” table.
Step 5) Type the following command to insert data into the table a table for all the four fields 4 fields/columns
(userId, userName, userAge, userAddress).
insert into userinfo (userID, userName, userAge, userAddress) values (‘1’, ‘shruti’, ’25’, ‘Noida’);
To view the added data, type the following command:
Similarly, you can add more data in your table and can create other tables as well.
264
Now, that we have created our database. We can move ahead and understand the implementation of
automated queries to fetch the records from the database.
As we also iterated earlier, Selenium WebDriver is a tool for UI Automation. Thus, Selenium WebDriver alone
is ineligible to perform database testing but this can be done using Java Database Connectivity API (JDBC).
The API lets the user connect and interact with the data source and fetch the data with the help of automated
queries. To be able to exploit the JDBC API, it is required to have Java Virtual Machine (JVM) running on the
system.
JDBC Workflow
In this tutorial we would discuss “Read operation and its variants” and about their implementation in Selenium
WebDriver script. But prior to that, let us check the test scenario manually using “MySQL command line”.
Scenario
1) Open the Database server and connect to “user” database.
2) List down all the records from the “userinfo” table.
Syntax : select * from userinfo;
265
3) Close the Database connection.
Notice that the read query will list down all the user data present in the userinfo table. The table is consisting of
the following columns.
userId
username
userAge
userAddress
The result also shows that there is only a single data set present within the table.
here or here.
Step 1: The first and the foremost step is to configure the project’s build path and add “mysql-connector-java-
3.1.13-bin.jar” file as an external library.
Step 2: Create a java class named as “DatabaseTesingDemo”.
Step 3: Copy and paste the below code in the class created in the above step.
266
Code Sample
1 import org.junit.After;
2 import org.junit.Before;
3 import org.junit.Test;
4 import java.sql.Connection;
5 import java.sql.DriverManager;
6 import java.sql.ResultSet;
7 import java.sql.Statement;
8
9 public class DatabaseTesingDemo {
10 // Connection object
11 static Connection con = null;
12 // Statement object
13 private static Statement stmt;
// Constant for Database
14
URL
15 public static String DB_URL = "jdbc:mysql://localhost:3306/user";
16 // Constant for Database Username
17 public static String DB_USER = "root";
18 // Constant for Database Password
19 public static String DB_PASSWORD = "root";
20
21 @Before
22 public void setUp() throws Exception {
23 try{
24 // Make the database connection
25 String dbClass = "com.mysql.jdbc.Driver";
26 Class.forName(dbClass).newInstance();
27 // Get connection to DB
28 Connection con = DriverManager.getConnection(DB_URL, DB_USER, DB_PASSWORD);
29 // Statement object to send the SQL statement to the Database
30 stmt = con.createStatement();
31 }
32 catch (Exception e)
33 {
34 e.printStackTrace();
35 }
36 }
37
38 @Test
39 public void test() {
40 try{
41 String query = "select * from userinfo";
42 // Get the contents of userinfo table from DB
43 ResultSet res = stmt.executeQuery(query);
267
44 // Print the result untill all the records are printed
45 // res.next() returns true if there is any next record else returns false
46 while (res.next())
47 {
48 System.out.print(res.getString(1));
49 System.out.print("\t" + res.getString(2));
50 System.out.print("\t" + res.getString(3));
51 System.out.println("\t" + res.getString(4));
52 }
53 }
54 catch(Exception e)
55 {
56 e.printStackTrace();
57 }
58 }
59
60 @After
61 public void tearDown() throws Exception {
62 // Close DB connection
63 if (con != null) {
64 con.close();
65 }
66 }
67 }
268
String query = “select userId from userinfo”;
ResultSet res = stmt.executeQuery(query);
Output:
1
2
Display userId with where clause
String Address =”Noida”;
String query = “select userId,userName from userinfo where userAddress='”+Address+”‘”;
ResultSet res = stmt.executeQuery(query);
Output:
2
shrivastava
Thus, in the same way user can execute various queries on the database.
With this, Let us shed some light on result accessibility methods also.
String getString() Method is used to fetch the string type data from
the result set
float getFloat() Method is used to fetch the float type data from
the result set
long getLong() Method is used to fetch the long type data from
the result set
short getShort() Method is used to fetch the short type data from
the result set
269
Method name Description
JDBC makes it possible for the java class to connect with the Database, retrieve data from the database or for
the matter of fact perform any of the CRUD operations, manipulate the resultant data and close the connection.
Thus, the tutorial constitutes of the basic sample implementation of the above mentioned process.
Next Tutorial #29: We will move ahead with advanced Selenium topics. In next tutorial we will cover
Selenium GRID – which is used when you have to perform multi browser testing and you have large number of
test cases.
270
Tutorial #29 – Selenium Grid Introduction (Must Read)
We are now close to the end of this comprehensive Selenium tutorials series. Next week, we will conclude this
online Selenium Training series with “effort estimation of Selenium Projects” and “Selenium Interview
questions and answers” tutorials.
Today, in this tutorial we will introduce you with Selenium Grid – a distributed test execution environment
to speed up the execution of a test pass.
There are 2 versions of Grid available. Selenium Grid 2.0 is the latest from Selenium. Selenium 1.0 was the
earlier version. Most of the Selenium experts prefer using Selenium Grid 2.0 as it is packed with new features.
Selenium Grid 2.0 supports both Selenium RC and Selenium WebDriver scripts.
271
Hub: Hub is central point to the entire GRID Architecture which receives all requests. There is only one hub in
the selenium grid. Hub distributes the test cases across each node.
Node: There can be multiple nodes in Grid. Tests will run in nodes. Each node communicates with the Hub and
performs test assigned to it.
272
Browser and Nodes:
After starting hub and nodes in each machine when you will navigate to GRID Console
You will find 5 Chrome, 5 Firefox and 1 IE browser under Browser section like below.
This indicates that by default you can use 5 Chrome, 5 Firefox and 1 IE browser.
For Instance if you want to use only IE you can start the node by using below command:
273
Similarly for Firefox:
1 java -jar selenium-server-standalone-2.41.0.jar -role webdriver -hub
2 http://localhost:4444/grid/register -port 5556 -browser browserName=firefox
For Chrome:
1 java -jar selenium-server-standalone-2.41.0.jar -role webdriver -hub
2 http://localhost:4444/grid/register -port 5556 -browser browserName=chrome
There are few scenarios where you may need browser from each type i.e.: IE, Chrome and Firefox.
For instance you may need to use 1 IE and 1 Firefox and 1 Chrome browser
274
For example if you want to work with 2 Firefox and 2 IE then you can start the node using maxInstance.
maxSession:
maxSession is used to configure how many number of browsers can be used parallel in the remote system.
NODE1:
275
NODE2:
As in the example you have to use RemoteWebDriver if you are using GRID and you have to provide
capabilities to the browser. You have to set the browser and platform as above.
276
In this example I have used platform as WINDOWS. You can use any platform as per your requirement.
For Instance you need to run this test serially in multiple browsers you have to configure your testng.xml
.Below is the testng.xml suite for above test to run your test serially.
To run the test parallel, you have to change your testng.xml like below.
Here in the testng.xml you have to specify parameter as parllel=“tests” and thread-count=“3” describes the
maximum number of threads to be executed in parallel.
Configuration using JSON file:
277
Grid can also be launched along with its configuration by using json configuration file.
Create a json file for having below configuration. Here I have created a json file named as grid_hub.json
1{
2 "host": null,
3 "port": 4444,
4 "newSessionWaitTimeout": -1,
5 "servlets" : [],
6 "prioritizer": null,
7 "capabilityMatcher": "org.openqa.grid.internal.utils.DefaultCapabilityMatcher",
8 "throwOnCapabilityNotPresent": true,
9 "nodePolling": 5000,
10
11 "cleanUpCycle": 5000,
12 "timeout": 300000,
13 "maxSession": 5
14 }
1{
2 "capabilities":
3 [
4 {
5 "browserName": "chrome",
6 "maxInstances": 2
7 },
8 {
9 "browserName": "firefox",
10 "maxInstances": 2
11 },
12 {
13 "browserName": "internet explorer",
14 "maxInstances": 1
15 }
16 ],
17 "configuration":
18 {
19 "nodeTimeout":120,
278
20 "port":5555,
21
22 "hubPort":4444,
23 "hubHost":"localhost",
24
25 "nodePolling":2000,
26
27 "registerCycle":10000,
28 "register":true,
29 "cleanUpCycle":2000,
30 "timeout":30000,
31 "maxSession":5,
32 }
33 }
You can provide browser version, platform in the json config file like below
{
“browserName”: “chrome”,”version”:”8”,”platform”:”Windows”
}
Conclusion:
It is advisable to use Selenium Grid when you have to perform multi browser testing and you have large
number of test cases.
In this module we covered how to setup Grid hub and nodes along with how to run Grid test cases using
testng.xml and json file.
Next Tutorial #30: Automation testing with Selenium and Cucumber tool. Cucumber is a BDD
testing tool and Framework. We will learn features of Cucumber tool and its usage in real time scenario
including how to integrate Selenium WebDriver with Cucumber.
Please post you queries related to Selenium Grid in comments below.
279
Tutorial #30 – Automation Testing Using Cucumber and Selenium Part -1
In last Selenium tutorial we introduced you to Selenium Gridwhich is a distributed test execution environment
to speed up the execution of a test pass.
Now at the end of this comprehensive Selenium training series we are learning advanced Selenium testingand
related concepts.
In this and the next tutorial we will be introducing you to the Cucumber – a Behavior Driven Development
(BDD) framework which is used with Selenium for performing acceptance testing.
Cucumber Introduction:
Cucumber is a tool based on Behavior Driven Development (BDD) framework which is used to write
acceptance tests for web application. It allows automation of functional validation in easily readable and
understandable format (like plain English) to Business Analysts, Developers, Testers, etc.
Cucumber feature files can serve as a good document for all. There are many other tools like JBehave which
also support BDD framework. Initially Cucumber was implemented in Ruby and then extended to Java
framework. Both the tools support native JUnit.
Behavior Driven Development is extension of Test Driven Development and it is used to test the system rather
than testing the particular piece of code. We will discuss more about the BDD and style of writing BDD tests.
Cucumber can be used along with Selenium, Watir, and Capybara etc. Cucumber supports many other
languages like Perl, PHP, Python, .Net etc. In this tutorial we will concentrate on Cucumber with Java as a
language.
Cucumber Basics:
In order to understand cucumber we need to know all the features of cucumber and its usage.
280
Feature: Login Functionality Feature
In order to ensure Login Functionality works,
I want to run the cucumber test to verify it is working
Scenario: Login Functionality
Given user navigates to SOFTWARETETINGHELP.COM
When user logs in using Username as “USER” and Password “PASSWORD”
Then login should be successful
Scenario: Login Functionality
Given user navigates to SOFTWARETETINGHELP.COM
When user logs in using Username as “USER1” and Password “PASSWORD1”
Then error message should be thrown
#2) Feature:
This gives information about the high level business functionality (Refer to previous example) and the purpose
of Application under test. Everybody should be able to understand the intent of feature file by reading the first
Feature step. This part is basically kept brief.
#3) Scenario:
Basically a scenario represents a particular functionality which is under test. By seeing the scenario user should
be able to understand the intent behind the scenario and what the test is all about. Each scenario should follow
given, when and then format. This language is called as “gherkin”.
1. Given: As mentioned above, given specifies the pre-conditions. It is basically a known state.
2. When: This is used when some action is to be performed. As in above example we have seen when the
user tries to log in using username and password, it becomes an action.
3. Then: The expected outcome or result should be placed here. For Instance: verify the login is
successful, successful page navigation.
4. Background: Whenever any step is required to perform in each scenario then those steps needs to be
placed in Background. For Instance: If user needs to clear database before each scenario then those steps
can be put in background.
5. And: And is used to combine two or more same type of action.
Example:
Feature: Login Functionality Feature
Scenario: Login Functionality
Given user navigates to SOFTWARETETINGHELP.COM
When user logs in using Username as “USER”
And password as “password”
Then login should be successful
And Home page should be displayed
281
Example of Background:
Background:
Given user logged in as databases administrator
And all the junk values are cleared
#4) Scenario Outline:
Scenario outlines are used when same test has to be performed with different data set. Let’s take the same
example. We have to test login functionality with multiple different set of username and password.
For instance: Feature files related to smoke test need not run all the time. So if you mention a tag as smokeTest
in each feature file which is related to smoke test and run cucumber test with @SmokeTest tag . Cucumber will
run only those feature files specific to given tags. Please follow the below example. You can specify multiple
tags in one feature file.
Example of use of single tags:
@SmokeTest
Any number of tags can be mentioned for a feature file as well as for scenario.
@SmokeTest @LoginTest
Feature: Login Functionality Feature
In order to ensure Login Functionality works,
I want to run the cucumber test to verify it is working
Scenario Outline: Login Functionality
Given user navigates to SOFTWARETETINGHELP.COM
When user logs in using Username as <username> and Password <password>
Then login should be successful
Examples:
|username |password |
|Tom |password1 |
|Harry |password2 |
|Jerry |password3 |
Similarly you can specify tags to run specific scenario in a feature file. Please check below example to run
specific scenario.
Similarly you can give instruction to cucumber to run multiple tags. Below example illustrates how to use
multiple tags in cucumber to run different scenarios.
1 import cucumber.api.junit.Cucumber;
2 import org.junit.runner.RunWith;
3 @RunWith(Cucumber.class)
4 @Cucumber.Options(format={"SimpleHtmlReport:report/smokeTest.html"},tags={"@smokeTest",”@LoginTest”})
5 Public class JUnitRunner {
6}
284
Implementation of Feature file:
We have to implement these steps in Java in order to test the feature files. Need to create a class which contains
those given, when and then statements. Cucumber uses its annotations and all the steps are embedded in those
annotations (given, when, then).Each phrase starts with “^” so that cucumber understands the start of the step.
Similarly each step ends with “$”. User can use regular expressions to pass different test data. Regular
expressions take data from feature steps and passes to step definitions. The order of parameters depends how
they are passed from feature file. Please refer next tutorial for project setup and mapping between feature files
and java classes.
Example:
Below example is to illustrate how feature files can be implemented.
In this example we have not used any selenium API. This is to just show how cucumber works as standalone
framework. Please follow next tutorial for selenium integration with cucumber.
When you execute cucumber runner class, cucumber will start reading feature file steps. For example, when you
execute @smokeTest, cucumber will read Feature step and Given statement of scenario. As soon as cucumber
285
finds Given statement, same Given statement will be searched in your java files. If same step is found in java
file then cucumber executes the function specified for the same step otherwise cucumber will skip the step.
Conclusion:
In this tutorial, we have covered features of cucumber tool and its usage in real time scenario.
Cucumber is a most favorite tool for many projects as it is easy to understand, readable and contains business
functionality.
In the next chapter we will cover how to setup a cucumber – java project and how to integrate Selenium
WebDriver with Cucumber.
286
Tutorial #31 – Integration of Selenium WebDriver with Cucumber Part -2
In last tutorial we discussed Cucumber tool, its usage and different features.
Moving ahead in our free Selenium online trainingseries, we will discuss how to set up a cucumber project and
will discuss about integration of selenium WebDriver with Cucumber.
We will set up Cucumber project with Maven. To set up Maven in your system please refer this tutorial on
Maven from the same series.
Cucumber Project Setup:
Step #1: Create New Maven Project:
Right Click -> New -> Others -> Maven -> Maven Project -> Next
Step #2: Now the project will look like this:
287
20 </dependencies>
Provide the path of the report as given here. The reports will store in ‘test-report’ folder under project folder and
“pretty” format specifies the type of report.
288
If we want to use default reporting then navigate the path mentioned in Junit Runner. In this case we have given
path as reports->test-reports->index.html.
Open this report in Internet Explorer or in Firefox to verify the result. Below is the sample of the report:
So here is the sample test case we have implemented using Cucumber and WebDriver. As given below, the
scenario in feature file is self-explanatory.
289
5 dr=new FirefoxDriver();
6 dr.get("http://www.gmail.com");
7 }
8 @When ("^user logged in using username as \"(.*)\" and password as \"(.*)\"$")
9 public void login(String username,String password){
10 dr.findElement(By.xpath("//*[@id='Email']")).sendKeys(username);
11 dr.findElement(By.xpath("//*[@id='Passwd']")).sendKeys(password);
12 dr.findElement(By.xpath("//*[@id='signIn']")).click();
13 dr.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
14 }
15 @Then("^home page should be displayed$")
16 public void verifySuccessful(){
17 String expectedText="Gmail";
18 String actualText= dr.findElement(By.xpath("//*[@id='gbq1']/div/a/span")).getText();
19 Assert.assertTrue("Login not successful",expectedText.equals(actualText));
20 }
21 }
In this test we have used the Firefox as the browser to test the Gmail login functionality.
Clearly WebDriver object is a class variable and used across the class.
Given statement initializes the browser and navigates to the page.
When statement logs into the application using username as “userA” and password as “password”. Both the
values ‘username’ and ‘password’ are passed from feature file and both the values to be used in the same order.
Then Statement only validates the conditions after logging into the application.
This is a sample test describing the usage of Cucumber and Selenium. You can create multilayer architecture
depending upon your project requirement.
Conclusion:
In this Tutorial we have covered most of the Cucumber concepts which includes Cucumber features and its
usage along with WebDriver.
This reduces the complexity of code which is written to design the traditional frameworks like Keyword Driven
and Hybrid Framework. Cucumber is used in most of the project where people follow agile methodology as
Behavior Driven Development is an Agile Software practice.
Next Tutorial #32: We have now completed all technical tutorials from this Selenium training series. Next, we
will post about few important general topics like ‘effort estimation for Selenium projects’ and ‘Selenium
interview questions with answers’.
Please post your queries regarding to Cucumber.
290
Selenium Tips and Interview Preparation
• Tutorial #32 – Selenium project test effort estimation
• Tutorial #33 – Selenium Interview Questions and Answers
291
Tutorial #32 – Selenium project test effort estimation
In last couple of Selenium tutorials we learned about automation testing using Cucumber and Selenium tool.
We also discussed about integration of selenium WebDriver with Cucumber.
In this tutorial we will discuss about different factors affecting effort estimation of Selenium automation.
Planning and estimation are two most important aspect of a software development life cycle.
I personally feel that in software industry, there are no bullet proof methods of doing anything. Since every
project is exclusive and have different sets of complexity and environmental factors, implementing the
estimation and planning strategy should be a collaborative effort of the individual teams with proper
interventions of seniors and management support.
Before you begin with estimating any project, it is imperial to understand each and every phase that your
project will be going through, so that you can give a correct and a justified estimation.
Estimation can not only be done for the manual testing process, but in this era of automation, estimation
techniques are applied to test automation as well. Now Selenium gaining a momentum and popularity in the
market, I am trying to write about some factors which should be taken into consideration while estimating a
Selenium project.
Let’s Start!!
I am assuming that we are starting the Automation initiative from the scratch and that we have no ready-made
framework available.
292
2. Break the application into smaller modules
3. Analyze each module to identify the candidate test cases
4. Calculate ROI
For more details of how to identify the correct test case, please see my previous paper: Selection of correct test
cases for Automation
#2 Complexity of the application
Steps involved here are:
1. Determine the Size the application based on the number of test cases that needs to be automated.
2. Size complexity through Fibonacci series.
3. Identify the verification point and check point of each test case
Here we have to establish the definition of big / medium and small sized application. This definition differs
from an individual / group perspective. How you classify your application, depends can also be dependent upon
the number of test cases.
For example:
If your application has 300 – 500 test cases to automate, you can consider it as small sized application. If the
test cases are over 1500, it can be classified as complex. This factor can be different for different application.
For some, 1500 test cases to automate can be considered as small / medium scaled. So once you have identified
the exact number of test cases, scale it to small / medium or large. Your strategy towards estimating the effort
will hugely dependent on these criteria.
You have to also consider the different check points and verification points for your test case. A test case can
have more than 1 check point but will have only 1 verification point. In case you have more than 1 verification
point, it is recommended to bifurcate into separate test cases. This will also ease your maintenance and
enhancement of your test suite.
293
To achieve these you need separate tools that will be integrated with your framework. So it is important here to
identify these supporting entities which will best suite your requirement and will help to get a positive ROI
1. Identify the input (pattern in which data is fed in to script) and output (reports / test results) of your
automation suite.
2. Design your input files. This may range from a simple text file to complex excel file. It is basically the
file which will have your test data.
3. Design the folder structure based on your input parameters and
4. Implement the reporting feature ( either in some excel file or using any tool like ReportNG)
5. Determine / implement logger in your frame work
6. Implement the build tool in your framework
7. Implement the unit test framework (Junit or TestNG)
There are many other requirements apart from just scripting in test automation with Selenium, like reading the
data from a file, reporting / tracking the test results, tracking logs , trigger the scripts based on the input
conditions and environment etc. So we need a structure that will take care of all these scripts. This structure is
nothing but your Framework.
Web applications are complex by nature because it involves lots of supporting tools and technology to
implement. In a similar way, implementing framework in Selenium is also tricky (I will not say complex) as it
involves other tools to integrate. Since we know Selenium is NOT a tool but actually a collection / group of jar
files, it is configured and not “Installed”, Selenium itself is not strong enough to build a complex framework. It
requires a list of third party tools for building a framework.
We have to remember here that there is nothing “Ready-made” in Selenium. For everything, we have to code,
so provisions in estimation should be there for googling the errors and troubleshooting.
Here we have to understand that that Framework building is the most important aspect of your Automation
effort. If your framework is rock solid, maintenance and enhancement becomes easier specially in the era of
Agile, if your framework is good, you can integrate your tests in all the sprints easily.
I won’t be wrong if I say that this particular factor of designing the Framework should be the most important
aspect of estimation. If needed (like in complex application) this factor should be again broken down into a
separate WBS and estimation should be done.
294
#5 Learning & Training
Learning Selenium is a bit different than learning any other automation tool. It basically involves learning a
programming language than just a scripting language (though script language helps while building a framework
, like you want to write a script that would invoke your automated scripts after doing the environment setting
changes).
In case we are combining WebDriver with java, I would say that if one is well versed with core java, they are in
a very good shape to start with selenium automation.
Along with learning java, provisions should be there to learn other technologies like ANT / Maven( for
building), TestNG/jUnit ( unit test framework), Log4J( for Logging), reporting ( for reporting) etc. this list may
grow based on the level of framework. The more this list grows, the more time it would take.
------------
If the management has decided to go with selenium, these learning activities can be done parallel with the
planning activity. Because there is no limit to learn these technologies, it is suggested to have a definite plan
(syllabus) ready for the team so that they can initiated their learning process in a definite direction and
everybody is in the same page.
Practically speaking, we testers do not have a very much keen in learning a full-fledged programming language
and we feel this is developers piece of cake. But now we have to change this mentality and should consider
learning the programming language to be equally important as learning new testing process. This will not only
increase tester’s knowledge about the language and automation but also will give a chance to understand how
the application works internally which may increase their scope to find new bugs.
#6 Environment setup
Environment set up deals with (not limited to):-
295
1. Candidate test cases should be handy
2. Framework is ready
Identify different actions that your web application does. It can be simple actions like navigation, clicking,
entering text; or a complex action like connect to database, handle flash or Ajax. Take one test case at a time,
and identify what all action that particular test case does and estimate hours accordingly for per test case. The
sum of all the hours for the entire test suite will give you the exact number.
Provision should be there for Review as well. The reviews are simple the code review which can be done either
by peer or a developer. Pair programming is the best option which is quick, but if it is not possible, based on the
available resources or organizations review strategy, hours should be allocated for it.
Remarks: Recommended – A test case can have multiple check point but only 1 verification point. If a test case
has more than 1 verification point, it should be bifurcated into a separate test case.
Factor #3: Supporting tools
Meaning: Selenium itself is not strong enough to build a complex framework. It requires a list of third party
tools for building a framework.
Steps Involved:
1. Finalized IDE
296
2. Finalized unit test tool
3. Finalized logger
4. Finalized reporting tool
5. Finalized build tool
Deliverable: List of tools needed to create the framework.
Remarks:
Examples:
297
Remarks: We should try to build our framework in such a way that with least hassle, our code is deployed in to
the said environment / box.
I should not be wrong if I say that with minimal entries into our text files (which have the url and credentials)
our code should be ready to run and ROCK!
Factor #6: Learning & training
Meaning: Learning a programming language and other supporting technologies
Steps Involved: Prepare a plan as per your automation needs and share it with the team and encourage them to
learn and proceed as per the syllabus.
Deliverable: Training Plan and its tracker which will track the progress of the team.
Remarks: Emphasis should be on building logics rather learning syntax.
Factor #7: Coding / scripting and Review
Meaning: Writing the actual test scripts and reviewing them
Steps Involved:
1. Test cases and framework is ready.
2. Take / divide the test cases and convert it into automated scripts and track your progress
Deliverable: Automated test scripts
Remarks: Whole team should participate in writing the test scripts using the implemented framework. So while
estimating, efforts from the whole team should be taken into consideration.
Conclusion:
Having said about all these points, do not forget to include Management overhead and some buffer time in your
final Selenium automation estimation. The best and the proven way to do any estimation is to follow the WBS
(Work Break down Structure) mechanism. This is straight forward and serves the purpose of implementing the
automation estimation needs.
The factors mentioned above are the ones based on my experience, but there can be other entities as well which
might affect the strategy.
The thumb rule here is “Identify certain criteria, divide your modules or test case on those criteria; and
scale it”. Based on your scaled figure – you can come to an accurate estimation.
Next Tutorial #33: We will be concluding our most comprehensive Selenium online training free tutorials
series with last tutorial i.e. “Selenium testing interview questions with answers”.
Let us know if you have any other tips for effort estimation of Selenium projects.
298
Tutorial #33 – Selenium Interview Questions and Answers
In this tutorial, we have listed the 50 most popularly asked Selenium interview questions including
Selenium WebDriver interview questions.
A quick note about this Selenium article series before we move to this last tutorial:
This is the last tutorial in our Selenium online training series of 30+ comprehensive tutorials. I hope you all
enjoyed these tutorials and started learning from it. If you are new here please head over to this very first
tutorial in this training series.
299
7. supports distributed testing
Q #4) What is Selenium? What are the different Selenium components?
Selenium is one of the most popular automated testing suites. Selenium is designed in a way to support and
encourage automation testing of functional aspects of web based applications and a wide range of browsers and
platforms. Due to its existence in the open source community, it has become one of the most accepted tools
amongst the testing professionals.
Selenium is not just a single tool or a utility, rather a package of several testing tools and for the same reason it
is referred to as a Suite. Each of these tools is designed to cater different testing and test environment
requirements.
Selenium Integrated Development Environment (IDE) – Selenium IDE is a record and playback tool.
It is distributed as a Firefox Plugin.
Selenium Remote Control (RC) – Selenium RC is a server that allows user to create test scripts in a
desired programming language. It also allows executing test scripts within the large spectrum of
browsers.
Selenium WebDriver – WebDriver is a different tool altogether that has various advantages over
Selenium RC. WebDriver directly communicates with the web browser and uses its native compatibility
to automate.
Selenium Grid – Selenium Grid is used to distribute your test execution on multiple platforms and
environments concurrently.
Q #5) What are the testing types that can be supported by Selenium?
Selenium supports the following types of testing:
1. Functional Testing
2. Regression Testing
Q #6) What are the limitations of Selenium?
Following are the limitations of Selenium:
301
Feature Selenium IDE Selenium RC WebDriver
302
Feature Selenium IDE Selenium RC WebDriver
communicates
with the
browser.
303
The fundamental behind locating elements using Xpath is the traversing between various elements across the
entire page and thus enabling a user to find an element with the reference of another element.
Origin is a sequential combination of scheme, host and port of the URL. For example, for a URL http://
http://www.softwaretestinghelp.com/resources/, the origin is a combination of http, softwaretestinghelp.com, 80
correspondingly.
Thus the Selenium Core (JavaScript Program) cannot access the elements from an origin that is different from
where it was launched. For Example, if I have launched the JavaScript Program from
“http://www.softwaretestinghelp.com”, then I would be able to access the pages within the same domain such as
“http://www.softwaretestinghelp.com/resources” or “http://www.softwaretestinghelp.com/istqb-free-updates/”.
The other domains like google.com, seleniumhq.org would no more be accessible.
So, In order to handle same origin policy, Selenium Remote Control was introduced.
Q #15) When should I use Selenium Grid?
Selenium Grid can be used to execute same or different test scripts on multiple platforms and browsers
concurrently so as to achieve distributed test execution, testing under different environments and saving
execution time remarkably.
Q #16) What do we mean by Selenium 1 and Selenium 2?
Selenium RC and WebDriver, in a combination are popularly known as Selenium 2. Selenium RC alone is also
referred as Selenium 1.
Q #17) Which is the latest Selenium tool?
WebDriver
304
WebDriver driver = new ChromeDriver();
WebDriver driver = new InternetExplorerDriver();
Q #19) What are the different types of Drivers available in WebDriver?
The different drivers available in WebDriver are:
FirefoxDriver
InternetExplorerDriver
ChromeDriver
SafariDriver
OperaDriver
AndroidDriver
IPhoneDriver
HtmlUnitDriver
Q #20) What are the different types of waits available in WebDriver?
There are two types of waits available in WebDriver:
1. Implicit Wait
2. Explicit Wait
Implicit Wait: Implicit waits are used to provide a default waiting time (say 30 seconds) between each
consecutive test step/command across the entire test script. Thus, subsequent test step would only execute when
the 30 seconds have elapsed after executing the previous test step/command.
Explicit Wait: Explicit waits are used to halt the execution till the time a particular condition is met or the
maximum time has elapsed. Unlike Implicit waits, explicit waits are applied for a particular instance only.
Q #21) How to type in a textbox using Selenium?
User can use sendKeys(“String to be entered”) to enter the string in the textbox.
Syntax:
WebElement username = drv.findElement(By.id(“Email”));
// entering username
username.sendKeys(“sth”);
Q #22) How can you find if an element in displayed on the screen?
WebDriver facilitates the user with the following methods to check the visibility of the web elements. These
web elements can be buttons, drop boxes, checkboxes, radio buttons, labels etc.
1. isDisplayed()
2. isSelected()
3. isEnabled()
Syntax:
305
isDisplayed():
boolean buttonPresence = driver.findElement(By.id(“gbqfba”)).isDisplayed();
isSelected():
boolean buttonSelected = driver.findElement(By.id(“gbqfba”)).isDisplayed();
isEnabled():
boolean searchIconEnabled = driver.findElement(By.id(“gbqfb”)).isEnabled();
Q #23) How can we get a text of a web element?
Get command is used to retrieve the inner text of the specified web element. The command doesn’t require any
parameter but returns a string value. It is also one of the extensively used commands for verification of
messages, labels, errors etc displayed on the web pages.
Syntax:
String Text = driver.findElement(By.id(“Text”)).getText();
Q #24) How to select value in a dropdown?
Value in the drop down can be selected using WebDriver’s Select class.
Syntax:
selectByValue:
Select selectByValue = new Select(driver.findElement(By.id(“SelectID_One”)));
selectByValue.selectByValue(“greenvalue”);
selectByVisibleText:
Select selectByVisibleText = new Select (driver.findElement(By.id(“SelectID_Two”)));
selectByVisibleText.selectByVisibleText(“Lime”);
selectByIndex:
Select selectByIndex = new Select(driver.findElement(By.id(“SelectID_Three”)));
selectByIndex.selectByIndex(2);
Q #25) What are the different types of navigation commands?
Following are the navigation commands:
navigate().back() – The above command requires no parameters and takes back the user to the previous
webpage in the web browser’s history.
Sample code:
driver.navigate().back();
navigate().forward() – This command lets the user to navigate to the next web page with reference to the
browser’s history.
Sample code:
driver.navigate().forward();
306
navigate().refresh() – This command lets the user to refresh the current web page there by reloading all the
web elements.
Sample code:
driver.navigate().refresh();
navigate().to() – This command lets the user to launch a new web browser window and navigate to the
specified URL.
Sample code:
driver.navigate().to(“https://google.com”);
Q #26) How to click on a hyper link using linkText?
driver.findElement(By.linkText(“Google”)).click();
The command finds the element using link text and then click on that element and thus the user would be re-
directed to the corresponding page.
The above mentioned link can also be accessed by using the following command.
------------
driver.findElement(By.partialLinkText(“Goo”)).click();
The above command find the element based on the substring of the link provided in the parenthesis and thus
partialLinkText() finds the web element with the specified substring and then clicks on it.
Select iframe by id
driver.switchTo().frame(“ID of the frame“);
Locating iframe using tagName
driver.switchTo().frame(driver.findElements(By.tagName(“iframe”).get(0));
Locating iframe using index
frame(index)
driver.switchTo().frame(0);
frame(Name of Frame)
driver.switchTo().frame(“name of the frame”);
frame(WebElement element)
Select Parent Window
driver.switchTo().defaultContent();
Q #28) When do we use findElement() and findElements()?
307
findElement(): findElement() is used to find the first element in the current web page matching to the specified
locator value. Take a note that only first matching element would be fetched.
Syntax:
WebElement element = driver.findElements(By.xpath(“//div[@id=’example’]//ul//li”));
findElements(): findElements() is used to find all the elements in the current web page matching to the
specified locator value. Take a note that all the matching elements would be fetched and stored in the list of
WebElements.
Syntax:
List <WebElement> elementList = driver.findElements(By.xpath(“//div[@id=’example’]//ul//li”));
Q #29) How to find more than one web element in the list?
At times, we may come across elements of same type like multiple hyperlinks, images etc arranged in an
ordered or unordered list. Thus, it makes absolute sense to deal with such elements by a single piece of code and
this can be done using WebElement List.
Sample Code
1 // Storing the list
2 List <WebElement> elementList = driver.findElements(By.xpath("//div[@id='example']//ul//li"));
3 // Fetching the size of the list
4 int listSize = elementList.size();
5 for (int i=0; i<listSize; i++)
6{
7 // Clicking on each service provider link
8 serviceProviderLinks.get(i).click();
9 // Navigating back to the previous page that stores link to service providers
10 driver.navigate().back();
11 }
Q #30) What is the difference between driver.close() and driver.quit command?
close(): WebDriver’s close() method closes the web browser window that the user is currently working on or we
can also say the window that is being currently accessed by the WebDriver. The command neither requires any
parameter nor does is return any value.
quit(): Unlike close() method, quit() method closes down all the windows that the program has opened. Same as
close() method, the command neither requires any parameter nor does is return any value.
Q #31) Can Selenium handle windows based pop up?
Selenium is an automation testing tool which supports only web application testing. Therefore, windows pop up
cannot be handled using Selenium.
308
WebDriver offers the users with a very efficient way to handle these pop ups using Alert interface. There are the
four methods that we would be using along with the Alert interface.
void dismiss() – The accept() method clicks on the “Cancel” button as soon as the pop up window
appears.
void accept() – The accept() method clicks on the “Ok” button as soon as the pop up window appears.
String getText() – The getText() method returns the text displayed on the alert box.
void sendKeys(String stringToSend) – The sendKeys() method enters the specified string pattern into
the alert box.
Syntax:
// accepting javascript alert
Alert alert = driver.switchTo().alert();
alert.accept();
Q #33) How can we handle windows based pop up?
Selenium is an automation testing tool which supports only web application testing, that means, it doesn’t
support testing of windows based applications. However Selenium alone can’t help the situation but along with
some third party intervention, this problem can be overcome. There are several third party tools available for
handling window based pop ups along with the selenium like AutoIT, Robot class etc.
Thus, In the following scenario, we have used Action Interface to mouse hover on a drop down which then
opens a list of options.
Sample Code:
1 // Instantiating Action Interface
2 Actions actions=new Actions(driver);
3 // howering on the dropdown
4 actions.moveToElement(driver.findElement(By.id("id of the dropdown"))).perform();
5 // Clicking on one of the items in the list options
6 WebElement subLinkOption=driver.findElement(By.id("id of the sub link"));
7 subLinkOption.click();
309
Syntax:
driver.findElement(By.id(“id“)).getCssValue(“name of css attribute”);
driver.findElement(By.id(“id“)).getCssValue(“font-size”);
Q #37) How to capture screenshot in WebDriver?
1 import org.junit.After;
2 import org.junit.Before;
3 import org.junit.Test;
4 import java.io.File;
5 import java.io.IOException;
6 import org.apache.commons.io.FileUtils;
7 import org.openqa.selenium.OutputType;
8 import org.openqa.selenium.TakesScreenshot;
9 import org.openqa.selenium.WebDriver;
10 import org.openqa.selenium.firefox.FirefoxDriver;
11
12 public class CaptureScreenshot {
13 WebDriver driver;
14 @Before
15 public void setUp() throws Exception {
16 driver = new FirefoxDriver();
17 driver.get("https://google.com");
18 }
19 @After
20 public void tearDown() throws Exception {
21 driver.quit();
22 }
23
24 @Test
public void test() throws IOException
25
{
26 // Code to capture the screenshot
27 File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
28 // Code to copy the screenshot in the desired location
29 FileUtils.copyFile(scrFile, newFile("C:\\CaptureScreenshot\\google.jpg"));
30 }
31 }
@Test: Annotation lets the system know that the method annotated as @Test is a test method. There
can be multiple test methods in a single test script.
310
@Before: Method annotated as @Before lets the system know that this method shall be executed every
time before each of the test method.
@After: Method annotated as @After lets the system know that this method shall be executed every
time after each of the test method.
@BeforeClass: Method annotated as @BeforeClass lets the system know that this method shall be
executed once before any of the test method.
@AfterClass: Method annotated as @AfterClass lets the system know that this method shall be
executed once after any of the test method.
@Ignore: Method annotated as @Ignore lets the system know that this method shall not be executed.
Q #40) What is TestNG and how is it better than Junit?
TestNG is an advance framework designed in a way to leverage the benefits by both the developers and testers.
With the commencement of the frameworks, JUnit gained an enormous popularity across the Java applications,
Java developers and Java testers with remarkably increasing the code quality. Despite being easy to use and
straightforward, JUnit has its own limitations which give rise to the need of bringing TestNG into the picture.
TestNG is an open source framework which is distributed under the Apache software License and is readily
available for download.
TestNG with WebDriver provides an efficient and effective test result format that can in turn be shared with the
stake holders to have a glimpse on the product’s/application’s health thereby eliminating the drawback of
WebDriver’s incapability to generate test reports. TestNG has an inbuilt exception handling mechanism which
lets the program to run without terminating unexpectedly.
There are various advantages that make TestNG superior to JUnit. Some of them are:
311
11 public void method3() {
12 }
13 }
312
5. Hybrid Testing Framework: Hybrid Testing Framework is a combination of more than one above
mentioned frameworks. The best thing about such a setup is that it leverages the benefits of all kinds of
associated frameworks.
6. Behavior Driven Development Framework: Behavior Driven Development framework allows
automation of functional validations in easily readable and understandable format to Business Analysts,
Developers, Testers, etc.
Q #45) How can I read test data from excels?
Test data can efficiently be read from excel using JXL or POI API. See detailed tutorial here.
Q #46) What is the difference between POI and jxl jar?
# JXL jar POI jar
1 JXL supports “.xls” format i.e. binary POI jar supports all of
based format. JXL doesn’t support these formats
Excel 2007 and “.xlsx” format i.e.
XML based format
2 JXL API was last updated in the year POI is regularly updated
2009 and released
4 JXL API doesn’t support rich text POI API supports rich
formatting text formatting
5 JXL API is faster than POI API POI API is slower than
JXL API
313
Quick Test
Feature Selenium
Professional (QTP)
Q #50) What is Object Repository? How can we create Object Repository in Selenium?
Object Repository is a term used to refer to the collection of web elements belonging to Application Under Test
(AUT) along with their locator values. Thus, whenever the element is required within the script, the locator
value can be populated from the Object Repository. Object Repository is used to store locators in a centralized
location instead of hard coding them within the scripts.
In Selenium, objects can be stored in an excel sheet which can be populated inside the script whenever required.
Hope in this article you will find answers to most frequently asked Selenium and WebDriver Interview
questions. The answers provided here are also helpful for understanding the Selenium basics and advanced
WebDriver topics.
314
Do you have any Selenium Interview questions that are not answered here? Please let us know in comments
below and we will try to answer all.
=> This finishes not just this article but our complete Selenium training series. Check list of ALL 30+
tutorials listed on this page. Please let us know your comments and questions.
**********************************
315
Source:
http://www.softwaretestinghelp.com/category/selenium-tutorials/
As of 2017 Feb 09
316