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

Functional

Automation Testing
Using Selenium
Introduction to Selenium
Table of Contents
Introducing Selenium ................................................................................................ 3
To Automate or Not to Automate? ........................................................................................................... 3
Test Automation for Web Applications ................................................................................................... 4
Introducing Selenium .............................................................................................................................. 5
Selenium Components ........................................................................................................................... 5
Supported ro!sers ............................................................................................................................... "
#le$ibilit% and &$tensibilit% ...................................................................................................................... '
Selenium Basics ........................................................................................................ 7
(etting Started ) C*oosing +our Selenium Tool .................................................................................... '
Introducing Selenium Commands .......................................................................................................... ,
Test Suites ........................................................................................................................................... --
Commonl% .sed Selenium Commands ................................................................................................ --
Selenium-IDE .......................................................................................................... 13
Introduction ........................................................................................................................................... -3
Installing t*e I/& .................................................................................................................................. -3
0pening t*e I/& ................................................................................................................................... -4
I/& #eatures ........................................................................................................................................ -5
1enu ar .......................................................................................................................................... -5
Toolbar .............................................................................................................................................. -5
Test Case 2ane ................................................................................................................................ -'
3og45eference4.I6&lement45ollup 2ane ........................................................................................... -'
uilding Test Cases ............................................................................................................................. -7
5ecording ......................................................................................................................................... -7
Adding 8erifications and Asserts Wit* t*e Conte$t 1enu ................................................................. -7
&diting ............................................................................................................................................... 9:
0pening and Sa;ing a Test Case ..................................................................................................... 9-
5unning Test Cases ............................................................................................................................. 9-
.sing ase .53 to 5un Test Cases in /ifferent /omains ................................................................... 99
/ebugging ............................................................................................................................................ 93
Writing a Test Suite .............................................................................................................................. 95
.ser &$tensions ................................................................................................................................... 9"
#ormat .................................................................................................................................................. 9'
&$ecuting Selenium6I/& Tests on /ifferent ro!sers ......................................................................... 9'
Selenium Commands .............................................................................................. 28
2
Introduction to Selenium
3ocating &lements ................................................................................................................................ 3:
Store Commands and Selenium 8ariables ........................................................................................... 34
Selenium-RC ........................................................................................................... 36
Introduction ........................................................................................................................................... 3"
<o! Selenium65C Wor=s ..................................................................................................................... 3"
Installation ............................................................................................................................................ 3,
#rom Selenese to a 2rogram ............................................................................................................... 37
2rogramming +our Test ....................................................................................................................... 4:
est Design Considerations ...................................................................................... !3
Introducing Test /esign ......................................................................................................................... 43
W*at to Test? ......................................................................................................................................... 43
Testing 3in=s ..................................................................................................................................... 43
#unction Tests .................................................................................................................................. 44
Introducing Selenium
To Automate or Not to Automate?
Is automation always advantageous? When should one decide to automate test cases?
3
Introduction to Selenium
It is not always advantageous to automate test cases. There are times when manual testing may
be more appropriate. For instance, if the applications user interface will change considerably in
the near future, then any automation would need to be rewritten. Also, sometimes there simply is
not enough time to build test automation. For the short term, manual testing may be more
effective. If an application has a very tight deadline, there is currently no test automation
available, and its imperative that the testing get done within that time frame, then manual testing
is the best solution.
owever, automation has specific advantages for improving the long!term efficiency of a
software teams testing processes. Test automation supports"
Fre#uent regression testing
$apid feedbac% to developers during the development process
&irtually unlimited iterations of test case e'ecution
(ustomi)ed reporting of application defects
*upport for Agile and e+treme development methodologies
,isciplined documentation of test cases
Finding defects missed by manual testing
Test Automation for Web Applications
-any, perhaps most, software applications today are written as web!based applications to be run
in an Internet browser. The effectiveness of testing these applications varies widely among
companies and organi)ations. In an era of continuously improving software processes, such as
e+treme programming .+/0 and Agile, it can be argued that disciplined testing and #uality
assurance practices are still underdeveloped in many organi)ations. *oftware testing is often
conducted manually. At times, this is effective1 however there are alternatives to manual testing
that many organi)ations are unaware of, or lac% the s%ills to perform. 2tili)ing these alternatives
would in most cases greatly improve the efficiency of their software development by adding
efficiencies to their testing.
Test automation is often the answer. Test automation means using a tool to run repeatable tests
against the target application whenever necessary.
There are many advantages to test automation. -ost are related to the repeatability of the tests
and the speed at which the tests can be e'ecuted. There are a number of commercial and open
source tools available for assisting with the development of test automation. *elenium is possibly
the most widely!used open source solution. This users guide will assist both new and
e'perienced *elenium users in learning effective techni#ues in building test automation for web
applications.
This guide introduces *elenium, teaches its most widely used features, and provides useful
advice in best practices accumulated from the *elenium community. -any e'amples are
provided. Also, technical information on the internal structure of *elenium and recommended
uses of *elenium are provided as contributed by a consortium of e'perienced *elenium users. It
is our hope that this guide will get additional new users e'cited about using *elenium for test
!
Introduction to Selenium
automation. We hope this guide will assist in 3getting the word out4 that #uality assurance and
software testing have many options beyond what is currently practiced. We hope this users
guide and *elenium itself provide a valuable aid to boosting the readers efficiency in his or her
software testing processes.
Introducing Selenium
*elenium is a robust set of tools that supports rapid development of test automation for web!
based applications. *elenium provides a rich set of testing functions specifically geared to the
needs of testing of a web application. These operations are highly fle'ible, allowing many
options for locating 2I elements and comparing e'pected test results against actual application
behavior.
5ne of *eleniums %ey features is the support for e'ecuting ones tests on multiple browser
platforms.
Selenium Components
*elenium is composed of three ma6or tools. 7ach one has a specific role in aiding the
development of web application test automation.
Selenium-IDE
*elenium!I,7 is the Integrated ,evelopment 7nvironment for building *elenium test cases. It
operates as a Firefo' add!on and provides an easy!to!use interface for developing and running
individual test cases or entire test suites. *elenium!I,7 has a recording feature, which will %eep
account of user actions as they are performed and store them as a reusable script to play bac%. It
also has a conte't menu .right!clic%0 integrated with the Firefo' browser, which allows the user
to pic% from a list of assertions and verifications for the selected location. *elenium!I,7 also
offers full editing of test cases for more precision and control.
Although *elenium!I,7 is a Firefo' only add!on, tests created in it can also be run against other
browsers by using *elenium!$( and specifying the name of the test suite on the command line.
Selenium-RC Remote Control!
*elenium!$( allows the test automation developer to use a programming language for ma'imum
fle'ibility and e'tensibility in developing test logic. For instance, if the application under test
returns a result set, and if the automated test program needs to run tests on each element in the
result set, the programming languages iteration support can be used to iterate through the result
set, calling *elenium commands to run tests on each item.
*elenium!$( provides an A/I .Application /rogramming Interface0 and library for each of its
supported languages" T-8, 9ava, (:, /erl, //, /ython, and $uby. This ability to use
"
Introduction to Selenium
*elenium!$( with a high!level programming language to develop test cases also allows the
automated testing to be integrated with a pro6ects automated build environment.
Selenium-"rid
*elenium!;rid allows the *elenium!$( solution to scale for large test suites or test suites that
must be run in multiple environments. With *elenium!;rid, multiple instances of *elenium!$(
are running on various operating system and browser configurations1 7ach of these when
launching register with a hub. When tests are sent to the hub they are then redirected to an
available *elenium!$(, which will launch the browser and run the test. This allows for running
tests in parallel, with the entire test suite theoretically ta%ing only as long to run as the longest
individual test.
Supported #ro$sers
#ro$ser Selenium-IDE Selenium-RC %perating S&stems
Firefo' <.' $ecord and playbac% tests
*tart browser, run
tests
Windows, 8inu',
-ac
Firefo' < $ecord and playbac% tests
*tart browser, run
tests
Windows, 8inu',
-ac
Firefo' = $ecord and playbac% tests
*tart browser, run
tests
Windows, 8inu',
-ac
I7 > Test e'ecution only via *elenium!$(?
*tart browser, run
tests
Windows
I7 @ Test e'ecution only via *elenium!$(?
*tart browser, run
tests
Windows
I7 A Test e'ecution only via *elenium!$(?
*tart browser, run
tests
Windows
*afari B Test e'ecution only via *elenium!$(
*tart browser, run
tests
-ac
*afari < Test e'ecution only via *elenium!$(
*tart browser, run
tests
-ac
*afari = Test e'ecution only via *elenium!$(
*tart browser, run
tests
-ac
5pera CD Test e'ecution only via *elenium!$(
*tart browser, run
tests
Windows, 8inu',
-ac
5pera E Test e'ecution only via *elenium!$(
*tart browser, run
tests
Windows, 8inu',
-ac
5pera > Test e'ecution only via *elenium!$(
*tart browser, run
tests
Windows, 8inu',
-ac
;oogle Test e'ecution only via *elenium!$( *tart browser, run Windows
6
Introduction to Selenium
(hrome .Windows0 tests
5thers Test e'ecution only via *elenium!$(
/artial support
possible??
As applicable
? Tests developed on Firefo' via *elenium!I,7 can be e'ecuted on any other supported browser
via a simple *elenium!$( command line.
?? *elenium!$( server can start any e'ecutable, but depending on browser security settings
there may be technical limitations that would limit certain features.
'le(ibilit& and E(tensibilit&
Foull find that *elenium is highly fle'ible. There are multiple ways in which one can add
functionality to *eleniums framewor% to customi)e test automation for ones specific testing
needs. This is, perhaps, *eleniums strongest characteristic when compared with proprietary test
automation tools and other open source solutions. *elenium!$( support for multiple
programming and scripting languages allows the test writer to build any logic they need into
their automated testing and to use a preferred programming or scripting language of ones
choice.
*elenium!I,7 allows for the addition of user!defined 3user!e'tensions4 for creating additional
commands customi)ed to the users needs. Also, it is possible to re!configure how the *elenium!
I,7 generates its *elenium!$( code. This allows users to customi)e the generated code to fit in
with their own test framewor%s. Finally, *elenium is an 5pen *ource pro6ect where code can be
modified and enhancements can be submitted for contribution.
Selenium #asics
"etting Started ) C*oosing +our Selenium Tool
-ost people get started with *elenium!I,7. This is what we recommend. Its an easy way to get
familiar with *elenium commands #uic%ly. Fou can develop your first script in 6ust a few
minutes. *elenium!I,7 is also very easy to install. *ee the chapter on Selenium-IDE for
specifics.
Fou may also run your scripts from the *elenium!I,7. Its simple to use and is recommended
for less!technical users. The I,7 allows developing and running tests without the need for
programming s%ills as re#uired by *elenium!$(. The *elenium!I,7 can serve as an e'cellent
way to train 6unior!level employees in test automation. Anyone who understands how to conduct
7
Introduction to Selenium
manual testing of a website can easily transition to using the *elenium!I,7 for running and
developing tests.
*ome testing tas%s are too comple' though for the *elenium!I,7. When programming logic is
re#uired *elenium!$( must be used. For e'ample, any tests re#uiring iteration, such as testing
each element of a variable length list re#uires running the script from a programming language.
*elenium!I,7 does not support iteration or condition statements.
Finally, *elenium!(ore is another way of running tests. 5ne can run test scripts from a web!
browser using the T-8 interface TestRunner.html. This is the original method for running
*elenium commands. It has limitations though1 similar to *elenium!I,7, it does not support
iteration.
*elenium!(ore also cannot switch between http and https protocols. *ince the development of
*elenium!I,7 and *elenium!$(, more people are using these tools rather than *elenium!(ore.
At the time of writing .April DE0 it is still available and may be convenient for some. owever,
the *elenium community is encouraging the use of *elenium!I,7 and $( and discouraging the
use of *elenium!(ore. *upport for *elenium!(ore is becoming less available and it may even be
deprecated in a future release.
Introducing Selenium Commands
Selenium Commands ) Selenese
*elenium provides a rich set of commands for fully testing your web!app in virtually any way
you can imagine. The command set is often called selenese. These commands essentially create a
testing language.
In selenese, one can test the e'istence of 2I elements based on their T-8 tags, test for specific
content, test for bro%en lin%s, input fields, selection list options, submitting forms, and table data
among other things. In addition *elenium commands support testing of window si)e, mouse
position, alerts, A6a' functionality, pop up windows, event handling, and many other web!
application features. The (ommand $eference lists all the available commands.
A command is what tells *elenium what to do. *elenium commands come in three 3flavors4"
Actions, Accessors and Assertions.
Actions are commands that generally manipulate the state of the application. They do
things li%e 3clic% this lin%4 and 3select that option4. If an Action fails, or has an error, the
e'ecution of the current test is stopped.
-any Actions can be called with the 3AndWait4 suffi', e.g. 3clic%AndWait4. This suffi'
tells *elenium that the action will cause the browser to ma%e a call to the server, and that
*elenium should wait for a new page to load.
8
Introduction to Selenium
Accessors e'amine the state of the application and store the results in variables, e.g.
3storeTitle4. They are also used to automatically generate Assertions.
Assertions are li%e Accessors, but they verify that the state of the application conforms to
what is e'pected. 7'amples include 3ma%e sure the page title is +4 and 3verify that this
chec%bo' is chec%ed4.
All *elenium Assertions can be used in < modes" 3assert4, 3verify4, and 4 waitFor4. For
e'ample, you can 3assertTe't4, 3verifyTe't4 and 3waitForTe't4. When an 3assert4 fails,
the test is aborted. When a 3verify4 fails, the test will continue e'ecution, logging the
failure. This allows a single 3assert4 to ensure that the application is on the correct page,
followed by a bunch of 3verify4 assertions to test form field values, labels, etc.
3waitFor4 commands wait for some condition to become true .which can be useful for
testing A6a' applications0. They will succeed immediately if the condition is already true.
owever, they will fail and halt the test if the condition does not become true within the
current timeout setting .see the setTimeout action below0.
Script S&nta(
*elenium commands are simple, they consist of the command and two parameters. For e'ample"
verifyTe't GGdivGGaH=I 8ogin
The parameters are not always re#uired1 it depends on the command. In some cases both are
re#uired, in others one parameter is re#uired, and in still others the command may ta%e no
parameters at all. ere are a couple more e'amples"
goJac%AndWait
verifyTe't/resent Welcome to -y ome /age
type idKphone .LLL0 AAA!@DAA
type idKaddressC MNmy&ariableAddressO
The command reference describes the parameter re#uirements for each command.
/arameters vary, however they are typically"
a locator for identifying a 2I element within a page.
a text pattern for verifying or asserting e'pected page content
a text pattern or a selenium variable for entering te't in an input field or for selecting an
option from an option list.
8ocators, te't patterns, selenium variables, and the commands themselves are described in
considerable detail in the section on *elenium (ommands.
#
Introduction to Selenium
*elenium scripts that will be run from *elenium!I,7 will be be stored in an T-8 te't file
format. This consists of an T-8 table with three columns. The first column identifies the
*elenium command, the second is a target, and the final column contains a value. The second
and third columns may not re#uire values depending on the chosen *elenium command, but they
should be present. 7ach table row represents a new *elenium command. ere is an e'ample of a
test that opens a page, asserts the page title and then verifies some content on the page"
<table>
<tr><td>open</td><td></td><td>/download/</td></tr>
<tr><td>assertTitle</td><td></td><td>Downloads</td></tr>
<tr><td>verifyText</td><td>//h2</td><td>Downloads</td></tr>
</table>
$endered as a table in a browser this would loo% li%e the following"
open GdownloadG
assertTitle ,ownloads
verifyTe't GGh= ,ownloads
The *elenese T-8 synta' can be used to write and run tests without re#uiring %nowledge of a
programming language. With a basic %nowledge of selenese and *elenium!I,7 you can #uic%ly
produce and run test cases.
1$
Introduction to Selenium
Test Suites
A test suite is a collection of tests. 5ften one will run all the tests in a test suite as one continuous
batch!6ob.
When using *elenium!I,7, test suites also can be defined using a simple T-8 file. The synta'
again is simple. An T-8 table defines a list of tests where each row defines the filesystem path
to each test. An e'ample tells it all.
<html>
<head>
<title>Test Suite Function Tests - riority !</title>
</head>
<body>
<table>
<tr><td><b>Suite "f Tests</b></td></tr>
<tr><td><a href#$%/&o'in%html$>&o'in</a></td></tr>
<tr><td><a href#$%/Search(alues%html$>Test Searchin' for
(alues</a></td></tr>
<tr><td><a href#$%/Save(alues%html$>Test Save</a></td></tr>
</table>
</body>
</html>
A file similar to this would allow running the tests all at once, one after another, from the
*elenium!I,7.
Test suites can also be maintained when using *elenium!$(. This is done via programming and
can be done a number of ways. (ommonly 9unit is used to maintain a test suite if one is using
*elenium!$( with 9ava. Additionally, if (: is the chosen language, Punit could be employed. If
using an interpreted language li%e /ython with *elenium!$( than some simple programming
would be involved in setting up a test suite. *ince the whole reason for using *el!$( is to ma%e
use of programming logic for your testing this usually isnt a problem.
Commonl& ,sed Selenium Commands
To conclude our introduction of *elenium, well show you a few typical *elenium commands.
These are probably the most commonly used commands for building tests.
open
opens a page using a 2$8.
clic%Gclic%AndWait
performs a clic% operation, and optionally waits for a new page to load.
verifyTitleGassertTitle
verifies an e'pected page title.
verifyTe't/resent
verifies e'pected te't is somewhere on the page.
11
Introduction to Selenium
verify7lement/resent
verifies an e'pected 2I element, as defined by its T-8 tag, is present on the page.
verifyTe't
verifies e'pected te't and its corresponding T-8 tag are present on the page.
verifyTable
verifies a tables e'pected contents.
waitFor/ageTo8oad
pauses e'ecution until an e'pected new page loads. (alled automatically when
clic%AndWait is used.
waitFor7lement/resent
pauses e'ecution until an e'pected 2I element, as defined by its T-8 tag, is present on
the page.
12
Introduction to Selenium
Selenium-IDE
Introduction
The *elenium!I,7 .Integrated ,evelopment 7nvironment0 is the tool you use to develop your
*elenium test cases. Its an easy!to!use Firefo' plug!in and is generally the most efficient way to
develop test cases. It also contains a conte't menu that allows you to first select a 2I element
from the browsers currently displayed page and then select from a list of *elenium commands
with parameters pre!defined according to the conte't of the selected 2I element. This is not only
a time!saver, but also an e'cellent way of learning *elenium script synta'.
This chapter is all about the *elenium I,7 and how to use it effectively.
Installing t*e IDE
2sing Firefo', first, download the I,7.
When downloading from Firefo', youll be presented with the following window.
*elect Install Pow. The Firefo' Add!ons window pops up, first showing a progress bar, and
when the download is complete, displays the following.
13
Introduction to Selenium
$estart Firefo'. After Firefo' reboots you will find the *elenium!I,7 listed under the Firefo'
Tools menu.
%pening t*e IDE
1!
Introduction to Selenium
To run the *elenium!I,7, simply select it from the Firefo' Tools menu. It opens as follows with
an empty script!editing window and a menu for loading, or creating new test cases.
IDE 'eatures
-enu #ar
The File menu allows you to create, open, and save test case and test suite files. The 7dit menu
allows copy, paste, delete, undo, and select all operations for editing the commands in your test
case. The 5ptions menu allows the changing of settings. Fou can set the timeout value for
certain commands, add user!defined user e'tensions to the base set of *elenium commands, and
specify the format .language0 used when saving your test cases. The elp menu is the standard
Firefo' elp menu1 only one item on this menuQ2I!7lement ,ocumentationQpertains to
*elenium!I,7.
Toolbar
1"
Introduction to Selenium
The toolbar contains buttons for controlling the e'ecution of your test cases, including a step
feature for debugging your test cases. The right!most button, the one with the red!dot, is the
record button.
S%eed Control& controls 'o( )ast *our test case runs.
Run +ll& Runs t'e entire test suite ('en a test suite (it' multi%le test cases is
loaded.
Run& Runs t'e currentl* selected test. ,'en onl* a single test is loaded t'is
-utton and t'e Run +ll -utton 'a.e t'e same e))ect.
/ause0Resume& +llo(s sto%%ing and re-starting o) a running test case.
Ste%& +llo(s *ou to 1ste%2 t'roug' a test case -* running it one command at
a time. 3se )or de-ugging test cases.
estRunner 4ode& +llo(s *ou to run t'e test case in a -ro(ser loaded (it'
t'e Selenium-Core estRunner. 'e estRunner is not commonl* used no(
and is li5el* to -e de%recated. 'is -utton is )or e.aluating test cases )or
-ac5(ards com%ati-ilit* (it' t'e estRunner. 4ost users (ill %ro-a-l* not
need t'is -utton.
+%%l* Rollu% Rules& 'is ad.anced )eature allo(s re%etiti.e se6uences o)
Selenium commands to -e grou%ed into a single action. Detailed
documentation on rollu% rules can -e )ound in t'e 3I-Element Documentation
on t'e 7el% menu.
16
Introduction to Selenium
Record& Records t'e user8s -ro(ser actions.
Test Case .ane
Four script is displayed in the test case pane. It has two tabs, one for displaying the command
and their parameters in a readable 3table4 format.
The other tab ! *ource displays the test case in the native format in which the file will be stored.
Jy default, this is T-8 although it can be changed to a programming language such as 9ava or
(:, or a scripting language li%e /ython. *ee the 5ptions menu for details. The *ource view also
allows one to edit the test case in its raw form, including copy, cut and paste operations.
The (ommand, Target, and &alue entry fields display the currently selected command along
with its parameters. These are entry fields where you can modify the currently selected
command. The first parameter specified for a command in the $eference tab of the bottom pane
always goes in the Target field. If a second parameter is specified by the $eference tab, it always
goes in the &alue field.
If you start typing in the (ommand field, a drop!down list will be populated based on the first
characters you type1 you can then select your desired command from the drop!down.
/og0Reference0,I-Element0Rollup .ane
The bottom pane is used for four different functionsQ8og, $eference, 2I!7lement, and $ollupQ
depending on which tab is selected.
Log
17
Introduction to Selenium
When you run your test case, error messages and information messages showing the progress are
displayed in this pane automatically, even if you do not first select the 8og tab. These messages
are often useful for test case debugging. Potice the (lear button for clearing the 8og. Also notice
the Info button is a drop!down allowing selection of different levels of information to log.
Reference
The $eference tab is the default selection whenever you are entering or modifying *elenese
commands and parameters in Table mode. In Table mode, the $eference pane will display
documentation on the current command. When entering or modifying commands, whether from
Table or *ource mode, it is critically important to ensure that the parameters specified in the
Target and &alue fields match those specified in the parameter list in the $eference pane. The
number of parameters provided must match the number specified, the order of parameters
provided must match the order specified, and the type of parameters provided must match the
type specified. If there is a mismatch in any of these three areas, the command will not run
correctly.
While the $eference tab is invaluable as a #uic% reference, it is still often necessary to consult
the *elenium $eference document.
UI-Element and Rollup
,etailed information on these two panes .which cover advanced features0 can be found in the
2I!7lement ,ocumentation on the elp menu of *elenium!I,7.
18
Introduction to Selenium
#uilding Test Cases
There are three primary methods for developing test cases. Fre#uently, a test developer will
re#uire all three techni#ues.
Recording
-any first!time users begin by recording a test case from their interactions with a website. When
*elenium!I,7 is first opened, the record button is 5P by default.
Pote
This can be set to 5FF as a default with an available user e'tension.
,uring recording, *elenium!I,7 will automatically insert commands into your test case based
on your actions. Typically, this will include"
clic5ing a lin5 - click or clickAndWait commands
entering .alues - type command
selecting o%tions )rom a dro%-do(n list-o9 - select command
clic5ing c'ec5-o9es or radio -uttons - click command
ere are some 3gotchas4 to be aware of"
'e type command ma* re6uire clic5ing on some ot'er area o) t'e (e- %age
)or it to record.
:ollo(ing a lin5 usuall* records a click command. ;ou (ill o)ten need to
c'ange t'is to clickAndWait to ensure *our test case %auses until t'e ne(
%age is com%letel* loaded. <t'er(ise= *our test case (ill continue running
commands -e)ore t'e %age 'as loaded all its 3I elements. 'is (ill cause
une9%ected test case )ailures.
Adding 1erifications and Asserts Wit* t*e Conte(t -enu
Four test cases will also need to chec% the properties of a web!page. This re#uires assert and
verify commands. We wont describe the specifics of these commands here1 that is in the chapter
on Selenese Selenium Commands. ere well simply describe how to add them to your test
case.
With *elenium!I,7 recording, go to the browser displaying your test application and right clic%
anywhere on the page. Fou will see a conte't menu showing verify andGor assert commands.
The first time you use *elenium, there may only be one *elenium command listed. As you use
the I,7 however, you will find additional commands will #uic%ly be added to this menu.
*elenium!I,7 will attempt to predict what command, along with the parameters, you will need
for a selected 2I element on the current web!page.
1#
Introduction to Selenium
8ets see how this wor%s. 5pen a web!page of your choosing and select a bloc% of te't on the
page. A paragraph or a heading will wor% fine. Pow, right!clic% the selected te't. The conte't
menu should give you a verifyTextresent command and the suggested parameter should be the
te't itself.
Also, notice the *how All Available (ommands menu option. This shows many, many more
commands, again, along with suggested parameters, for testing your currently selected 2I
element.
Try a few more 2I elements. Try right!clic%ing an image, or a user control li%e a button or a
chec%bo'. Fou may need to use *how All Available (ommands to see options other than
verifyTextresent. 5nce you select these other options, the more commonly used ones will show
up on the primary conte't menu. For e'ample, selecting verifyElementresent for an image
should later cause that command to be available on the primary conte't menu the ne't time you
select an image and right!clic%.
Again, these commands will be e'plained in detail in the chapter on *elenium commands. For
now though, feel free to use the I,7 to record and select commands into a test case and then run
it. Fou can learn a lot about the *elenium commands simply by e'perimenting though the I,7.
Editing
Insert Command
Table Vie
*elect the point in your test case where you want to insert the command. To do this, in the Test
(ase /ane, left!clic% on the line where you want to insert a new command. $ight!clic% and select
Insert (ommand1 the I,7 will add a blan% line 6ust ahead of the line you selected. Pow use the
command editing te't fields to enter your new command and its parameters.
Source Vie
*elect the point in your test case where you want to insert the command. To do this, in the Test
(ase /ane, left!clic% between the commands where you want to insert a new command, and
enter the T-8 tags needed to create a <!column row containing the (ommand, first parameter
.if one is re#uired by the (ommand0, and second parameter .again, if one is re#uired0. Je sure to
save your test before switching bac% to Table view.
Insert Comment
(omments may be added to ma%e your test case more readable. These comments are ignored
when the test case is run.
2$
Introduction to Selenium
(omments may also be used to add vertical white space .one or more blan% lines0 in your tests1
6ust create empty comments. An empty command will cause an error during e'ecution1 an empty
comment wont.
Table Vie
*elect the line in your test case where you want to insert the comment. $ight!clic% and select
Insert (omment. Pow use the (ommand field to enter the comment. Four comment will appear
in purple font.
Source Vie
*elect the point in your test case where you want to insert the comment. Add an T-8!style
comment, i.e., !"# your comment here #$.
Edit a Command or Comment
Table Vie
*imply select the line to be changed and edit it using the (ommand, Target, and &alue fields.
Source Vie
*ince *ource view provides the e#uivalent of a WF*IWF; editor, simply modify which line
you wishQcommand, parameter, or comment.
%pening and Sa2ing a Test Case
The FileKR5pen, *ave and *ave As menu commands behave similarly to opening and saving
files in most other programs. When you open an e'isting test case, *elenium!I,7 displays its
*elenium commands in the Test (ase /ane.
Test suite files can also be opened and saved via the File menu. owever, such operations have
their own menu entries near the bottom1 the 5pen, *ave, and *ave As items are only for files.
Pote
At the time of this writing, theres a bug, where at times, when the I,7 is first opened and then
you select FileKR5pen, nothing happens. If you see this, close down the I,7 and restart it .you
dont need to close the browser itself0. This will fi' the problem.
Running Test Cases
21
Introduction to Selenium
The I,7 allows many options for running your test case. Fou can run a test case all at once, stop
and start it, run it one line at a time, run a single command you are currently developing, and you
can do a batch run of an entire test suite. 7'ecution of test cases is very fle'ible in the I,7.
Run a est Case
Clic5 t'e Run -utton to run t'e currentl* dis%la*ed test case.
Run a est Suite
Clic5 t'e Run +ll -utton to run all t'e test cases in t'e currentl* loaded test
suite.
Sto% and Start
'e /ause -utton can -e used to sto% t'e test case ('ile it is running. 'e
icon o) t'is -utton t'en c'anges to indicate t'e Resume -utton. o continue
clic5 Resume.
Sto% in t'e 4iddle
;ou can set a -rea5%oint in t'e test case to cause it to sto% on a %articular
command. 'is is use)ul )or de-ugging *our test case. o set a -rea5%oint=
select a command= rig't-clic5= and )rom t'e conte9t menu select oggle
Brea5%oint.
Start )rom t'e 4iddle
;ou can tell t'e IDE to -egin running )rom a s%eci)ic command in t'e middle
o) t'e test case. 'is also is used )or de-ugging. o set a start%oint= select a
command= rig't-clic5= and )rom t'e conte9t menu select Set0Clear Start /oint.
Run +n* Single Command
Dou-le-clic5 an* single command to run it -* itsel). 'is is use)ul ('en
(riting a single command. It lets *ou immediatel* test a command *ou are
constructing= ('en *ou are not sure i) it is correct. ;ou can dou-le-clic5 it to
see i) it runs correctl*. 'is is also a.aila-le )rom t'e conte9t menu.
,sing #ase ,R/ to Run Test Cases in Different Domains
The %ase &R' field at the top of the *elenium!I,7 window is very useful for allowing test cases
to be run across different domains. *uppose that a site named http"GGnews.portal.com had an in!
house beta site named http"GGbeta.news.portal.com. Any test cases for these sites that begin with
an open statement should specify a relative &R' as the argument to open rather than an a(solute
&R' .one starting with a protocol such as http" or https"0. *elenium!I,7 will then create an
22
Introduction to Selenium
absolute 2$8 by appending the open commands argument onto the end of the value of Jase
2$8. For e'ample, the test case below would be run against http"GGnews.portal.comGabout.html"
This same test case with a modified Jase 2$8 setting would be run against
http"GGbeta.news.portal.comGabout.html"
Debugging
,ebugging means finding and fi'ing errors in your test case. This is a normal part of test case
development.
We wont teach debugging here as most new users to *elenium will already have some basic
e'perience with debugging. If this is new to you, we recommend you as% one of the developers
in your organi)ation.
!rea"points and Startpoints
The *el!I,7 supports the setting of brea%points and the ability to start and stop the running of a
test case, from any point within the test case. That is, one can run up to a specific command in
the middle of the test case and inspect how the test case behaves at that point. To do this, set a
brea%point on the command 6ust before the one to be e'amined.
To set a brea%point, select a command, right!clic%, and from the conte't menu select To))le
%rea*point. Then clic% the $un button to run your test case from the beginning up to the
brea%point.
23
Introduction to Selenium
It is also sometimes useful to run a test case from somewhere in the middle to the end of the test
case or up to a brea%point that follows the starting point. For e'ample, suppose your test case
first logs into the website and then performs a series of tests and you are trying to debug one of
those tests. owever, you only need to login once, but you need to %eep rerunning your tests as
you are developing them. Fou can login once, then run your test case from a startpoint placed
after the login portion of your test case. That will prevent you from having to manually logout
each time you rerun your test case.
To set a startpoint, select a command, right!clic%, and from the conte't menu select Set+Clear
Start oint. Then clic% the $un button to e'ecute the test case beginning at that startpoint.
Stepping T#roug# a Testcase
To e'ecute a test case one command at a time .3step through4 it0, follow these steps"
1. Start t'e test case running (it' t'e Run -utton )rom t'e tool-ar.
2. Immediatel* %ause t'e e9ecuting test case (it' t'e /ause -utton.
3. Re%eatedl* select t'e Ste% -utton.
Find !utton
The Find button is used to see which 2I element on the currently displayed webpage .in the
browser0 is used in the currently selected *elenium command. This is useful when building a
locator for a commands first parameter .see the section on locators in the *elenium (ommands
chapter0. It can be used with any command that identifies a 2I element on a webpage, i.e. clic*,
clic*,nd-ait, type, and certain assert and verify commands, among others.
From Table view, select any command that has a locator parameter. (lic% the Find button. Pow
loo% on the webpage" There should be a bright green rectangle enclosing the element specified
by the locator parameter.
$age Source for %ebugging
5ften, when debugging a test case, you simply must loo% at the page source .the T-8 for the
webpage youre trying to test0 to determine a problem. Firefo' ma%es this easy. *imply right!
clic% the webpage and select S&iew!R/age *ource. The T-8 opens in a separate window. 2se
its *earch feature .7ditKRFind0 to search for a %eyword to find the T-8 for the 2I element
youre trying to test.
2!
Introduction to Selenium
Alternatively, select 6ust that portion of the webpage for which you want to see the source. Then
right!clic% the webpage and select &iew *election *ource. In this case, the separate T-8
window will contain 6ust a small amount of source, with highlighting on the portion representing
your selection.
Locator Assistance
Whenever *elenium!I,7 records a locator!type argument, it stores additional information which
allows the user to view other possible locator!type arguments that could be used instead. This
feature can be very useful for learning more about locators, and is often needed to help one build
a different type of locator than the type that was recorded.
This locator assistance is presented on the *elenium!I,7 window as a drop!down list accessible
at the right end of the Target field .only when the Target field contains a recorded locator!type
argument0. Jelow is a snapshot showing the contents of this drop!down for one command. Pote
that the first column of the drop!down provides alternative locators, whereas the second column
indicates the type of each alternative.
Writing a Test Suite
A test suite is a collection of test cases which is displayed in the leftmost pane in the I,7. The
test suite pane can be manually opened or closed via selecting a small dot halfway down the right
edge of the pane .which is the left edge of the entire *elenium!I,7 window if the pane is
closed0.
2"
Introduction to Selenium
The test suite pane will be automatically opened when an e'isting test suite is opened or when
the user selects the Pew Test (ase item from the File menu. In the latter case, the new test case
will appear immediately below the previous test case.
*elenium!I,7 does not yet support loading pre!e'isting test cases into a test suite. 2sers who
want to create or modify a test suite by adding pre!e'isting test cases must manually edit a test
suite file.
A test suite file is an T-8 file containing a one!column table. 7ach cell of each row in the
TtbodyR section contains a lin% to a test case. The e'ample below is of a test suite containing
four test cases"
<html>
<head>
<meta http-e)uiv#$*ontent-Type$ content#$text/html+ charset#,TF--$>
<title>Sample Selenium Test Suite</title>
</head>
<body>
<table cellpaddin'#$!$ cellspacin'#$!$ border#$!$>
<thead>
<tr><td>Test *ases for De .n/a .-0 Directory &in1s</td></tr>
</thead>
<tbody>
<tr><td><a href#$%/a%html$>. &in1s</a></td></tr>
<tr><td><a href#$%/b%html$>2 &in1s</a></td></tr>
<tr><td><a href#$%/c%html$>* &in1s</a></td></tr>
<tr><td><a href#$%/d%html$>D &in1s</a></td></tr>
</tbody>
</table>
</body>
</html>
Pote
Test case files should not have to be co!located with the test suite file that invo%es them. And on
-ac 5* and 8inu' systems, that is indeed the case. owever, at the time of this writing, a bug
prevents Windows users from being able to place the test cases elsewhere than with the test suite
that invo%es them.
,ser E(tensions
2ser e'tensions are 9ava*cript files that allow one to create his or her own customi)ations and
features to add additional functionality. 5ften this is in the form of customi)ed commands
although this e'tensibility is not limited to additional commands.
There are a number of useful e'tensions created by users.
/erhaps the most popular of all *elenium!I,7 e'tensions is one which provides flow control in
the form of while loops and primitive conditionals. This e'tension is the gotoUselUide.6s. For an
26
Introduction to Selenium
e'ample of how to use the functionality provided by this e'tension, loo% at the page created by
its author.
To install this e'tension, put the pathname to its location on your computer in the Selenium
Core e(tensions field of *elenium!I,7s 5ptionsKR5ptionsKR;eneral tab.
After selecting the %3 button, you must close and reopen *elenium!I,7 in order for the
e'tensions file to be read. Any change you ma%e to an e'tension will also re#uire you to close
and reopen *elenium!I,7.
Information on writing your own e'tensions can be found near the bottom of the *elenium
$eference document.
'ormat
Format, under the 5ptions menu, allows you to select a language for saving and displaying the
test case. The default is T-8.
If you will be using *elenium!$( to run your test cases, this feature is used to translate your test
case into a programming language. *elect the language, i.e. 9ava, //, you will be using with
*elenium!$( for developing your test programs. Then simply save the test case using
FileKR*ave. Four test case will be translated into a series of functions in the language you
choose. 7ssentially, program code supporting your test is generated for you by *elenium!I,7.
Also, note that if the generated code does not suit your needs, you can alter it by editing a
configuration file which defines the generation process. 7ach supported language has
configuration settings which are editable. This is under the 5ptionsKR5ptionsKRFormat tab.
Pote
At the time of this writing, this feature is not yet supported by the *elenium developers. owever
the author has altered the (: format in a limited manner and it has wor%ed well.
E(ecuting Selenium-IDE Tests on Different #ro$sers
27
Introduction to Selenium
While *elenium!I,7 can only run tests against Firefo', tests developed with *elenium!I,7 can
be run against other browsers, using a simple command!line interface that invo%es the *elenium!
$( server. This topic is covered in the Run Selenese tests section on *elenium!$( chapter. The
-htmlSuite command!line option is the particular feature of interest.
Selenium Commands
*elenium commands, often called selenese, are the set of commands that run your tests. A
se#uence of these commands is a test script. ere we e'plain those commands in detail, and we
present the many choices you have in testing your web application when using *elenium.
1erif&ing .age Elements
&erifying 2I elements on a web page is probably the most common feature of your automated
tests. *elenese allows multiple ways of chec%ing for 2I elements. It is important that you
understand these different methods because these methods define what you are actually testing.
For e'ample, will you test that...
C. an element is present somewhere on the page?
=. specific te't is somewhere on the page?
<. specific te't is at a specific location on the page?
For e'ample, if you are testing a te't heading, the te't and its position at the top of the page are
probably relevant for your test. If, however, you are testing for the e'istence of an image on the
home page, and the web designers fre#uently change the specific image file along with its
position on the page, then you only want to test that an ima)e .as opposed to the specific image
file0 e'ists some.here on the pa)e.
Assertion or 1erification?
(hoosing between 3assert4 and 3verify4 comes down to convenience and management of
failures. Theres very little point chec%ing that the first paragraph on the page is the correct one if
your test has already failed when chec%ing that the browser is displaying the e'pected page. If
youre not on the correct page, youll probably want to abort your test case so that you can
investigate the cause and fi' the issue.s0 promptly. 5n the other hand, you may want to chec%
many attributes of a page without aborting the test case on the first failure as this will allow you
to review all failures on the page and ta%e the appropriate action. 7ffectively an 3assert4 will fail
the test and abort the current test case, whereas a 3verify4 will fail the test and continue to run the
test case.
The best use of this feature is to logically group your test commands, and start each group with
an 3assert4 followed by one or more 3verify4 test commands. An e'ample follows"
28
Introduction to Selenium
Command Target 1alue
open GdownloadG
assertTitle ,ownloads
verifyTe't GGh= ,ownloads
assertTable C.=.C *elenium I,7
verifyTable C.=.= 9une <, =DD>
verifyTable C.=.< C.D beta =
The above e'ample first opens a page and then 3asserts4 that the correct page is loaded by
comparing the title with the e'pected value. 5nly if this passes will the following command run
and 3verify4 that the te't is present in the e'pected location. The test case then 3asserts4 the first
column in the second row of the first table contains the e'pected value, and only if this passed
will the remaining cells in that row be 3verified4.
2erif&Te(t.resent
The command verifyTextresent is used to verify specific text exists some.here on the pa)e.
It ta%es a single argumentQthe te't pattern to be verified. For e'ample"
Command Target 1alue
verifyTe't/resent -ar%eting Analysis
This would cause *elenium to search for, and verify, that the te't string 3-ar%eting Analysis4
appears somewhere on the page currently being tested. 2se verifyTextresent when you are
interested in only the te't itself being present on the page. ,o not use this when you also need to
test where the te't occurs on the page.
2erif&Element.resent
2se this command when you must test for the presence of a specific 2I element, rather then its
content. This verification does not chec% the te't, only the T-8 tag. 5ne common use is to
chec% for the presence of an image.
Command Target 1alue
verify7lement/resent GGdivGpGimg
This command verifies that an image, specified by the e'istence of an TimgR T-8 tag, is
present on the page, and that it follows a TdivR tag and a TpR tag. The first .and only0 parameter
is a locator for telling the *elenese command how to find the element. 8ocators are e'plained in
the ne't section.
2#
Introduction to Selenium
verify3lementresent can be used to chec% the e'istence of any T-8 tag within the page.
Fou can chec% the e'istence of lin%s, paragraphs, divisions TdivR, etc. ere are a few more
e'amples.
Command Target 1alue
verify7lement/resent GGdivGp
verify7lement/resent GGdivGa
verify7lement/resent idK8ogin
verify7lement/resent lin%K;o to -ar%eting $esearch
verify7lement/resent GGaH=I
verify7lement/resent GGheadGtitle
These e'amples illustrate the variety of ways a 2I element may be tested. Again, locators are
e'plained in the ne't section.
2erif&Te(t
2se verifyText when both the te't and its 2I element must be tested. verifyText must use a
locator. If you choose an /ath or D01 locator, you can verify that specific te't appears at a
specific location on the page relative to other 2I components on the page.
Command Target 1alue
verifyTe't GGtableGtrGtdGdivGp This is my te't and it occurs right after the div inside the table.
/ocating Elements
For many *elenium commands, a target is re#uired. This target identifies an element in the
content of the web application, and consists of the location strategy followed by the location in
the format locatorType#location. The locator type can be omitted in many cases. The various
locator types are e'plained below with e'amples for each.
/ocating b& Identifier
This is probably the most common method of locating elements and is the catch!all default when
no recognised locator type is used. With this strategy, the first element with the id attribute value
matching the location will be used. If no element has a matching id attribute, then the first
element with a name attribute matching the location will be used.
For instance, your page source could have id and name attributes as follows"
!
2
4
<html>
<body>
<form id#$lo'inForm$>
3$
Introduction to Selenium
5
6
7
8
-
9
<input name#$username$ type#$text$ />
<input name#$password$ type#$password$ />
<input name#$continue$ type#$submit$ value#$&o'in$ />
</form>
</body>
<html>
The following locator strategies would return the elements from the T-8 snippet above
indicated by line number"
identifier#lo'inForm .<0
identifier#username .B0
identifier#continue .L0
continue .L0
*ince the identifier type of locator is the default, the identifier# in the first three e'amples
above is not necessary.
/ocating b& Id
This type of locator is more limited than the identifier locator type, but also more e'plicit. 2se
this when you %now an elements id attribute.
!
2
4
5
6
7
8
-
9
!:
<html>
<body>
<form id#$lo'inForm$>
<input name#$username$ type#$text$ />
<input name#$password$ type#$password$ />
<input name#$continue$ type#$submit$ value#$&o'in$ />
<input name#$continue$ type#$button$ value#$*lear$ />
</form>
</body>
<html>
id#lo'inForm .<0
/ocating b& Name
The name locator type will locate the first element with a matching name attribute. If multiple
elements have the same value for a name attribute, then you can use filters to further refine your
location strategy. The default filter type is value .matching the value attribute0.
!
2
4
5
6
7
8
-
<html>
<body>
<form id#$lo'inForm$>
<input name#$username$ type#$text$ />
<input name#$password$ type#$password$ />
<input name#$continue$ type#$submit$ value#$&o'in$ />
<input name#$continue$ type#$button$ value#$*lear$ />
</form>
31
Introduction to Selenium
9
!:
</body>
<html>
name#username .B0
name#continue value#*lear .@0
name#continue *lear .@0
name#continue type#button .@0
Pote
2nli%e some types of +/ath and ,5- locators, the three types of locators above allow *elenium
to test a 2I element independent of its location on the page. *o if the page structure and
organi)ation is altered, the test will still pass. Fou may or may not want to also test whether the
page structure changes. In the case where web designers fre#uently alter the page, but its
functionality must be regression tested, testing via id and name attributes, or really via any
T-8 property, becomes very important.
/ocating b& 4.at*
+/ath is the language used for locating nodes in an +-8 document. As T-8 can be an
implementation of +-8 .+T-80, *elenium users can leverage this powerful language to
target elements in their web applications. +/ath e'tends beyond .as well as supporting0 the
simple methods of locating by id or name attributes, and opens up all sorts of new possibilities
such as locating the third chec%bo' on the page.
5ne of the main reasons for using +/ath is when you dont have a suitable id or name attribute
for the element you wish to locate. Fou can use +/ath to either locate the element in absolute
terms .not advised0, or relative to an element that does have an id or name attribute. +/ath
locators can also be used to specify elements via attributes other than id and name.
Absolute +/aths contain the location of all elements from the root .html0 and as a result are
li%ely to fail with only the slightest ad6ustment to the application. Jy finding a nearby element
with an id or name attribute .ideally a parent element0 you can locate your target element based
on the relationship. This is much less li%ely to change and can ma%e your tests more robust.
*ince only xpath locators start with 3GG4, it is not necessary to include the xpath# label when
specifying an +/ath locator.
!
2
4
5
6
7
8
-
9
!:
<html>
<body>
<form id#$lo'inForm$>
<input name#$username$ type#$text$ />
<input name#$password$ type#$password$ />
<input name#$continue$ type#$submit$ value#$&o'in$ />
<input name#$continue$ type#$button$ value#$*lear$ />
</form>
</body>
<html>
32
Introduction to Selenium
xpath#/html/body/form;!< .<0 ! ,(solute path 2.ould (rea* if the 3T1' .as
chan)ed only sli)htly4
//form;!< .<0 ! 5irst form element in the 3T1'
xpath#//form;=id#>lo'inForm>< .<0 ! The form element .ith attri(ute named 6id7 and
the value 6lo)in5orm7
xpath#//form;input/?=name#>username>< .B0 ! 5irst form element .ith an input
child element .ith attri(ute named 6name7 and the value 6username7
//input;=name#>username>< .B0 ! 5irst input element .ith attri(ute named 6name7 and
the value 6username7
//form;=id#>lo'inForm></input;!< .B0 ! 5irst input child element of the form
element .ith attri(ute named 6id7 and the value 6lo)in5orm7
//input;=name#>continue><;=type#>button>< .@0 ! Input .ith attri(ute named
6name7 and the value 6continue7 and attri(ute named 6type7 and the value 6(utton7
//form;=id#>lo'inForm></input;5< .@0 ! 5ourth input child element of the form
element .ith attri(ute named 6id7 and value 6lo)in5orm7
These e'amples cover some basics, but in order to learn more, the following references are
recommended"
W<*chools +/ath Tutorial
W<( +/ath $ecommendation
+/ath Tutorial ! with interactive e'amples.
There are also a couple of very useful Firefo' Add!ons that can assist in discovering the +/ath
of an element"
+/ath (hec%er ! suggests +/ath and can be used to test +/ath results.
Firebug ! +/ath suggestions are 6ust one of the many powerful features of this very
useful add!on.
/ocating 5&perlin6s b& /in6 Te(t
This is a simple method of locating a hyperlin% in your web page by using the te't of the lin%. If
two lin%s with the same te't are present, then the first match will be used.
!
2
4
5
6
7
8
<html>
<body>
<p>.re you sure you want to do this@</p>
<a href#$continue%html$>*ontinue</a>
<a href#$cancel%html$>*ancel</a>
</body>
<html>
lin1#*ontinue .B0
lin1#*ancel .L0
33
Introduction to Selenium
Store Commands and Selenium 1ariables
Fou can use *elenium variables to store constants at the beginning of a script. Also, when
combined with a data!driven test design .discussed in a later section0, *elenium variables can be
used to store values passed to your test program from the command!line, from another program,
or from a file.
The plain store command is the most basic of the many store commands and can be used to
simply store a constant value in a selenium variable. It ta%es two parameters, the te't value to be
stored and a selenium variable. 2se the standard variable naming conventions of only
alphanumeric characters when choosing a name for your variable.
Command Target 1alue
store paulVmysite.org userPame
8ater in your script, youll want to use the stored value of your variable. To access the value of a
variable, enclose the variable in curly brac%ets .NO0 and precede it with a dollar sign li%e this.
Command Target 1alue
verifyTe't GGdivGp MNuserPameO
A common use of variables is for storing input for an input field.
Command Target 1alue
type idKlogin MNuserPameO
*elenium variables can be used in either the first or second parameter and are interpreted by
*elenium prior to any other operations performed by the command. A *elenium variable may
also be used within a locator e'pression.
An e#uivalent store command e'ists for each verify and assert command. ere are a couple more
commonly used store commands.
storeElement.resent
This corresponds to verify7lement/resent. It simply stores a boolean valueQ4true4 or 3false4Q
depending on whether the 2I element is found.
storeTe(t
*toreTe't corresponds to verifyTe't. It uses a locater to identify specific page te't. The te't, if
found, is stored in the variable. *toreTe't can be used to e'tract te't from the page being tested.
3!
Introduction to Selenium
storeE2al
This command ta%es a script as its first parameter. 7mbedding 9ava*cript within *elenese is
covered in the ne't section. *tore7val allows the test to store the result of running the script in a
variable.
echo - T*e Selenese .rint Command
*elenese has a simple command that allows you to print te't to your tests output. This is useful
for providing informational progress notes in your test which display on the console as your test
is running. These notes also can be used to provide conte't within your test result reports, which
can be useful for finding where a defect e'ists on a page in the event your test finds a problem.
Finally, echo statements can be used to print the contents of *elenium variables.
Command Target 1alue
echo Testing page footer now.
echo 2sername is MNuserPameO

3"
Introduction to Selenium
Selenium-RC
Introduction
*elenium!$( is the solution for tests that need more than simple browser actions and linear
e'ecution. *elenium!$( uses the full power of programming languages to create more comple'
tests li%e reading and writing files, #uerying a database, and emailing test results.
Foull want to use *elenium!$( whenever your test re#uires logic not supported by *elenium!
I,7. What logic could this be? For e'ample, *elenium!I,7 does not directly support"
condition statements
iteration
logging and reporting of test results
error handling, particularly une'pected errors
database testing
test case grouping
re!e'ecution of failed tests
test case dependency
screenshot capture of test failures
Although these tas%s are not supported by *elenium directly, all of them can be achieved by
using programming techni#ues with a language!specific *elenium!$(.
5o$ Selenium-RC Wor6s
First, we will describe how the components of *elenium!$( operate and the role each plays in
running your test scripts.
RC Components
*elenium!$( components are"
The *elenium *erver which launches and %ills browsers, interprets and runs the *elenese
commands passed from the test program, and acts as an 3TT proxy, intercepting and
verifying TT/ messages passed between the browser and the A2T.
(lient libraries which provide the interface between each programming language and the
*elenium!$( *erver.
ere is a simplified architecture diagram....
36
Introduction to Selenium
The diagram shows the client libraries communicate with the *erver passing each *elenium
command for e'ecution. Then the server passes the *elenium command to the browser using
*elenium!(ore 9ava*cript commands. The browser, using its 9ava*cript interpreter, e'ecutes the
*elenium command. This runs the *elenese action or verification you specified in your test
script.
Selenium Ser2er
*elenium *erver receives *elenium commands from your test program, interprets them, and
reports bac% to your program the results of running those tests.
The $( server bundles *elenium (ore and automatically in6ects it into the browser. This occurs
when your test program opens the browser .using a client library A/I function0. *elenium!(ore
is a 9ava*cript program, actually a set of 9ava*cript functions which interprets and e'ecutes
*elenese commands using the browsers built!in 9ava*cript interpreter.
37
Introduction to Selenium
The *erver receives the *elenese commands from your test program using simple TT/
;7TG/5*T re#uests. This means you can use any programming language that can send TT/
re#uests to automate *elenium tests on the browser.
Client /ibraries
The client libraries provide the programming support that allows you to run *elenium commands
from a program of your own design. There is a different client library for each supported
language. A *elenium client library provides a programming interface .A/I0, i.e., a set of
functions, which run *elenium commands from your own program. Within each interface, there
is a programming function that supports each *elenese command.
The client library ta%es a *elenese command and passes it to the *elenium *erver for processing
a specific action or test against the application under test .A2T0. The client library also receives
the result of that command and passes it bac% to your program. Four program can receive the
result and store it into a program variable and report it as a success or failure, or possibly ta%e
corrective action if it was an une'pected error.
*o to create a test program, you simply write a program that runs a set of *elenium commands
using a client library A/I. And, optionally, if you already have a *elenese test script created in
the *elenium!I,7, you can )enerate the Selenium-RC code. The *elenium!I,7 can translate
.using its 7'port menu item0 its *elenium commands into a client!drivers A/I function calls.
*ee the *elenium!I,7 chapter for specifics on e'porting $( code from *elenium!I,7.
Installation
After downloading the *elenium!$( )ip file from the downloads page, youll notice it has
several sub!folders. These folders have all the components you need for using *elenium!$( with
the programming language of your choice.
5nce youve chosen a language to wor% with, you simply need to"
Install the *elenium!$( *erver.
*et up a programming pro6ect using a language specific client driver.
Installing Selenium Ser2er
The *elenium!$( server is simply a 9ava 8ar file .selenium-server.8ar0, which doesnt re#uire
any special installation. 9ust downloading the )ip file and e'tracting the server in the desired
directory is sufficient.
Running Selenium Ser2er
Jefore starting any tests you must start the server. ;o to the directory where *elenium!$(s
server is located and run the following from a command!line console.
38
Introduction to Selenium
6ava !6ar selenium!server.6ar
This can be simplified by creating a batch or shell e'ecutable file ..bat on Windows and .sh on
8inu'0 containing the command above. Then ma%e a shortcut to that e'ecutable on your des%top
and simply double!clic% the icon to start the server.
For the server to run youll need 9ava installed and the /AT environment variable correctly
configured to run it from the console. Fou can chec% that you have 9ava correctly installed by
running the following on a console"
Aava -version
If you get a version number .which needs to be C.L or later0, youre ready to start using
*elenium!$(.
,sing t*e 7NET Client Dri2er
,ownload *elenium!$( from the *eleniumW downloads page
7'tract the folder
,ownload and install P2nit . Pote" Fou can use P2nit as your test engine. If youre not
familiar yet with P2nit, you can also write a simple main.0 function to run your tests1
however P2nit is very useful as a test engine.0
5pen your desired .Pet I,7 .&isual *tudio, *harp,evelop, -ono,evelop0
(reate a class library ..dll0
Add references to the following ,88s" nmoc%.dll, nunit.core.dll, nunit. framewor%.dll,
ThoughtWor%s.*elenium.(ore.dll, ThoughtWor%s.*elenium. IntegrationTests.dll and
ThoughtWor%s.*elenium.2nitTests.dll
Write your *elenium test in a .Pet language .(:, &J.Pet0, or e'port a script from
*elenium!I,7 to a (: file and copy this code into the class file you 6ust created.
Write your own simple main.0 program or you can include P2nit in your pro6ect for
running your test. These concepts are e'plained later in this chapter.
$un *elenium server from console
$un your test either from the I,7, from the P2nit ;2I or from the command line
For specific details on .P7T client driver configuration with &isual *tudio, see the appendi'
.9ET client driver confi)uration.
'rom Selenese to a .rogram
The primary tas% for using *elenium!$( is to convert your *elenese into a programming
language. In this section, we provide several different language!specific e'amples.
Sample Test Script
3#
Introduction to Selenium
8ets start with an e'ample *elenese test script. Imagine recording the following test with
*elenium!I,7.
open G
type # selenium rc
clic%AndWait btn;
assertTe't/resent $esults ? for selenium rc
Pote" This e'ample would wor% with the ;oogle search page http"GGwww.google.com
Selenese as .rogramming Code
ere is the test script e'ported .via *elenium!I,70 to each of the supported programming
languages. If you have at least basic %nowledge of an ob6ect! oriented programming language,
you will understand how *elenium runs *elenese commands by reading one of these e'amples.
In the ne't section well e'plain how to build a test program using the generated code.
.rogramming +our Test
Pow well illustrate how to program your own tests using e'amples in each of the supported
programming languages. There are essentially two tas%s"
;enerate your script into a programming language from *elenium!I,7, optionally
modifying the result.
Write a very simple main program that e'ecutes the generated code.
5ptionally, you can adopt a test engine platform li%e 92nit or TestP; for 9ava, or P2nit for
.P7T if you are using one of those languages.
C8
The .P7T (lient ,river wor%s with -icrosoft.P7T. It can be used with any .P7T testing
framewor% li%e P2nit or the &isual *tudio =DDL Team *ystem.
*elenium!I,7 assumes you will use P2nit as your testing framewor%. Fou can see this in the
generated code below. It includes the usin) statement for P2nit along with corresponding P2nit
attributes identifying the role for each member function of the test class.
Fou will probably have to rename the test class from 3PewTest4 to something of your own
choosing. Also, you will need to change the browser!open parameters in the statement"
selenium # new DefaultSeleniumB$localhost$C 5555C $Diehta$C
$httpE//www%'oo'le%com/$F+
!$
Introduction to Selenium
The generated code will loo% similar to this.
usin' System+
usin' System%Text+
usin' System%Text%Ge'ular3xpressions+
usin' System%Threadin'+
usin' H,nit%Framewor1+
usin' Selenium+
namespace SeleniumTests
I
;TestFixture<
public class HewTest
I
private JSelenium selenium+
private Strin'2uilder verification3rrors+
;Set,p<
public void SetupTestBF
I
selenium # new DefaultSeleniumB$localhost$C 5555C $Diehta$C
$httpE//www%'oo'le%com/$F+
selenium%StartBF+
verification3rrors # new Strin'2uilderBF+
K
;TearDown<
public void TeardownTestBF
I
try
I
selenium%StopBF+
K
catch B3xceptionF
I
// J'nore errors if unable to close the browser
K
.ssert%.re3)ualB$$C verification3rrors%ToStrin'BFF+
K
;Test<
public void TheHewTestBF
I
// "pen Loo'le search en'ine%
selenium%"penB$httpE//www%'oo'le%com/$F+
!1
Introduction to Selenium
// .ssert Title of pa'e%
.ssert%.re3)ualB$Loo'le$C selenium%LetTitleBFF+
// rovide search term as $Selenium "penM.$
selenium%TypeB$)$C $Selenium "penM.$F+
// Gead the 1eyed search term and assert it%
.ssert%.re3)ualB$Selenium "penM.$C selenium%Let(alueB$)$FF+
// *lic1 on Search button%
selenium%*lic1B$btnL$F+
// Nait for pa'e to load%
selenium%NaitFora'eTo&oadB$6:::$F+
// .ssert that $www%open)a%or'$ is available in search results%
.ssert%JsTrueBselenium%JsTextresentB$www%open)a%or'$FF+
// .ssert that pa'e title is - $Selenium "penM. - Loo'le Search$
.ssert%.re3)ualB$Selenium "penM. - Loo'le Search$C
selenium%LetTitleBFF+
K
K
K
Fou can allow P2nit to manage the e'ecution of your tests. 5r alternatively, you can write a
simple main.0 program that instantiates the test ob6ect and runs each of the three methods,
*etupTest.0, ThePewTest.0, and TeardownTest.0 in turn.
!2
Introduction to Selenium
Test Design Considerations
Introducing Test Design
In this subsection we describe a few types of different tests you can do with *elenium. This may
not be new to you, but we provide this as a framewor% for relating *elenium test automation to
the decisions a #uality assurance professional will ma%e when deciding what tests to perform, the
priority for each of those tests, and whether to automate those tests or not.
W*at to Test?
What parts of your application should you test? That depends on aspects of your pro6ect" user
e'pectations, time allowed for the pro6ect, priorities set by the pro6ect manager and so on. 5nce
the pro6ect boundaries are defined though, you, the tester, will certainly ma%e many decisions on
what to test.
We will define some terms here to help us categori)e the types of testing typical for a web!
application. These terms are by no means standard, although the concepts we present here are
typical for web!application testing. Weve created a few terms here of our own for the purposes
of categori)ing the types of test you may perform on your web application.
Testing for E(pected Content
The simplest type of test, a content test, is a simple test for the e'istence of a static, non!
changing, 2I element. For instance
,oes each page have its e'pected page title? This can be used to verify your test found an
e'pected page after following a lin%.
,oes each page of the website contain a footer area with lin%s to the company contact
page, privacy policy, and trademar%s information?
,oes each page begin with heading te't using the ThCR tag? And, does each page have
the correct te't within that header?
Fou may or may not need content tests. If your page content is not li%ely to be affected then it
may be more efficient to test page content manually. If, however, your application will be
undergoing platform changes, or files will li%ely be moved to different locations, content tests
may prove valuable.
Testing /in6s
!3
Introduction to Selenium
A fre#uent source of errors for web!sites is bro%en lin%s and missing pages behind those bro%en
lin%s. Testing for these involves clic%ing each lin% and verifying the e'pected page behind that
lin% loads correctly.
'unction Tests
These would be tests of a specific function within your application, re#uiring some type of user
input, and returning some type of results. 5ften a function test will involve multiple pages with a
form!based input page containing a collection of input fields, *ubmit and (ancel operations, and
one or more response pages. 2ser input can be via te't!input fields, chec%bo'es, drop!down lists,
or any other browser!supported input.
!!

You might also like