173
Table Of Contents Introduction Test Automation for Web Applications  To Automate or Not to Automate?  Introducing Selenium Brief History of The Selenium Project  Seleniums Tool Suite !hoosing "our Selenium Tool  Supported Bro#sers and Platforms  $le%ibility and &%tensibility Whats in this Boo'? The (ocumentation Team)Authors Past and Present  Introduction Test Automation for Web Applications *any+ perhaps most+ soft#are applications today are #ritten as #eb,based applications to be run in an Internet bro#ser- The effecti.eness of testing these applications .aries #idely among companies and organi/ations- In an era of highly interacti.e and responsi.e soft#are processes #here many organi/ations are using some form of Agile methodology+ test automation is fre0uently becoming a re0uirement for soft#are projects- Test automation is often the ans#er- Test automation means using a soft#are tool to run repeatable tests against the application to be tested- $or regression testing this pro.ides that responsi.e ness- There are many ad.antages to test automation- *ost are related to the repeatability of the tests and the speed at #hich the tests can be e%ecuted- There are a number of commercial and open source tools a.ailable for assisting #ith the de.elopment of test automation- Selenium is possibly the most #idely,used open source solution- This users guide #ill assist both ne# and e%perienced Selenium users in learning effecti.e techni0ues in building test automation for #eb applications- This users guide introduces Selenium+ teaches its features+ and presents commonly used best practices accumulated from the Selenium community- *any e%amples are pro.ided- Also+ technical information on the internal structure of Selenium and recommended uses of Selenium are pro.ided-

About Sellinum

  • Upload
    webiis

  • View
    217

  • Download
    0

Embed Size (px)

Citation preview

Page 1: About Sellinum

8/11/2019 About Sellinum

http://slidepdf.com/reader/full/about-sellinum 1/173

Table Of Contents

• Introduction

• Test Automation for Web Applications 

• To Automate or Not to Automate? 

• Introducing Selenium 

• Brief History of The Selenium Project 

• Seleniums Tool Suite 

• !hoosing "our Selenium Tool 

• Supported Bro#sers and Platforms 

• $le%ibility and &%tensibility 

• Whats in this Boo'? 

• The (ocumentation Team)Authors Past and Present 

Introduction

Test Automation for Web Applications

*any+ perhaps most+ soft#are applications today are #ritten as #eb,based applications to be run in an Internet bro#ser- The effecti.eness oftesting these applications .aries #idely among companies and organi/ations- In an era of highly interacti.e and responsi.e soft#areprocesses #here many organi/ations are using some form of Agile methodology+ test automation is fre0uently becoming a re0uirement for

soft#are projects- Test automation is often the ans#er- Test automation means using a soft#are tool to run repeatable tests against theapplication to be tested- $or regression testing this pro.ides that responsi.eness-

There are many ad.antages to test automation- *ost are related to the repeatability of the tests and the speed at #hich the tests can bee%ecuted- There are a number of commercial and open source tools a.ailable for assisting #ith the de.elopment of test automation- Seleniumis possibly the most #idely,used open source solution- This users guide #ill assist both ne# and e%perienced Selenium users in learningeffecti.e techni0ues in building test automation for #eb applications-

This users guide introduces Selenium+ teaches its features+ and presents commonly used best practices accumulated from the Seleniumcommunity- *any e%amples are pro.ided- Also+ technical information on the internal structure of Selenium and recommended uses ofSelenium are pro.ided-

Page 2: About Sellinum

8/11/2019 About Sellinum

http://slidepdf.com/reader/full/about-sellinum 2/173

Test automation has specific ad.antages for impro.ing the long,term efficiency of a soft#are teams testing processes- Test automationsupports1

• $re0uent regression testing

• 2apid feedbac' to de.elopers

• 3irtually unlimited iterations of test case e%ecution

• Support for Agile and e%treme de.elopment methodologies

• (isciplined documentation of test cases

• !ustomi/ed defect reporting

• $inding defects missed by manual testing

To Automate or Not to Automate?

Is automation al#ays ad.antageous? When should one decide to automate test cases?

It is not al#ays ad.antageous to automate test cases- There are times #hen manual testing may be more appropriate- $or instance+ if theapplications user interface #ill change considerably in the near future+ then any automation might need to be re#ritten any#ay- Also+sometimes there simply is not enough time to build test automation- $or the short term+ manual testing may be more effecti.e- If anapplication has a .ery tight deadline+ there is currently no test automation a.ailable+ and its imperati.e that the testing get done #ithin thattime frame+ then manual testing is the best solution-

Introducing Selenium

Selenium is a set of different soft#are tools each #ith a different approach to supporting test automation- *ost Selenium 4A &ngineersfocus on the one or t#o tools that most meet the needs of their project+ ho#e.er learning all the tools #ill gi.e you many different options

for approaching different test automation problems- The entire suite of tools results in a rich set of testing functions specifically geared to theneeds of testing of #eb applications of all types- These operations are highly fle%ible+ allo#ing many options for locating 5I elements andcomparing e%pected test results against actual application beha.ior- 6ne of Seleniums 'ey features is the support for e%ecuting ones testson multiple bro#ser platforms-

Brief History of The Selenium ro!ect

Selenium first came to life in 7889 #hen :ason Huggins #as testing an internal application at ThoughtWor's- Being a smart guy+ he reali/edthere #ere better uses of his time than manually stepping through the same tests #ith e.ery change he made- He de.eloped a :a.ascriptlibrary that could dri.e interactions #ith the page+ allo#ing him to automatically rerun tests against multiple bro#sers- That library

Page 3: About Sellinum

8/11/2019 About Sellinum

http://slidepdf.com/reader/full/about-sellinum 3/173

e.entually became Selenium !ore+ #hich underlies all the functionality of Selenium 2emote !ontrol ;2!< and Selenium I(&- Selenium 2!#as ground,brea'ing because no other product allo#ed you to control a bro#ser from a language of your choice-

While Selenium #as a tremendous tool+ it #asnt #ithout its dra#bac's- Because of its :a.ascript based automation engine and the securitylimitations bro#sers apply to :a.ascript+ different things became impossible to do- To ma'e things #orse+ #ebapps became more and morepo#erful o.er time+ using all sorts of special features ne# bro#sers pro.ide and ma'ing this restrictions more and more painful-

In 788= a pluc'y engineer at >oogle named Simon Ste#art started #or' on a project he called Web(ri.er- >oogle had long been a hea.yuser of Selenium+ but testers had to #or' around the limitations of the product- Simon #anted a testing tool that spo'e directly to the bro#serusing the nati.e method for the bro#ser and operating system+ thus a.oiding the restrictions of a sandbo%ed :a.ascript en.ironment- TheWeb(ri.er project began #ith the aim to sol.e the Selenium pain,points-

:ump to 788@- The Beijing 6lympics mar' !hinas arri.al as a global po#er+ massi.e mortgage default in the 5nited States triggers the#orst international recession since the >reat (epression+ The (ar' night is .ie#ed by e.ery human ;t#ice<+ still reeling from the untimelyloss of Heath edger- But the most important story of that year #as the merging of Selenium and Web(ri.er- Selenium had massi.ecommunity and commercial support+ but Web(ri.er #as clearly the tool of the future- The joining of the t#o tools pro.ided a common set offeatures for all users and brought some of the brightest minds in test automation under one roof- Perhaps the best e%planation for #hy

Web(ri.er and Selenium are merging #as detailed by Simon Ste#art+ the creator of Web(ri.er+ in a joint email to the Web(ri.er andSelenium community on August =+ 788C-

DWhy are the projects merging? Partly because #ebdri.er addresses some shortcomings in selenium ;by being able to bypass the:S sandbo%+ for e%ample- And #e.e got a gorgeous API<+ partly because selenium addresses some shortcomings in #ebdri.er;such as supporting a broader range of bro#sers< and partly because the main selenium contributors and I felt that it #as the best#ay to offer users the best possible frame#or'-E

Selenium"s Tool Suite

Selenium is composed of multiple soft#are tools- &ach has a specific role-

Selenium # $a%a& Selenium Webdri'er(

Selenium 7 is the future direction of the project and the ne#est addition to the Selenium tool'it- This brand ne# automation tool pro.ides allsorts of a#esome features+ including a more cohesi.e and object oriented API as #ell as an ans#er to the limitations of the oldimplementation-

As you can read in Brief History of The Selenium Project

+ both the Selenium and Web(ri.er de.elopers agreed that both tools ha.ead.antages and that merging the t#o projects #ould ma'e a much more robust automation tool-

Page 4: About Sellinum

8/11/2019 About Sellinum

http://slidepdf.com/reader/full/about-sellinum 4/173

Selenium 7-8 is the product of that effort- It supports the Web(ri.er API and underlying technology+ along #ith the Selenium F technologyunderneath the Web(ri.er API for ma%imum fle%ibility in porting your tests- In addition+ Selenium 7 still runs Selenium Fs Selenium 2!interface for bac'#ards compatibility-

Selenium ) $a%a& Selenium *C or *emote Control(

As you can read in Brief History of The Selenium Project

+ Selenium 2! #as the main Selenium project for a long time+ before theWeb(ri.erGSelenium merge brought up Selenium 7+ the ne#est and more po#erful tool-

Selenium F is still acti.ely supported ;mostly in maintenance mode< and pro.ides some features that may not be a.ailable in Selenium 7 fora #hile+ including support for se.eral languages ;:a.a+ :a.ascript+ 2uby+ PHP+ Python+ Perl and !< and support for almost e.ery bro#ser outthere-

Selenium I+,

Selenium I(& ;Integrated (e.elopment &n.ironment< is a prototyping tool for building test scripts- It is a $irefo% plugin and pro.ides an

easy,to,use interface for de.eloping automated tests- Selenium I(& has a recording feature+ #hich records user actions as they are performedand then e%ports them as a reusable script in one of many programming languages that can be later e%ecuted-

Note

&.en though Selenium I(& has a DSa.eE feature that allo#s users to 'eep the tests in a table,based format for later import and e%ecution+ itis not designed to run your test passes nor is it designed to build all the automated tests you will need - Specifically+ Selenium I(& doesntpro.ide iteration or conditional statements for test scripts- At the time of #riting there is no plan to add such thing- The reasons are partlytechnical and partly based on the Selenium de.elopers encouraging best practices in test automation #hich al#ays re0uires some amount ofprogramming- Selenium I+, is simply intended as a rapid prototyping tool- The Selenium de.elopers recommend for serious+ robust testautomation either Selenium 7 or Selenium F to be used #ith one of the many supported programming languages-

Selenium-.rid

Selenium,>rid allo#s the Selenium 2! solution to scale for large test suites and for test suites that must be run in multiple en.ironments-Selenium >rid allo#s you to run your tests in parallel+ that is+ different tests can be run at the same time on different remote machines- Thishas t#o ad.antages- $irst+ if you ha.e a large test suite+ or a slo#,running test suite+ you can boost its performance substantially by usingSelenium >rid to di.ide your test suite to run different tests at the same time using those different machines- Also+ if you must run your testsuite on multiple en.ironments you can ha.e different remote machines supporting and running your tests in them at the same time- In eachcase Selenium >rid greatly impro.es the time it ta'es to run your suite by ma'ing use of parallel processing-

Page 5: About Sellinum

8/11/2019 About Sellinum

http://slidepdf.com/reader/full/about-sellinum 5/173

Choosing /our Selenium Tool

*any people get started #ith Selenium I(&- If you are not already e%perienced #ith a programming or scripting language you can useSelenium I(& to get familiar #ith Selenium commands- 5sing the I(& you can create simple tests 0uic'ly+ sometimes #ithin seconds-

We dont+ ho#e.er+ recommend you do all your test automation using Selenium I(&- To effecti.ely use Selenium you #ill need to build and

run your tests using either Selenium 7 or Selenium F in conjunction #ith one of the supported programming languages- Which one youchoose depends on you-

At the time of #riting the Selenium de.elopers are planning on the Selenium,Web(ri.er API being the future direction for Selenium-Selenium F is pro.ided for bac'#ards compatibility- Still+ both ha.e strengths and #ea'nesses #hich are discussed in the correspondingchapters of this document-

We recommend those #ho are completely ne# to Selenium to read through these sections- Ho#e.er+ for those #ho are adopting Seleniumfor the first time+ and therefore building a ne# test suite from scratch+ you #ill probably #ant to go #ith Selenium 7 since this is the portionof Selenium that #ill continue to be supported in the future-

Supported Bro0sers and latformsIn Selenium 7-8+ the supported bro#sers .ary depending on #hether you are using Selenium,Web(ri.er or Selenium,2!-

Selenium-Web+ri'er

Selenium,Web(ri.er supports the follo#ing bro#sers along #ith the operating systems these bro#sers are compatible #ith-

• >oogle !hrome F7-8-F7-8J

• Internet &%plorer =+ + @+ C , K7 and =9,bit #here applicable

$irefo% K-8+ K-L+ K-=+ 9-8+ L-8+ =+ • 6pera FF-LJ

• Html5nit 7-C

• Android ) 7-KJ for phones and tablets ;de.ices M emulators<

• i6S KJ for phones ;de.ices M emulators< and K-7J for tablets ;de.ices M emulators<

 Note: At the time of writing there is an emulator bug with Android 2.3 that prevents the driver from working properly on device emulators.

 However, it works fine on tablet emulators and real devices.

Page 6: About Sellinum

8/11/2019 About Sellinum

http://slidepdf.com/reader/full/about-sellinum 6/173

Selenium )&1 and Selenium-*C&

This is the old+ support platform for Selenium F-8- It should still apply to the Selenium 7-8 release of Selenium,2!-

Bro0ser SeleniumI+,

Selenium) $*C(

OperatingSystems

2irefo34&3

*ecordandplaybac%tests

Startbro0ser5run tests

Windo0s56inu357ac

2irefo3 4 *ecordandplaybac%tests

Startbro0ser5run tests

Windo0s56inu357ac

2irefo3 # *ecordand

playbac%tests

Startbro0ser5

run tests

Windo0s56inu35

7ac

I, 8 Teste3ecutiononly 'iaSelenium*C9

Startbro0ser5run tests

Windo0s

I, : Teste3ecution

only 'iaSelenium*C9

Startbro0ser5

run tests

Windo0s

I, ; Teste3ecutiononly 'iaSelenium*C9

Startbro0ser5run tests

Windo0s

Safari < Teste3ecution

Startbro0ser5

Windo0s57ac

Page 7: About Sellinum

8/11/2019 About Sellinum

http://slidepdf.com/reader/full/about-sellinum 7/173

only 'iaSelenium*C

run tests

Safari 4 Teste3ecution

only 'iaSelenium*C

Startbro0ser5

run tests

Windo0s57ac

Safari # Teste3ecutiononly 'iaSelenium*C

Startbro0ser5run tests

Windo0s57ac

Opera)1

Teste3ecution

only 'iaSelenium*C

Startbro0ser5

run tests

Windo0s56inu35

7ac

Opera = Teste3ecutiononly 'iaSelenium*C

Startbro0ser5run tests

Windo0s56inu357ac

Opera 8 Test

e3ecutiononly 'iaSelenium*C

Start

bro0ser5run tests

Windo0s5

6inu357ac

.oogleChrome

Teste3ecutiononly 'iaSelenium*C

Startbro0ser5run tests

Windo0s56inu357ac

Others Test artial As

Page 8: About Sellinum

8/11/2019 About Sellinum

http://slidepdf.com/reader/full/about-sellinum 8/173

e3ecutiononly 'iaSelenium*C

supportpossible99

applicable

9 Tests de'eloped on 2irefo3 'ia Selenium I+, can be e3ecuted on any other supported bro0ser 'ia a simple Selenium *C command

line& Selenium 2! ser.er can start any e%ecutable+ but depending on bro#ser security settings there may be technical limitations that #ouldlimit certain features-

2le3ibility and ,3tensibility

"oull find that Selenium is highly fle%ible- There are many #ays you can add functionality to both Selenium test scripts and Seleniumsframe#or' to customi/e your test automation- This is perhaps Seleniums greatest strength #hen compared #ith other automation tools-These customi/ations are described in .arious places throughout this document- In addition+ since Selenium is 6pen Source+ the sourcecodecan al#ays be do#nloaded and modified-

What"s in this Boo%?

This users guide targets both ne# users and those #ho ha.e already used Selenium but are see'ing additional 'no#ledge- We introduceSelenium to ne# users and #e do not assume prior Selenium e%perience- We do assume+ ho#e.er+ that the user has at least a basicunderstanding of test automation- $or the more e%perienced user+ this guide can act as a reference- $or the more e%perienced+ #e recommendbro#sing the chapter and subheadings- We.e pro.ided information on the Selenium architecture+ e%amples of common usage+ and a chapteron test design techni0ues-

The remaining chapters of the reference present1

Selenium I(& Introduces Selenium I(& and describes ho# to use it to build test scripts- using the Selenium Integrated (e.elopment &n.ironment- Ifyou are not e%perienced in programming+ but still hoping to learn test automation this is #here you should start and youll find you cancreate 0uite a fe# automated tests #ith Selenium I(&- Also+ if you are e%perienced in programming+ this chapter may still interest youin that you can use Selenium I(& to do rapid prototyping of your tests- This section also demonstrates ho# your test script can beDe%portedE to a programming language for adding more ad.anced capabilities not supported by Selenium I(&-

Selenium 7 &%plains ho# to de.elop an automated test program using Selenium 7-

Selenium F &%plains ho# to de.elop an automated test program using the Selenium 2! API- *any e%amples are presented in both programming

Page 9: About Sellinum

8/11/2019 About Sellinum

http://slidepdf.com/reader/full/about-sellinum 9/173

languages and scripting languages- Also+ the installation and setup of Selenium 2! is co.ered here- The .arious modes+ orconfigurations+ that Selenium 2! supports are described+ along #ith their trade,offs and limitations- An architecture diagram ispro.ided to help illustrate these points- Solutions to common problems fre0uently difficult for ne# Sel,2 users are described here+ forinstance+ handling Security !ertificates+ https re0uests+ pop,ups+ and the opening of ne# #indo#s-

Test (esign !onsiderations This chapter presents programming techni0ues for use #ith Selenium,Web(ri.er and Selenium 2!- We also demonstrate techni0uescommonly as'ed about in the user forum such as ho# to design setup and teardo#n functions+ ho# to implement data,dri.en tests;tests #here one can .ary the data bet#een test passes< and other methods of programming common test automation tas's-

Selenium,>rid his chapter is not yet developed. 

5ser e%tensions (escribes #ays that Selenium can be modified+ e%tended and customi/ed-

The +ocumentation Team>Authors ast and resent

In alphabetical order+ the follo#ing people ha.e made significant contributions to the authoring of this users guide+ its publishinginfrastructure+ or both- We are .ery grateful to all of them-

• (a.e Hunt

• u'e Inman,Semerau

• *ary Ann *ay,Pumphrey

• Noah Sussman

• Paul >randjean

• Peter Ne#hoo'

• Santiago Suare/,6rdone/

• Simon Ste#art

• Tarun umar 

Ac%no0ledgements

A special than's goes to Patric' ightbody- As an administrator of the SeleniumH4 #ebsite+ major contributor to Selenium 2!+ his support#as in.aluable #hen #riting the first release of the users guide- Patric' helped us understand our audience- He also set us up #ithe.erything #e needed on the seleniumh0-org #ebsite for publishing the documents- Also a than's goes to Andras Hat.ani for his ad.ice onpublishing solutions+ and to Amit umar for participating in our discussions and for assisting #ith re.ie#ing the document-

Page 10: About Sellinum

8/11/2019 About Sellinum

http://slidepdf.com/reader/full/about-sellinum 10/173

And of course+ #e must recogni!e the "elenium #evelopers- They ha.e truly designed an ama/ing tool- Without the .ision of the originaldesigners+ and the continued efforts of the current de.elopers+ #e #ould not ha.e such a great tool to pass on to you-

Table Of Contents• Selenium,I(&

• Introduction 

• Installing the I(& 

• 6pening the I(& 

• I(& $eatures 

• Building Test !ases 

• 2unning Test !ases 

• 5sing Base 52 to 2un Test !ases in (ifferent (omains 

• Selenium !ommands ) DSeleneseE 

• Script Synta% 

• Test Suites 

• !ommonly 5sed Selenium !ommands 

• 3erifying Page &lements 

• Assertion or 3erification? 

• ocating &lements 

• *atching Te%t Patterns 

• The DAndWaitE !ommands 

• The #ait$or !ommands in A:AO applications 

• Se0uence of &.aluation and $lo# !ontrol 

• Store !ommands and Selenium 3ariables 

• :a.aScript and Selenese Parameters 

• echo , The Selenese Print !ommand 

• Alerts+ Popups+ and *ultiple Windo#s 

• (ebugging 

• Writing a Test Suite 

Page 11: About Sellinum

8/11/2019 About Sellinum

http://slidepdf.com/reader/full/about-sellinum 11/173

• 5ser &%tensions 

• $ormat 

• &%ecuting Selenium,I(& Tests on (ifferent Bro#sers 

• Troubleshooting 

Selenium-I+,

Introduction

The Selenium,I(& ;Integrated (e.elopment &n.ironment< is the tool you use to de.elop your Selenium test cases- Its an easy,to,use$irefo% plug,in and is generally the most efficient #ay to de.elop test cases- It also contains a conte%t menu that allo#s you to first select a

5I element from the bro#sers currently displayed page and then select from a list of Selenium commands #ith parameters pre,definedaccording to the conte%t of the selected 5I element- This is not only a time,sa.er+ but also an e%cellent #ay of learning Selenium scriptsynta%-

This chapter is all about the Selenium I(& and ho# to use it effecti.ely-

Installing the I+,

5sing $irefo%+ first+ do#nload the I(& from the SeleniumH4 do#nloads page

$irefo% #ill protect you from installing addons from unfamiliar locations+ so you #ill need to clic' Allo# to proceed #ith the installation+

as sho#n in the follo#ing screenshot- 

When do#nloading from $irefo%+ youll be presented #ith the follo#ing #indo#- 

Select Install No#- The $irefo% Add,ons #indo# pops up+ first sho#ing a progress bar+ and #hen the do#nload is complete+ displays thefollo#ing- 

2estart $irefo%- After $irefo% reboots you #ill find the Selenium,I(& listed under the $irefo% Tools menu-

Page 12: About Sellinum

8/11/2019 About Sellinum

http://slidepdf.com/reader/full/about-sellinum 12/173

 

Opening the I+,

To run the Selenium,I(&+ simply select it from the $irefo% Tools menu- It opens as follo#s #ith an empty script,editing #indo# and a menu

for loading+ or creating ne# test cases- 

I+, 2eatures

7enu Bar

The $ile menu has options for Test !ase and Test Suite ;suite of Test !ases<- 5sing these you can add a ne# Test !ase+ open a Test !ase+sa.e a Test !ase+ e%port Test !ase in a language of your choice- "ou can also open the recent Test !ase-All these options are also a.ailable

for Test Suite-The &dit menu allo#s copy+ paste+ delete+ undo+ and select all operations for editing the commands in your test case- The 6ptions menuallo#s the changing of settings- "ou can set the timeout .alue for certain commands+ add user,defined user e%tensions to the base set ofSelenium commands+ and specify the format ;language< used #hen sa.ing your test cases- The Help menu is the standard $irefo% Helpmenu only one item on this menu)5I,&lement (ocumentation)pertains to Selenium,I(&-

Toolbar

The toolbar contains buttons for controlling the e%ecution of your test cases+ including a step feature for debugging your test cases- Theright,most button+ the one #ith the red,dot+ is the record button-

 

Speed !ontrol1 controls ho# fast your test case runs-

2un All1 2uns the entire test suite #hen a test suite #ith multiple test cases is loaded-

2un1 2uns the currently selected test- When only a single test is loaded this button and the 2un All button ha.e the same effect-

PauseG2esume1 Allo#s stopping and re,starting of a running test case-

Page 13: About Sellinum

8/11/2019 About Sellinum

http://slidepdf.com/reader/full/about-sellinum 13/173

 

Step1 Allo#s you to DstepE through a test case by running it one command at a time- 5se for debugging test cases-

Test2unner *ode1 Allo#s you to run the test case in a bro#ser loaded #ith the Selenium,!ore Test2unner- The Test2unner is notcommonly used no# and is li'ely to be deprecated- This button is for e.aluating test cases for bac'#ards compatibility #ith theTest2unner- *ost users #ill probably not need this button-

Apply 2ollup 2ules1 This ad.anced feature allo#s repetiti.e se0uences of Selenium commands to be grouped into a single action-(etailed documentation on rollup rules can be found in the 5I,&lement (ocumentation on the Help menu-

2ecord1 2ecords the users bro#ser actions-

Test Case ane

"our script is displayed in the test case pane- It has t#o tabs+ one for displaying the command and their parameters in a readable DtableE

format- 

The other tab , Source displays the test case in the nati.e format in #hich the file #ill be stored- By default+ this is HT* although it can bechanged to a programming language such as :a.a or !+ or a scripting language li'e Python- See the 6ptions menu for details- The Source.ie# also allo#s one to edit the test case in its ra# form+ including copy+ cut and paste operations-

The !ommand+ Target+ and 3alue entry fields display the currently selected command along #ith its parameters- These are entry fields #hereyou can modify the currently selected command- The first parameter specified for a command in the 2eference tab of the bottom paneal#ays goes in the Target field- If a second parameter is specified by the 2eference tab+ it al#ays goes in the 3alue field- 

If you start typing in the !ommand field+ a drop,do#n list #ill be populated based on the first characters you type you can then select yourdesired command from the drop,do#n-

6og*eference@I-,lement*ollup ane

The bottom pane is used for four different functions)og+ 2eference+ 5I,&lement+ and 2ollup)depending on #hich tab is selected-

Page 14: About Sellinum

8/11/2019 About Sellinum

http://slidepdf.com/reader/full/about-sellinum 14/173

6og

When you run your test case+ error messages and information messages sho#ing the progress are displayed in this pane automatically+ e.enif you do not first select the og tab- These messages are often useful for test case debugging- Notice the !lear button for clearing the og-Also notice the Info button is a drop,do#n allo#ing selection of different le.els of information to log- 

*eference

The 2eference tab is the default selection #hene.er you are entering or modifying Selenese commands and parameters in Table mode- InTable mode+ the 2eference pane #ill display documentation on the current command- When entering or modifying commands+ #hether fromTable or Source mode+ it is critically important to ensure that the parameters specified in the Target and 3alue fields match those specified inthe parameter list in the 2eference pane- The number of parameters pro.ided must match the number specified+ the order of parameterspro.ided must match the order specified+ and the type of parameters pro.ided must match the type specified- If there is a mismatch in any ofthese three areas+ the command #ill not run correctly- 

While the 2eference tab is in.aluable as a 0uic' reference+ it is still often necessary to consult the Selenium 2eference document-

@I-,lement and *ollup

(etailed information on these t#o panes ;#hich co.er ad.anced features< can be found in the 5I,&lement (ocumentation on the Help menuof Selenium,I(&-

Building Test Cases

There are three primary methods for de.eloping test cases- $re0uently+ a test de.eloper #ill re0uire all three techni0ues-

*ecording

*any first,time users begin by recording a test case from their interactions #ith a #ebsite- When Selenium,I(& is first opened+ the recordbutton is 6N by default- If you do not #ant Selenium,I(& to begin recording automatically you can turn this off by going under 6ptions Q6ptions--- and deselecting DStart recording immediately on open-E

(uring recording+ Selenium,I(& #ill automatically insert commands into your test case based on your actions- Typically+ this #ill include1

• clic'ing a lin' , click  or clickAnd$ait  commands

Page 15: About Sellinum

8/11/2019 About Sellinum

http://slidepdf.com/reader/full/about-sellinum 15/173

• entering .alues , type command

• selecting options from a drop,do#n listbo% , select  command

• clic'ing chec'bo%es or radio buttons , click  command

Here are some DgotchasE to be a#are of1

The type command may re0uire clic'ing on some other area of the #eb page for it to record-• $ollo#ing a lin' usually records a click  command- "ou #ill often need to change this to clickAnd$ait  to ensure your test case pauses

until the ne# page is completely loaded- 6ther#ise+ your test case #ill continue running commands before the page has loaded all its5I elements- This #ill cause une%pected test case failures-

Adding erifications and Asserts With the Conte3t 7enu

"our test cases #ill also need to chec' the properties of a #eb,page- This re0uires assert  and verify commands- We #ont describe thespecifics of these commands here that is in the chapter on Selenium !ommands ) DSeleneseE- Here #ell simply describe ho# to add themto your test case-

With Selenium,I(& recording+ go to the bro#ser displaying your test application and right clic' any#here on the page- "ou #ill see aconte%t menu sho#ing verify andGor assert  commands-

The first time you use Selenium+ there may only be one Selenium command listed- As you use the I(& ho#e.er+ you #ill find additionalcommands #ill 0uic'ly be added to this menu- Selenium,I(& #ill attempt to predict #hat command+ along #ith the parameters+ you #illneed for a selected 5I element on the current #eb,page-

ets see ho# this #or's- 6pen a #eb,page of your choosing and select a bloc' of te%t on the page- A paragraph or a heading #ill #or' fine-No#+ right,clic' the selected te%t- The conte%t menu should gi.e you a verifye%t&resent  command and the suggested parameter should bethe te%t itself-

Also+ notice the Sho# All A.ailable !ommands menu option- This sho#s many+ many more commands+ again+ along #ith suggestedparameters+ for testing your currently selected 5I element-

Try a fe# more 5I elements- Try right,clic'ing an image+ or a user control li'e a button or a chec'bo%- "ou may need to use Sho# AllA.ailable !ommands to see options other than verifye%t&resent - 6nce you select these other options+ the more commonly used ones #illsho# up on the primary conte%t menu- $or e%ample+ selecting verify'lement&resent  for an image should later cause that command to bea.ailable on the primary conte%t menu the ne%t time you select an image and right,clic'-

Again+ these commands #ill be e%plained in detail in the chapter on Selenium commands- $or no# though+ feel free to use the I(& to recordand select commands into a test case and then run it- "ou can learn a lot about the Selenium commands simply by e%perimenting #ith theI(&-

Page 16: About Sellinum

8/11/2019 About Sellinum

http://slidepdf.com/reader/full/about-sellinum 16/173

,diting

Insert Command

Table ie0

Select the point in your test case #here you #ant to insert the command- To do this+ in the Test !ase Pane+ left,clic' on the line #here you#ant to insert a ne# command- 2ight,clic' and select Insert !ommand the I(& #ill add a blan' line just ahead of the line you selected-No# use the command editing te%t fields to enter your ne# command and its parameters-

Source ie0

Select the point in your test case #here you #ant to insert the command- To do this+ in the Test !ase Pane+ left,clic' bet#een the commands#here you #ant to insert a ne# command+ and enter the HT* tags needed to create a K,column ro# containing the !ommand+ firstparameter ;if one is re0uired by the !ommand<+ and second parameter ;again+ if one is re0uired to locate an element< and thirdparameter;again+ if one is re0uired to ha.e a .alue<- &%ample1

<tr>  <td>Command</td>  <td>target (locator)</td>  <td>Value</td></tr>

Insert Comment

!omments may be added to ma'e your test case more readable- These comments are ignored #hen the test case is run-

!omments may also be used to add .ertical #hite space ;one or more blan' lines< in your tests just create empty comments- An empty

command #ill cause an error during e%ecution an empty comment #ont-

Table ie0

Select the line in your test case #here you #ant to insert the comment- 2ight,clic' and select Insert !omment- No# use the !ommand fieldto enter the comment- "our comment #ill appear in purple te%t-

Page 17: About Sellinum

8/11/2019 About Sellinum

http://slidepdf.com/reader/full/about-sellinum 17/173

Source ie0

Select the point in your test case #here you #ant to insert the comment- Add an HT*,style comment+ i-e-+ <!-- your commenthere -->-

,dit a Command or Comment

Table ie0

Simply select the line to be changed and edit it using the !ommand+ Target+ and 3alue fields-

Source ie0

Since Source .ie# pro.ides the e0ui.alent of a W"SIW"> ;What "ou See is What "ou >et< editor+ simply modify #hich line you #ish) command+ parameter+ or comment-

Opening and Sa'ing a Test Case

i'e most programs+ there are Sa.e and 6pen commands under the $ile menu- Ho#e.er+ Selenium distinguishes bet#een test cases and testsuites- To sa.e your Selenium,I(& tests for later use you can either sa.e the indi.idual test cases+ or sa.e the test suite- If the test cases ofyour test suite ha.e not been sa.ed+ youll be prompted to sa.e them before sa.ing the test suite-

When you open an e%isting test case or suite+ Selenium,I(& displays its Selenium commands in the Test !ase Pane-

*unning Test Cases

The I(& allo#s many options for running your test case- "ou 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 de.eloping+ and you can do a batch run of an entire test suite- &%ecution of test cases is .ery fle%ible inthe I(&-

2un a Test !ase!lic' the 2un button to run the currently displayed test case-

2un a Test Suite!lic' the 2un All button to run all the test cases in the currently loaded test suite-

Stop and StartThe Pause button can be used to stop the test case #hile it is running- The icon of this button then changes to indicate the 2esumebutton- To continue clic' 2esume-

Stop in the *iddle

Page 18: About Sellinum

8/11/2019 About Sellinum

http://slidepdf.com/reader/full/about-sellinum 18/173

"ou can set a brea'point in the test case to cause it to stop on a particular command- This is useful for debugging your test case- To seta brea'point+ select a command+ right,clic'+ and from the conte%t menu select Toggle Brea'point-

Start from the *iddle"ou can tell the I(& to begin running from a specific command in the middle of the test case- This also is used for debugging- To set astartpoint+ select a command+ right,clic'+ and from the conte%t menu select SetG!lear Start Point-

2un Any Single !ommand(ouble,clic' any single command to run it by itself- This is useful #hen #riting a single command- It lets you immediately test acommand you are constructing+ #hen you are not sure if it is correct- "ou can double,clic' it to see if it runs correctly- This is alsoa.ailable from the conte%t menu-

@sing Base @*6 to *un Test Cases in +ifferent +omains

The (ase )*+ field at the top of the Selenium,I(& #indo# is .ery useful for allo#ing test cases to be run across different domains-Suppose that a site named http1GGne#s-portal-com had an in,house beta site named http1GGbeta-ne#s-portal-com- Any test cases for these sitesthat begin #ith an open statement should specify a relative )*+ as the argument to open rather than an absolute )*+ ;one starting #ith a

protocol such as http1 or https1<- Selenium,I(& #ill then create an absolute 52 by appending the open commands argument onto the endof the .alue of Base 52- $or e%ample+ the test case belo# #ould be run against http1GGne#s-portal-comGabout-html1 

This same test case #ith a modified Base 52 setting #ould be run against http1GGbeta-ne#s-portal-comGabout-html1 

Selenium Commands > Selenese

Selenium commands+ often called selenese+ are the set of commands that run your tests- A se0uence of these commands is a test script - Here#e e%plain those commands in detail+ and #e present the many choices you ha.e in testing your #eb application #hen using Selenium-

Selenium pro.ides a rich set of commands for fully testing your #eb,app in .irtually any #ay you can imagine- The command set is oftencalled selenese- These commands essentially create a testing language-

In selenese+ one can test the e%istence of 5I elements based on their HT* 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 Selenium commands support testing of #indo# si/e+mouse position+ alerts+ Aja% functionality+ pop up #indo#s+ e.ent handling+ and many other #eb,application features- The !ommand2eference lists all the a.ailable commands-

A command tells Selenium #hat to do- Selenium commands come in three Dfla.orsE1 Actions+ Accessors+ and Assertions-

Page 19: About Sellinum

8/11/2019 About Sellinum

http://slidepdf.com/reader/full/about-sellinum 19/173

• Actions are commands that generally manipulate the state of the application- They do things li'e Dclic' this lin'E and Dselect that

optionE- If an Action fails+ or has an error+ the e%ecution of the current test is stopped-

*any Actions can be called #ith the DAndWaitE suffi%+ e-g- Dclic'AndWaitE- This suffi% tells Selenium that the action #ill cause thebro#ser to ma'e a call to the ser.er+ and that Selenium should #ait for a ne# page to load-

• Accessors e%amine the state of the application and store the results in .ariables+ e-g- DstoreTitleE- They are also used to automatically

generate Assertions-

• Assertions are li'e Accessors+ but they .erify that the state of the application conforms to #hat is e%pected- &%amples include Dma'e

sure the page title is OE and D.erify that this chec'bo% is chec'edE-

All Selenium Assertions can be used in K modes1 DassertE+ D.erifyE+ and E #ait$orE- $or e%ample+ you can DassertTe%tE+ D.erifyTe%tEand D#ait$orTe%tE- When an DassertE fails+ the test is aborted- When a D.erifyE fails+ the test #ill continue e%ecution+ logging thefailure- This allo#s a single DassertE to ensure that the application is on the correct page+ follo#ed by a bunch of D.erifyE assertions totest form field .alues+ labels+ etc-

D#ait$orE commands #ait for some condition to become true ;#hich can be useful for testing Aja% applications<- They #ill succeed

immediately if the condition is already true- Ho#e.er+ they #ill fail and halt the test if the condition does not become true #ithin thecurrent timeout setting ;see the setTimeout action belo#<-

Script Synta3

Selenium commands are simple+ they consist of the command and t#o parameters- $or e%ample1

.erifyTe%t GGdi.GGaR7

ogin

The parameters are not al#ays re0uired it depends on the command- In some cases both are re0uired+ in others one parameter is re0uired+

and in still others the command may ta'e no parameters at all- Here are a couple more e%amples1goBac'AndWait

.erifyTe%tPresent Welcometo *yHomePage

type idphone

;LLL<===,8==

type idaddre

Page 20: About Sellinum

8/11/2019 About Sellinum

http://slidepdf.com/reader/full/about-sellinum 20/173

ssF

The command reference describes the parameter re0uirements for each command-

Parameters .ary+ ho#e.er they are typically1

• a locator for identifying a 5I element #ithin a page-

a te%t pattern for .erifying or asserting e%pected page content• a te%t pattern or a selenium .ariable for entering te%t in an input field or for selecting an option from an option list-

ocators+ te%t patterns+ selenium .ariables+ and the commands themsel.es are described in considerable detail in the section on Selenium!ommands-

Selenium scripts that #ill be run from Selenium,I(& #ill be be stored in an HT* te%t file format- This consists of an HT* table #iththree columns- The first column identifies the Selenium command+ the second is a target+ and the final column contains a .alue- The secondand third columns may not re0uire .alues depending on the chosen Selenium command+ but they should be present- &ach table ro#represents a ne# Selenium command- Here is an e%ample of a test that opens a page+ asserts the page title and then .erifies some content onthe page1

<table>  <tr><td>open</td><td>/download/</td><td></td></tr>  <tr><td>assertTitle</td><td></td><td>Downloads</td></tr>  <tr><td>eriyTe"t</td><td>//h#</td><td>Downloads</td></tr></table>

2endered as a table in a bro#ser this #ould loo' li'e the follo#ing1

open Gdo#nloadG

 

assertTitle (o#nloads

.erifyTe%t GGh7 (o#nloadsThe Selenese HT* synta% can be used to #rite and run tests #ithout re0uiring 'no#ledge of a programming language- With a basic'no#ledge of selenese and Selenium,I(& you can 0uic'ly produce and run testcases-

Test Suites

A test suite is a collection of tests- 6ften one #ill run all the tests in a test suite as one continuous batch,job-

When using Selenium,I(&+ test suites also can be defined using a simple HT* file- The synta% again is simple- An HT* table defines alist of tests #here each ro# defines the filesystem path to each test- An e%ample tells it all-

Page 21: About Sellinum

8/11/2019 About Sellinum

http://slidepdf.com/reader/full/about-sellinum 21/173

<html><head><title>Test $uite %unction Tests - &riority '</title></head><body><table>  <tr><td><b>$uite Tests</b></td></tr>

  <tr><td><a hre*+/,ogin+html*>,ogin</a></td></tr>  <tr><td><a hre*+/$earchValues+html*>Test $earching or Values</a></td></tr>  <tr><td><a hre*+/$aeValues+html*>Test $ae</a></td></tr></table></body></html>

A file similar to this #ould allo# running the tests all at once+ one after another+ from the Selenium,I(&-

Test suites can also be maintained #hen using Selenium,2!- This is done .ia programming and can be done a number of #ays- !ommonly:unit is used to maintain a test suite if one is using Selenium,2! #ith :a.a- Additionally+ if ! is the chosen language+ Nunit could be

employed- If using an interpreted language li'e Python #ith Selenium,2! then some simple programming #ould be in.ol.ed in setting up atest suite- Since the #hole reason for using Selenium,2! is to ma'e use of programming logic for your testing this usually isnt a problem-

Commonly @sed Selenium Commands

To conclude our introduction of Selenium+ #ell sho# you a fe# typical Selenium commands- These are probably the most commonly usedcommands for building tests-

openopens a page using a 52-

clic'Gclic'AndWait

performs a clic' operation+ and optionally #aits for a ne# page to load-.erifyTitleGassertTitle

.erifies an e%pected page title-.erifyTe%tPresent

.erifies e%pected te%t is some#here on the page-.erify&lementPresent

.erifies an e%pected 5I element+ as defined by its HT* tag+ is present on the page-.erifyTe%t

.erifies e%pected te%t and its corresponding HT* tag are present on the page-.erifyTable

Page 22: About Sellinum

8/11/2019 About Sellinum

http://slidepdf.com/reader/full/about-sellinum 22/173

.erifies a tables e%pected contents-#ait$orPageTooad

pauses e%ecution until an e%pected ne# page loads- !alled automatically #hen clic'AndWait is used-#ait$or&lementPresent

pauses e%ecution until an e%pected 5I element+ as defined by its HT* tag+ is present on the page-

erifying age ,lements

3erifying 5I elements on a #eb page is probably the most common feature of your automated tests- Selenese allo#s multiple #ays ofchec'ing for 5I elements- It is important that you understand these different methods because these methods define #hat you are actuallytesting-

$or e%ample+ #ill you test that---

F- an element is present some#here on the page?7- specific te%t is some#here on the page?

K- specific te%t is at a specific location on the page?$or e%ample+ if you are testing a te%t heading+ the te%t and its position at the top of the page are probably rele.ant for your test- If+ ho#e.er+you are testing for the e%istence of an image on the home page+ and the #eb designers fre0uently change the specific image file along #ithits position on the page+ then you only #ant to test that an image ;as opposed to the specific image file< e%ists somewhere on the page-

Assertion or erification?

!hoosing bet#een DassertE and D.erifyE comes do#n to con.enience and management of failures- Theres .ery little point chec'ing that thefirst paragraph on the page is the correct one if your test has already failed #hen chec'ing that the bro#ser is displaying the e%pected page-

If youre not on the correct page+ youll probably #ant to abort your test case so that you can in.estigate the cause and fi% the issue;s<promptly- 6n the other hand+ you may #ant to chec' many attributes of a page #ithout aborting the test case on the first failure as this #illallo# you to re.ie# all failures on the page and ta'e the appropriate action- &ffecti.ely an DassertE #ill fail the test and abort the current testcase+ #hereas a D.erifyE #ill 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 #ith an DassertE follo#ed by one or more D.erifyEtest commands- An e%ample follo#s1

Command Target alue

open do0nload

assertTitle +o0nloads

Page 23: About Sellinum

8/11/2019 About Sellinum

http://slidepdf.com/reader/full/about-sellinum 23/173

Command Target alue

'erifyTe3t h# +o0nloads

assertTable )&#&) SeleniumI+,

'erifyTable )&#&# Dune 45

#118'erifyTable )&#&4 )&1 beta #

The abo'e e3ample first opens a page and then asserts that the correct page is loaded by comparing the title 0ith the e3pected'alue& Only if this passes 0ill the follo0ing command run and 'erify that the te3t is present in the e3pected location& The test casethen asserts the first column in the second ro0 of the first table contains the e3pected 'alue5 and only if this passed 0ill theremaining cells in that ro0 be 'erified&

'erifyTe3tresent

The command eriyTe"t&resent is used to .erify specific te%t e%ists somewhere on the page- It ta'es a single argument)the te%t

pattern to be .erified- $or e%ample1

Command Target alue

'erifyTe3tresent

7ar%eting Analysis

 

This 0ould cause Selenium to search for5 and 'erify5 that the te3t string 7ar%eting Analysis appears some0here on the pagecurrently being tested& @se eriyTe"t&resent 0hen you are interested in only the te3t itself being present on the page& +o not

use this 0hen you also need to test 0here the te3t occurs on the page&

'erify,lementresent5se this command #hen you must test for the presence of a specific 5I element+ rather than its content- This .erification does not chec' thete%t+ only the HT* tag- 6ne common use is to chec' for the presence of an image-

Command Target alue

'erify,lementresent

 di'p img

 

This command 'erifies that an image5 specified by the e3istence of an EimgF HT76 tag5 is present on the page5 and that it follo0s aEdi'F tag and a EpF tag& The first $and only( parameter is a locator for telling the Selenese command ho0 to find the element&6ocators are e3plained in the ne3t section&

Page 24: About Sellinum

8/11/2019 About Sellinum

http://slidepdf.com/reader/full/about-sellinum 24/173

eriylement&resent can be used to chec' the e%istence of any HT* tag #ithin the page- "ou can chec' the e%istence of lin's+paragraphs+ di.isions Udi.Q+ etc- Here are a fe# more e%amples-

Command Target alue

'erify,lementresent

 di'p

'erify,lementresent

 di'a

'erify,lementresent

idG6ogin

'erify,lementresent

lin%G.oto7ar%eting*esearch

 

'erify,lementresent

 a#

'erify,lementresent

 headtitle

 

These e3amples illustrate the 'ariety of 0ays a @I element may be tested& Again5 locators are e3plained in the ne3t section&

'erifyTe3t

5se eriyTe"t #hen both the te%t and its 5I element must be tested- eriyTe"t must use a locator- If you choose an &ath or #-  locator+ you can .erify that specific te%t appears at a specific location on the page relati.e to other 5I components on the page-

Command Target alue

'erifyTe3t table trtddi'p

This is myte3t and itoccursright afterthe di'inside thetable&

Page 25: About Sellinum

8/11/2019 About Sellinum

http://slidepdf.com/reader/full/about-sellinum 25/173

6ocating ,lements

$or many Selenium commands+ a target is re0uired- This target identifies an element in the content of the #eb application+ and consists of thelocation strategy follo#ed by the location in the format locatorTypelocation- The locator type can be omitted in many cases- The.arious locator types are e%plained belo# #ith e%amples for each-

6ocating by Identifier

This is probably the most common method of locating elements and is the catch,all default #hen no recogni/ed locator type is used- Withthis strategy+ the first element #ith the id attribute .alue matching the location #ill be used- If no element has a matching id attribute+ thenthe first element #ith a name attribute matching the location #ill be used-

$or instance+ your page source could ha.e id and name attributes as follo#s1

'#.01234

<html> <body>  <orm id*login%orm*>  <input name*username* type*te"t* />  <input name*password* type*password* />  <input name*continue* type*submit* alue*,ogin* />  </orm> </body><html>

The follo#ing locator strategies #ould return the elements from the HT* snippet abo.e indicated by line number1

• identiierlogin%orm ;K<

• identiierpassword ;L<

• identiiercontinue ;=<

• continue ;=<

Since the identiier type of locator is the default+ the identiier in the first three e%amples abo.e is not necessary-

6ocating by Id

This type of locator is more limited than the identifier locator type+ but also more e%plicit- 5se this #hen you 'no# an elements id attribute-

 ' # .

 <html>  <body>  <orm id*login%orm*>

Page 26: About Sellinum

8/11/2019 About Sellinum

http://slidepdf.com/reader/full/about-sellinum 26/173

  0 1 2 3 4'5

  <input name*username* type*te"t* />  <input name*password* type*password* />  <input name*continue* type*submit* alue*,ogin* />  <input name*continue* type*button* alue*Clear* />  </orm>  </body> <html>

• idlogin$orm ;K<

6ocating by Name

The name locator type #ill locate the first element #ith a matching name attribute- If multiple elements ha.e the same .alue for a nameattribute+ then you can use filters to further refine your location strategy- The default filter type is .alue ;matching the .alue attribute<-

 ' # .

  0 1 2 3 4'5

 <html>  <body>  <orm id*login%orm*>

  <input name*username* type*te"t* />  <input name*password* type*password* />  <input name*continue* type*submit* alue*,ogin* />  <input name*continue* type*button* alue*Clear* />  </orm> </body> <html>

• nameusername ;9<

• namecontinue alueClear ;<

namecontinue Clear ;<• namecontinue typebutton ;<

Note

5nli'e some types of OPath and (6* locators+ the three types of locators abo.e allo# Selenium to test a 5I element independent of itslocation on the page- So if the page structure and organi/ation is altered+ the test #ill still pass- "ou may or may not #ant to also test #hetherthe page structure changes- In the case #here #eb designers fre0uently alter the page+ but its functionality must be regression tested+ testing.ia id and name attributes+ or really .ia any HT* property+ becomes .ery important-

Page 27: About Sellinum

8/11/2019 About Sellinum

http://slidepdf.com/reader/full/about-sellinum 27/173

6ocating by Jath

OPath is the language used for locating nodes in an O* document- As HT* can be an implementation of O* ;OHT*<+ Seleniumusers can le.erage this po#erful language to target elements in their #eb applications- OPath e%tends beyond ;as #ell as supporting< thesimple methods of locating by id or name attributes+ and opens up all sorts of ne# possibilities such as locating the third chec'bo% on thepage-

6ne of the main reasons for using OPath is #hen you dont ha.e a suitable id or name attribute for the element you #ish to locate- "ou canuse OPath to either locate the element in absolute terms ;not ad.ised<+ or relati.e to an element that does ha.e an id or name attribute- OPathlocators can also be used to specify elements .ia attributes other than id and name-

Absolute OPaths contain the location of all elements from the root ;html< and as a result are li'ely to fail #ith only the slightest adjustmentto the application- By finding a nearby element #ith an id or name attribute ;ideally a parent element< you can locate your target elementbased on the relationship- This is much less li'ely to change and can ma'e your tests more robust-

Since only "path locators start #ith DGGE+ it is not necessary to include the "path label #hen specifying an OPath locator-

 ' #

 .  0 1 2 3 4'5

 <html>  <body>

  <orm id*login%orm*>  <input name*username* type*te"t* />  <input name*password* type*password* />  <input name*continue* type*submit* alue*,ogin* />  <input name*continue* type*button* alue*Clear* />  </orm> </body> <html>

• %pathGhtmlGbodyGformRF ;K< , Absolute path /would break if the H+ was changed only slightly0 

• //orm6'7 ;K< , 1irst form element in the H+ 

• "path//orm68id9login%orm97 ;K< , he form element with attribute named id and the value login1orm  

• "path//orm6input/8name9username97 ;K< , 1irst form element with an input child element with attribute named

name and the value username 

• //input68name9username97 ;9< , 1irst input element with attribute named name and the value username 

• //orm68id9login%orm97/input6'7 ;9< , 1irst input child element of the form element with attribute named id and the

value login1orm 

• //input68name9continue9768type9button97 ;< , 4nput with attribute named name and the value continue and

attribute named type and the value button 

• //orm68id9login%orm97/input67 ;< , 1ourth input child element of the form element with attribute named id and

Page 28: About Sellinum

8/11/2019 About Sellinum

http://slidepdf.com/reader/full/about-sellinum 28/173

value login1orm 

These e%amples co.er some basics+ but in order to learn more+ the follo#ing references are recommended1

• WKSchools OPath Tutorial 

• WK! OPath 2ecommendation 

There are also a couple of .ery useful $irefo% Add,ons that can assist in disco.ering the OPath of an element1• OPath !hec'er , suggests OPath and can be used to test OPath results-

• $irebug , OPath suggestions are just one of the many po#erful features of this .ery useful add,on-

6ocating Hyperlin%s by 6in% Te3t

This is a simple method of locating a hyperlin' in your #eb page by using the te%t of the lin'- If t#o lin's #ith the same te%t are present+then the first match #ill be used-

'#.012

<html> <body>  <p>:re you sure you want to do this;</p>  <a hre*continue+html*>Continue</a>  <a hre*cancel+html*>Cancel</a></body><html>

• lin'!ontinue ;9<

• linCancel ;L<

6ocating by +O7

The (ocument 6bject *odel represents an HT* document and can be accessed using :a.aScript- This location strategy ta'es :a.aScriptthat e.aluates to an element on the page+ #hich can be simply the elements location using the hierarchical dotted notation-

Since only dom locators start #ith DdocumentE+ it is not necessary to include the dom label #hen specifying a (6* locator-

 ' # .  0 1

 <html>  <body>  <orm id*login%orm*>  <input name*username* type*te"t* />  <input name*password* type*password* />  <input name*continue* type*submit* alue*,ogin* />

Page 29: About Sellinum

8/11/2019 About Sellinum

http://slidepdf.com/reader/full/about-sellinum 29/173

 2 3 4'5

  <input name*continue* type*button* alue*Clear* />  </orm> </body> <html>

• domdocument-get&lementById;Vlogin$ormV< ;K<

• domdocument+orms69login%orm97 ;K<• domdocument+orms657 ;K<

• document+orms657+username ;9<

• document+orms657+elements69username97 ;9<

• document+orms657+elements657 ;9<

• document+orms657+elements6.7 ;<

"ou can use Selenium itself as #ell as other sites and e%tensions to e%plore the (6* of your #eb application- A good reference e%ists onWKSchools-

6ocating by CSS

!SS ;!ascading Style Sheets< is a language for describing the rendering of HT* and O* documents- !SS uses Selectors for bindingstyle properties to elements in the document- These Selectors can be used by Selenium as another locating strategy-

 ' # .  0 1 2

 3 4'5

 <html>  <body>  <orm id*login%orm*>  <input class*re=uired* name*username* type*te"t* />  <input class*re=uired passield* name*password* type*password* />  <input name*continue* type*submit* alue*,ogin* />  <input name*continue* type*button* alue*Clear* />

  </orm> </body> <html>

• cssformlogin$orm ;K<

• cssinput6name*username*7 ;9<

• cssinput+re=uired6type*te"t*7 ;9<

• cssinput+passield ;L<

• csslogin%orm input6type*button*7 ;<

Page 30: About Sellinum

8/11/2019 About Sellinum

http://slidepdf.com/reader/full/about-sellinum 30/173

• csslogin%orm input?nth-child(#) ;L<

$or more information about !SS Selectors+ the best place to go is the WK! publication- "oull find additional references there-

Note

*ost e%perienced Selenium users recommend !SS as their locating strategy of choice as its considerably faster than OPath and can find the

most complicated objects in an intrinsic HT* document-

Implicit 6ocators

"ou can choose to omit the locator type in the follo#ing situations1

• ocators #ithout an e%plicitly defined locator strategy #ill default to using the identifier locator strategy- See ocating by

Identifier-

• ocators starting #ith DGGE #ill use the OPath locator strategy- See ocating by OPath-

• ocators starting #ith DdocumentE #ill use the (6* locator strategy- See ocating by (6* 

7atching Te3t atterns

i'e locators+ patterns are a type of parameter fre0uently re0uired by Selenese commands- &%amples of commands #hich re0uire patternsare 'erifyTe3tresent+ 'erifyTitle+ 'erifyAlert+ assertConfirmation + 'erifyTe3t+ and 'erifyrompt- And as has been mentioned abo.e+lin' locators can utili/e a pattern- Patterns allo# you to describe+ .ia the use of special characters+ #hat te%t is e%pected rather than ha.ing tospecify that te%t e%actly-

There are three types of patterns1 globbing+ regular e%pressions+ and e%act -

.lobbing atterns*ost people are familiar #ith globbing as it is utili/ed in filename e%pansion at a (6S or 5ni%Ginu% command line such as ls @+c- Inthis case+ globbing is used to display all the files ending #ith a +c e%tension that e%ist in the current directory- >lobbing is fairly limited-6nly t#o special characters are supported in the Selenium implementation1

9 #hich translates to Dmatch anything+E i-e-+ nothing+ a single character+ or many characters-

 ;character class< #hich translates to Dmatch any single character found inside the s0uare brac'ets-E A dash ;hyphen< can beused as a shorthand to specify a range of characters ;#hich are contiguous in the AS!II character set<- A fe# e%amples #ill ma'ethe functionality of a character class clear1

Page 31: About Sellinum

8/11/2019 About Sellinum

http://slidepdf.com/reader/full/about-sellinum 31/173

6aeiou7 matches any lo#ercase .o#el

65-47 matches any digit

6a-A:-B5-47 matches any alphanumeric character

In most other conte%ts+ globbing includes a third special character+ the ?- Ho#e.er+ Selenium globbing patterns only support the asteris' andcharacter class-

To specify a globbing pattern parameter for a Selenese command+ you can prefi% the pattern #ith a globK label- Ho#e.er+ because globbingpatterns are the default+ you can also omit the label and specify just the pattern itself-

Belo# is an e%ample of t#o commands that use globbing patterns- The actual lin' te%t on the page being tested #as D$ilmGTele.ision(epartmentE by using a pattern rather than the e%act te%t+ the clic% command #ill #or' e.en if the lin' te%t is changed to D$ilm MTele.ision (epartmentE or D$ilm and Tele.ision (epartmentE- The glob patterns asteris' #ill match Danything or nothingE bet#een the#ord D$ilmE and the #ord DTele.isionE-

Command Target alueclic% lin%GglobK

2ilm9Tele'ision+epartment

 

'erifyTitle globK92ilm9Tele'ision9

 

The actual title of the page reached by clic%ing on the lin% 0as +e AnLa 2ilm And Tele'ision +epartment - 7enu& By using a

pattern rather than the e3act te3t5 the eriyTitle 0ill pass as long as the t0o 0ords 2ilm and Tele'ision appear $in thatorder( any0here in the page"s title& 2or e3ample5 if the page"s o0ner should shorten the title to !ust 2ilm M Tele'ision +epartment5the test 0ould still pass& @sing a pattern for both a lin% and a simple test that the lin% 0or%ed $such as the eriyTitle abo'e

does( can greatly reduce the maintenance for such test cases&

*egular ,3pression atterns

 *egular e%pression patterns are the most po#erful of the three types of patterns that Selenese supports- 2egular e%pressions are alsosupported by most high,le.el programming languages+ many te%t editors+ and a host of tools+ including the inu%G5ni% command,lineutilities grep+ sed+ and a0%- In Selenese+ regular e%pression patterns allo# a user to perform many tas's that #ould be .ery difficult

Page 32: About Sellinum

8/11/2019 About Sellinum

http://slidepdf.com/reader/full/about-sellinum 32/173

other#ise- $or e%ample+ suppose your test needed to ensure that a particular table cell contained nothing but a number- rege"p? 65-47 is a simple pattern that #ill match a decimal number of any length-

Whereas Selenese globbing patterns support only the 9 and  ;character class< features+ Selenese regular e%pression patterns offer the same#ide array of special characters that e%ist in :a.aScript- Belo# are a subset of those special characters1

ATT,*N 7ATCH

- any singlecharacter

R characterclass1 anysinglecharacter thatappearsinside thebrac'ets

0uantifier1 8or more ofthe precedingcharacter ;orgroup<

J 0uantifier1 For more ofthe precedingcharacter ;orgroup<

? 0uantifier1 8or F of theprecedingcharacter ;orgroup<

F+LX 0uantifier1 Fthrough L ofthe precedingcharacter ;or

Page 33: About Sellinum

8/11/2019 About Sellinum

http://slidepdf.com/reader/full/about-sellinum 33/173

ATT,*N 7ATCH

group<

Y alternation1thecharacterGgro

up on the leftor thecharacterGgroup on theright

; < grouping1often used#ithalternationandGor

0uantifier2egular e%pression patterns in Selenese need to be prefi%ed #ith either rege"p? or rege"pi?- The former is case,sensiti.e the latter iscase,insensiti.e-

A fe# e%amples #ill help clarify ho# regular e%pression patterns can be used #ith Selenese commands- The first one uses #hat is probablythe most commonly used regular e%pression pattern) &9 ;Ddot starE<- This t#o,character se0uence can be translated as D8 or more occurrencesof any characterE or more simply+ Danything or nothing-E It is the e0ui.alent of the one,character globbing pattern 9 ;a single asteris'<-

Command Target alue

clic% lin%Grege3pK2ilm&9Te

le'ision+epartment

 

'erifyTitle rege3pK&92ilm&9Tele'ision&9

 

The e3ample abo'e is functionally eui'alent to the earlier e3ample that used globbing patterns for this same test& The onlydifferences are the prefi3 $rege3pK instead of globK( and the anything or nothing pattern $&9 instead of !ust 9(&

The more comple% e%ample belo# tests that the "ahooZ Weather page for Anchorage+ Alas'a contains info on the sunrise time1

Page 34: About Sellinum

8/11/2019 About Sellinum

http://slidepdf.com/reader/full/about-sellinum 34/173

Command Target alue

open http1GG#eather-yahoo-comGforecastG5SA88F7-html

 

'erifyTe3tresen

t

rege3pKSunriseK 91-

=)5#PK1-=#Papm

 

6et"s e3amine the regular e3pression abo'e one part at a timeK

$unrise? @

ThestringSunriseK ollowedby 5 ormorespaces

65-47'E#F

' or #digits(or thehour othe day)

? Thecharacter K (nospecial

charactersinoled)

65-47#F

# digits(or theminutes)ollowedby a

Page 35: About Sellinum

8/11/2019 About Sellinum

http://slidepdf.com/reader/full/about-sellinum 35/173

space

6ap7m GaH orGpHollowedby GmH

(am orpm)

Exact Patterns

The e3act type of Selenium pattern is of marginal usefulness- It uses no special characters at all- So+ if you needed to loo' for an actualasteris' character ;#hich is special for both globbing and regular e%pression patterns<+ the e3act pattern #ould be one #ay to do that- $ore%ample+ if you #anted to select an item labeled D2eal E from a dropdo#n+ the follo#ing code might #or' or it might not- The asteris' inthe glob?Ieal @ pattern #ill match anything or nothing- So+ if there #as an earlier select option labeled D2eal Numbers+E it #ould be theoption selected rather than the D2eal E option-

select GGselect glob12eal

In order to ensure that the D2eal E item #ould be selected+ the e"act? prefi% could be used to create an e3act pattern as sho#n belo#1

select GGselect e%act12eal

But the same effect could be achie.ed .ia escaping the asteris' in a regular e%pression pattern1

select GGselect rege%p12eal [

Its rather unli'ely that most testers #ill e.er need to loo' for an asteris' or a set of s0uare brac'ets #ith characters inside them ;thecharacter class for globbing patterns<- Thus+ globbing patterns and regular e%pression patterns are sufficient for the .ast majority of us-

The AndWait Commands

The difference bet#een a command and its And$ait  alternati.e is that the regular command ;e-g- click < #ill do the action and continue #iththe follo#ing command as fast as it can+ #hile the And$ait  alternati.e ;e-g- clickAnd$ait < tells Selenium to 0ait for the page to load afterthe action has been done-

The And$ait  alternati.e is al#ays used #hen the action causes the bro#ser to na.igate to another page or reload the present one-

Page 36: About Sellinum

8/11/2019 About Sellinum

http://slidepdf.com/reader/full/about-sellinum 36/173

Be a#are+ if you use an And$ait  command for an action that does not trigger a na.igationGrefresh+ your test #ill fail- This happens becauseSelenium #ill reach the And$ait s timeout #ithout seeing any na.igation or refresh being made+ causing Selenium to raise a timeoute%ception-

The 0ait2or Commands in ADAJ applications

In A:AO dri.en #eb applications+ data is retrie.ed from ser.er #ithout refreshing the page- 5sing and$ait  commands #ill not #or' as thepage is not actually refreshed- Pausing the test e%ecution for a certain period of time is also not a good approach as #eb element mightappear later or earlier than the stipulated period depending on the systems responsi.eness+ load or other uncontrolled factors of the moment+leading to test failures- The best approach #ould be to #ait for the needed element in a dynamic period and then continue the e%ecution assoon as the element is found-

This is done using wait1or commands+ as wait1or'lement&resent  or wait1or5isible + #hich #ait dynamically+ chec'ing for the desiredcondition e.ery second and continuing to the ne%t command in the script as soon as the condition is met-

Seuence of ,'aluation and 2lo0 ControlWhen a script runs+ it simply runs in se0uence+ one command after another-

Selenese+ by itself+ does not support condition statements ;if,else+ etc-< or iteration ;for+ #hile+ etc-<- *any useful tests can be conducted#ithout flo# control- Ho#e.er+ for a functional test of dynamic content+ possibly in.ol.ing multiple pages+ programming logic is oftenneeded-

When flo# control is needed+ there are three options1

F- 2un the script using Selenium,2! and a client library such as :a.a or PHP to utili/e the programming languages flo# controlfeatures-

7- 2un a small :a.aScript snippet from #ithin the script using the store&.al command-

K- Install the goto\sel\ide-js e%tension-

*ost testers #ill e%port the test script into a programming language file that uses the Selenium,2! API ;see the Selenium,I(& chapter<-Ho#e.er+ some organi/ations prefer to run their scripts from Selenium,I(& #hene.er possible ;for instance+ #hen they ha.e many junior,le.el people running tests for them+ or #hen programming s'ills are lac'ing<- If this is your case+ consider a :a.aScript snippet or thegoto\sel\ide-js e%tension-

Store Commands and Selenium ariables

"ou can use Selenium .ariables to store constants at the beginning of a script- Also+ #hen combined #ith a data,dri.en test design ;discussed

Page 37: About Sellinum

8/11/2019 About Sellinum

http://slidepdf.com/reader/full/about-sellinum 37/173

in a later section<+ Selenium .ariables can be used to store .alues passed to your test program from the command,line+ from anotherprogram+ 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 .alue in a selenium.ariable- It ta'es t#o parameters+ the te%t .alue to be stored and a selenium .ariable- 5se the standard .ariable naming con.entions of onlyalphanumeric characters #hen choosing a name for your .ariable-

Command Target aluestore paul]mysite-org userName

6ater in your script5 you"ll 0ant to use the stored 'alue of your 'ariable& To access the 'alue of a 'ariable5 enclose the 'ariable incurly brac%ets $P( and precede it 0ith a dollar sign li%e this&

Command Target alue

'erifyTe3t di'p

A common use of 'ariables is for storing input for an input field&

Command Target alue

type idGlogin

Selenium 'ariables can be used in either the first or second parameter and are interpreted by Selenium prior to any other operationsperformed by the command& A Selenium 'ariable may also be used 0ithin a locator e3pression&

An e0ui.alent store command e%ists for each .erify and assert command- Here are a couple more commonly used store commands-

store,lementresent

This corresponds to .erify&lementPresent- It simply stores a boolean .alue)EtrueE or DfalseE)depending on #hether the 5I element is found-

storeTe3t

StoreTe%t corresponds to .erifyTe%t- It uses a locater to identify specific page te%t- The te%t+ if found+ is stored in the .ariable- StoreTe%t canbe used to e%tract te%t from the page being tested-

store,'al

This command ta'es a script as its first parameter- &mbedding :a.aScript #ithin Selenese is co.ered in the ne%t section- Store&.al allo#s thetest to store the result of running the script in a .ariable-

Page 38: About Sellinum

8/11/2019 About Sellinum

http://slidepdf.com/reader/full/about-sellinum 38/173

Da'aScript and Selenese arameters

:a.aScript can be used #ith t#o types of Selenese parameters1 script and non,script ;usually e%pressions<- In most cases+ youll #ant toaccess andGor manipulate a test case .ariable inside the :a.aScript snippet used as a Selenese parameter- All .ariables created in your testcase are stored in a :a.aScript associative array- An associati.e array has string inde%es rather than se0uential numeric inde%es- Theassociati.e array containing your test cases .ariables is named storedars- Whene.er you #ish to access or manipulate a .ariable #ithin a

:a.aScript snippet+ you must refer to it as storedarsQyourariableName"-

Da'aScript @sage 0ith Script arameters

Se.eral Selenese commands specify a script parameter including assert,'al+ 'erify,'al+ store,'al+ and 0ait2or,'al- These parametersre0uire no special synta%- A Selenium,I(& user #ould simply place a snippet of :a.aScript code into the appropriate field+ normally theTarget field ;because a script parameter is normally the first or only parameter<-

The e%ample belo# illustrates ho# a :a.aScript snippet can be used to perform a simple numerical calculation1

Command Target alue

store )1 hitsstoreJpathCount

 bloc%uote bloc%uotes

store,'al storedarsQhits"-storedarsQbloc%uotes"

paragraphs

This ne3t e3ample illustrates ho0 a Da'aScript snippet can include calls to methods5 in this case the Da'aScript String ob!ect"s

toJpperCase method and to,owerCase method&Command Target alue

store ,dithWharton

name

store,'al storedarsQname"&to@pperCase$(

uc

store,'al storedarsQname"&to6o

lc

Page 39: About Sellinum

8/11/2019 About Sellinum

http://slidepdf.com/reader/full/about-sellinum 39/173

Command Target alue

0erCase$(

Da'aScript @sage 0ith Non-Script arameters

:a.aScript can also be used to help generate .alues for parameters+ e.en #hen the parameter is not specified to be of type script- Ho#e.er+

in this case+ special synta% is re0uired)the :a.aScript snippet must be enclosed inside curly braces and preceded by the label Kaascript+as in Kaascript @yourCodeLere@F- Belo# is an e%ample in #hich the type commands second parameter alue is generated.ia :a.aScript code using this special synta%1

Command Target alue

store leagueofnations

searchString

type !a'ascriptstor

edarsQsearchString"&to@pperCase$(P

echo - The Selenese rint Command

Selenese has a simple command that allo#s you to print te%t to your tests output- This is useful for pro.iding informational progress notes inyour test #hich display on the console as your test is running- These notes also can be used to pro.ide conte%t #ithin your test result reports+#hich can be useful for finding #here a defect e%ists on a page in the e.ent your test finds a problem- $inally+ echo statements can be used toprint the contents of Selenium .ariables-

Command Target alue

echo Testingpagefooterno0&

 

echo @sername is

Page 40: About Sellinum

8/11/2019 About Sellinum

http://slidepdf.com/reader/full/about-sellinum 40/173

Alerts5 opups5 and 7ultiple Windo0s

Suppose that you are testing a page that loo's li'e this-

 ' # .

  0 1 2 3 4'5'''#'.''0

'1'2'3'4#5#'###.##0#1#2

#3#4.5.'.#....0.1.2.3

<!DCTM& LTN,><html><head>

  <script type*te"t/Kaascript*>  unction output(resultTe"t)  document+getlementOyPd(9output9)+childQodes657+nodeValueresultTe"tR  F

  unction showSconirm()  ar conirmationconirm(*Chose an option+*)R  i (conirmationtrue)  output(*Conirmed+*)R  F  else  output(*IeKected!*)R

  F  F

  unction showSalert()  alert(*P9m blocing!*)R  output(*:lert is gone+*)R  F  unction showSprompt()  ar response prompt(*hat9s the best web U: tool;*E*$elenium*)R  output(response)R  F  unction openSwindow(windowQame)

  window+open(*newindow+html*EwindowQame)R  F  </script></head><body>

  <input type*button* id*btnConirm* onclic*showSconirm()* alue*$how conirm bo"* />  <input type*button* id*btn:lert* onclic*showSalert()* alue*$how alert* />  <input type*button* id*btn&rompt* onclic*showSprompt()* alue*$how prompt* />  <a hre*newindow+html* id*lnQewindow* target*Sblan*>Qew indow ,in</a>  <input type*button* id*btnQewQamelessindow* onclic*openSwindow()* alue*pen Qameless indow* />

Page 41: About Sellinum

8/11/2019 About Sellinum

http://slidepdf.com/reader/full/about-sellinum 41/173

.45'#.0

  <input type*button* id*btnQewQamedindow* onclic*openSwindow(9Nie9)* alue*pen Qamed indow* />

  <br />  <span id*output*>  </span></body></html>

The user must respond to alertGconfirm bo%es+ as #ell as mo.ing focus to ne#ly opened popup #indo#s- $ortunately+ Selenium can co.er:a.aScript pop,ups-

But before #e begin co.ering alertsGconfirmsGprompts in indi.idual detail+ it is helpful to understand the commonality bet#een them- Alerts+confirmation bo%es and prompts all ha.e .ariations of the follo#ing

Command +escription

assert2oo$ pattern( thro0serror if pattern doesn"tmatch thete3t of thepop-up

assert2ooresent thro0serror if pop-up is nota'ailable

assert2ooNotrese

nt

thro0s

error if anypop-up ispresent

store2oo$variable( stores thete3t of thepop-up in a'ariable

store2ooresent$va

riable(stores thete3t of the

Page 42: About Sellinum

8/11/2019 About Sellinum

http://slidepdf.com/reader/full/about-sellinum 42/173

Page 43: About Sellinum

8/11/2019 About Sellinum

http://slidepdf.com/reader/full/about-sellinum 43/173

the same characteristics as their alert counterparts- Ho#e.er+ by default Selenium #ill select 6 #hen a confirmation pops up- Try recordingclic'ing on the DSho# confirm bo%E button in the sample page+ but clic' on the D!ancelE button in the popup+ then assert the output te%t-"our test may loo' something li'e this1

Command Target alue

open

clic% btnConfirm

 

chooseCancelOnNe3tConfirmation

 

assertConfirmation Choose anoption&

 

'erifyTe3tresent *e!ected

The chooseCancelnQe"tConirmation function tells Selenium that all follo0ing confirmation should return false& It can be

reset by calling chooseO%OnNe3tConfirmation&

"ou may notice that you cannot replay this test+ because Selenium complains that there is an unhandled confirmation- This is because theorder of e.ents Selenium,I(& records causes the clic' and choose!ancel6nNe%t!onfirmation to be put in the #rong order ;it ma'es sense ifyou thin' about it+ Selenium cant 'no# that youre cancelling before you open a confirmation< Simply s#itch these t#o commands andyour test #ill run fine-

+ebugging

(ebugging means finding and fi%ing errors in your test case- This is a normal part of test case de.elopment-

We #ont teach debugging here as most ne# users to Selenium #ill already ha.e some basic e%perience #ith debugging- If this is ne# to

you+ #e recommend you as' one of the de.elopers in your organi/ation-

Brea%points and Startpoints

The Sel,I(& supports the setting of brea'points and the ability to start and stop the running of a test case+ from any point #ithin the test case-That is+ one can run up to a specific command in the middle of the test case and inspect ho# the test case beha.es at that point- To do this+ seta brea'point on the command just before the one to be e%amined-

To set a brea'point+ select a command+ right,clic'+ and from the conte%t menu select oggle (reakpoint - Then clic' the 2un button to runyour test case from the beginning up to the brea'point-

Page 44: About Sellinum

8/11/2019 About Sellinum

http://slidepdf.com/reader/full/about-sellinum 44/173

It is also sometimes useful to run a test case from some#here in the middle to the end of the test case or up to a brea'point that follo#s thestarting point- $or e%ample+ suppose your test case first logs into the #ebsite and then performs a series of tests and you are trying to debugone of those tests- Ho#e.er+ you only need to login once+ but you need to 'eep rerunning your tests as you are de.eloping them- "ou canlogin once+ then run your test case from a startpoint placed after the login portion of your test case- That #ill pre.ent you from ha.ing tomanually logout each time you rerun your test case-

To set a startpoint+ select a command+ right,clic'+ and from the conte%t menu select "et67lear "tart &oint - Then clic' the 2un button toe%ecute the test case beginning at that startpoint-

Stepping Through a Testcase

To e%ecute a test case one command at a time ;Dstep throughE it<+ follo# these steps1

F- Start the test case running #ith the 2un button from the toolbar-

7- Immediately pause the e%ecuting test case #ith the Pause button-

K- 2epeatedly select the Step button-

2ind Button

The $ind button is used to see #hich 5I element on the currently displayed #ebpage ;in the bro#ser< is used in the currently selectedSelenium command- This is useful #hen building a locator for a commands first parameter ;see the section on locators in the Selenium!ommands chapter<- It can be used #ith any command that identifies a 5I element on a #ebpage+ i-e- click + clickAnd$ait + type+ and certain

assert  and verify commands+ among others-

$rom Table .ie#+ select any command that has a locator parameter- !lic' the $ind button- No# loo' on the #ebpage1 There should be abright green rectangle enclosing the element specified by the locator parameter-

age Source for +ebugging

6ften+ #hen debugging a test case+ you simply must loo' at the page source ;the HT* for the #ebpage youre trying to test< to determine aproblem- $irefo% ma'es this easy- Simply right,clic' the #ebpage and select 3ie#,QPage Source- The HT* opens in a separate #indo#-5se its Search feature ;&ditQ$ind< to search for a 'ey#ord to find the HT* for the 5I element youre trying to test-

Page 45: About Sellinum

8/11/2019 About Sellinum

http://slidepdf.com/reader/full/about-sellinum 45/173

Alternati.ely+ select just that portion of the #ebpage for #hich you #ant to see the source- Then right,clic' the #ebpage and select 3ie#Selection Source- In this case+ the separate HT* #indo# #ill contain just a small amount of source+ #ith highlighting on the portionrepresenting your selection-

6ocator Assistance

Whene.er Selenium,I(& records a locator,type argument+ it stores additional information #hich allo#s the user to .ie# other possiblelocator,type arguments that could be used instead- This feature can be .ery useful for learning more about locators+ and is often needed tohelp one build a different type of locator than the type that #as recorded-

This locator assistance is presented on the Selenium,I(& #indo# as a drop,do#n list accessible at the right end of the Target field ;only#hen the Target field contains a recorded locator,type argument<- Belo# is a snapshot sho#ing the contents of this drop,do#n for onecommand- Note that the first column of the drop,do#n pro.ides alternati.e locators+ #hereas the second column indicates the type of eachalternati.e- 

Writing a Test SuiteA test suite is a collection of test cases #hich is displayed in the leftmost pane in the I(&- The test suite pane can be manually opened orclosed .ia selecting a small dot half#ay do#n the right edge of the pane ;#hich is the left edge of the entire Selenium,I(& #indo# if thepane is closed<-

The test suite pane #ill be automatically opened #hen an e%isting test suite is opened or #hen the user selects the Ne# Test !ase item fromthe $ile menu- In the latter case+ the ne# test case #ill appear immediately belo# the pre.ious test case-

Selenium,I(& also supports loading pre,e%isting test cases by using the $ile ,Q Add Test !ase menu option- This allo#s you to add e%istingtest cases to a ne# test suite-

A test suite file is an HT* file containing a one,column table- &ach cell of each ro# in the UtbodyQ section contains a lin' to a test case-The e%ample belo# is of a test suite containing four test cases1

<html><head>  <meta http-e=ui*Content-Type* content*te"t/htmlR charsetJT%-3*>  <title>$ample $elenium Test $uite</title></head><body>  <table cellpadding*'* cellspacing*'* border*'*>  <thead>

Page 46: About Sellinum

8/11/2019 About Sellinum

http://slidepdf.com/reader/full/about-sellinum 46/173

  <tr><td>Test Cases or De :nAa :-B Directory ,ins</td></tr>  </thead>  <tbody>  <tr><td><a hre*+/a+html*>: ,ins</a></td></tr>  <tr><td><a hre*+/b+html*>O ,ins</a></td></tr>  <tr><td><a hre*+/c+html*>C ,ins</a></td></tr>  <tr><td><a hre*+/d+html*>D ,ins</a></td></tr>

  </tbody>  </table></body></html>

Note

Test case files should not ha.e to be co,located #ith the test suite file that in.o'es them- And on *ac 6S and inu% systems+ that is indeedthe case- Ho#e.er+ at the time of this #riting+ a bug pre.ents Windo#s users from being able to place the test cases else#here than #ith thetest suite that in.o'es them-

@ser ,3tensions5ser e%tensions are :a.aScript files that allo# one to create his or her o#n customi/ations and features to add additional functionality- 6ftenthis 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-

 4&-*AN: H4" "'74-N 4" -) -1 #A'8$' $4++ (' *'54"4N9 H4" "--N.

Perhaps the most popular of all Selenium,I(& e%tensions is one #hich pro.ides flo# control in the form of #hile loops and primiti.econditionals- This e%tension is the goto\sel\ide-js- $or an e%ample of ho# to use the functionality pro.ided by this e%tension+ loo' at thepage created by its author-

To install this e%tension+ put the pathname to its location on your computer in the Selenium Core e3tensions field of Selenium,I(&s6ptionsQ6ptionsQ>eneral tab- 

After selecting the O button+ you must close and reopen Selenium,I(& in order for the e%tensions file to be read- Any change you ma'e toan e%tension #ill also re0uire you to close and reopen Selenium,I(&-

Information on #riting your o#n e%tensions can be found near the bottom of the Selenium 2eference document-

Page 47: About Sellinum

8/11/2019 About Sellinum

http://slidepdf.com/reader/full/about-sellinum 47/173

2ormat

$ormat+ under the 6ptions menu+ allo#s you to select a language for sa.ing and displaying the test case- The default is HT*-

If you #ill be using Selenium,2! to run your test cases+ this feature is used to translate your test case into a programming language- Selectthe language+ e-g- :a.a+ PHP+ you #ill be using #ith Selenium,2! for de.eloping your test programs- Then simply sa.e the test case using$ileQ&%port Test !ase As- "our test case #ill be translated into a series of functions in the language you choose- &ssentially+ program codesupporting your test is generated for you by Selenium,I(&-

Also+ note that if the generated code does not suit your needs+ you can alter it by editing a configuration file #hich defines the generationprocess- &ach supported language has configuration settings #hich are editable- This is under the 6ptionsQ6ptionsQ$ormats tab-

Note

At the time of this #riting+ this feature is not yet supported by the Selenium de.elopers- Ho#e.er the author has altered the ! format in alimited manner and it has #or'ed #ell-

,3ecuting Selenium-I+, Tests on +ifferent Bro0sers

While Selenium,I(& can only run tests against $irefo%+ tests de.eloped #ith Selenium,I(& can be run against other bro#sers+ using asimple command,line interface that in.o'es the Selenium,2! ser.er- This topic is co.ered in the 2un Selenese tests section on Selenium,2!chapter- The html"uite command,line option is the particular feature of interest-

Troubleshooting

Belo# is a list of imageGe%planation pairs #hich describe fre0uent sources of problems #ith Selenium,I(&1

able view is not available with this format.

This message can be occasionally displayed in the Table tab #hen Selenium I(& is launched- The #or'around is to close and reopenSelenium I(&- See issue F88@- for more information- If you are able to reproduce this reliably then please pro.ide details so that #e can#or' on a fi%-

error loading test case: no command found

"ou.e used 2ileGFOpen to try to open a test suite file- 5se 2ileGFOpen Test Suite instead-

An enhancement re0uest has been raised to impro.e this error message- See issue F8F8-

Page 48: About Sellinum

8/11/2019 About Sellinum

http://slidepdf.com/reader/full/about-sellinum 48/173

 

This type of error may indicate a timing problem+ i-e-+ the element specified by a locator in your command #asnt fully loaded #hen thecommand #as e%ecuted- Try putting a pause 111 before the command to determine #hether the problem is indeed related to timing- If so+in.estigate using an appropriate 0ait2or9 or 9AndWait command before the failing command-

 

Whene.er your attempt to use .ariable substitution fails as is the case for the open command abo.e+ it indicates that you ha.ent actuallycreated the .ariable #hose .alue youre trying to access- This is sometimes due to putting the .ariable in the alue field #hen it should be inthe Target field or .ice .ersa- In the e%ample abo.e+ the t#o parameters for the store command ha.e been erroneously placed in the re.erseorder of #hat is re0uired- $or any Selenese command+ the first re0uired parameter must go in the Target field+ and the second re0uiredparameter ;if one e%ists< must go in the alue field-

error loading test case: ;'%ception... <7omponent returned failure code: =%>=?2==@2 /N"'**-*14+'N-1-)N#0;ns41ile4nput"tream.initBC nresult: <=%>=?2==@2 /N"'**-*14+'N-1-)N#0C location: <D" frame :: chrome:66selenium

ide6content6fileutils.Es :: anonymous :: line F>C data: noB

6ne of the test cases in your test suite cannot be found- *a'e sure that the test case is indeed located #here the test suite indicates it is

located- Also+ ma'e sure that your actual test case files ha.e the -html e%tension both in their filenames+ and in the test suite file #here theyare referenced-

An enhancement re0uest has been raised to impro.e this error message- See issue F8FF-

Page 49: About Sellinum

8/11/2019 About Sellinum

http://slidepdf.com/reader/full/about-sellinum 49/173

 

"our e%tension files contents ha.e not been read by Selenium,I(&- Be sure you ha.e specified the proper pathname to the e%tensions file.ia OptionsGFOptionsGF.eneral in the Selenium Core e3tensions field- Also+ Selenium,I(& must be restarted after any change to eitheran e%tensions file or to the contents of the Selenium Core e3tensions field-

Na'igation

• Selenium (ocumentation ^• ne%t 

• pre.ious Y

Table Of Contents

• Selenium Web(ri.er

• Introducing Web(ri.er 

• Ho# (oes Web(ri.er (ri.e the Bro#ser !ompared to Selenium,2!? 

Web(ri.er and the Selenium,Ser.er • Setting 5p a Selenium,Web(ri.er Project 

• *igrating from Selenium F-8 

• Introducing the Selenium,Web(ri.er API by &%ample 

• Selenium,Web(ri.er API !ommands and 6perations 

• (ri.er Specifics and Tradeoffs 

• Selenium,Web(ri.ers (ri.ers 

• Alternati.e Bac',&nds1 *i%ing Web(ri.er and 2! Technologies 

• 2unning Standalone Selenium Ser.er for use #ith 2emote(ri.ers 

Page 50: About Sellinum

8/11/2019 About Sellinum

http://slidepdf.com/reader/full/about-sellinum 50/173

• Additional 2esources 

• Ne%t Steps 

Selenium Web+ri'er N-': $ere currently working on documenting these sections. $e believe the information here is accurate, however be aware we are also

still working on this chapter. Additional information will be provided as we go which should make this chapter more solid.

Introducing Web+ri'er

The primary ne# feature in Selenium 7-8 is the integration of the Web(ri.er API- Web(ri.er is designed to pro.ide a simpler+ more conciseprogramming interface in addition to addressing some limitations in the Selenium,2! API- Selenium,Web(ri.er #as de.eloped to bettersupport dynamic #eb pages #here elements of a page may change #ithout the page itself being reloaded- Web(ri.ers goal is to supply a#ell,designed object,oriented API that pro.ides impro.ed support for modern ad.anced #eb,app testing problems-

Ho0 +oes Web+ri'er Q+ri'e" the Bro0ser Compared to Selenium-*C?

Selenium,Web(ri.er ma'es direct calls to the bro#ser using each bro#sers nati.e support for automation- Ho# these direct calls are made+and the features they support depends on the bro#ser you are using- Information on each bro#ser dri.er is pro.ided later in this chapter-

$or those familiar #ith Selenium,2!+ this is 0uite different from #hat you are used to- Selenium,2! #or'ed the same #ay for eachsupported bro#ser- It injected ja.ascript functions into the bro#ser #hen the bro#ser #as loaded and then used its ja.ascript to dri.e theA5T #ithin the bro#ser- Web(ri.er does not use this techni0ue- Again+ it dri.es the bro#ser directly using the bro#sers built in support for

automation-

Web+ri'er and the Selenium-Ser'er

"ou may+ or may not+ need the Selenium Ser.er+ depending on ho# you intend to use Selenium,Web(ri.er- If you #ill be only using theWeb(ri.er API you do not need the Selenium,Ser.er- If your bro#ser and tests #ill all run on the same machine+ and your tests only use theWeb(ri.er API+ then you do not need to run the Selenium,Ser.er Web(ri.er #ill run the bro#ser directly-

There are some reasons though to use the Selenium,Ser.er #ith Selenium,Web(ri.er-

Page 51: About Sellinum

8/11/2019 About Sellinum

http://slidepdf.com/reader/full/about-sellinum 51/173

• "ou are using Selenium,>rid to distribute your tests o.er multiple machines or .irtual machines ;3*s<-

• "ou #ant to connect to a remote machine that has a particular bro#ser .ersion that is not on your current machine-

• "ou are not using the :a.a bindings ;i-e- Python+ !+ or 2uby< and #ould li'e to use Html5nit (ri.er 

Setting @p a Selenium-Web+ri'er ro!ectTo install Selenium means to set up a project in a de.elopment so you can #rite a program using Selenium- Ho# you do this depends onyour programming language and your de.elopment en.ironment-

Da'a

The easiest #ay to set up a Selenium 7-8 :a.a project is to use *a.en- *a.en #ill do#nload the ja.a bindings ;the Selenium 7-8 ja.a clientlibrary< and all its dependencies+ and #ill create the project for you+ using a ma.en pom-%ml ;project configuration< file- 6nce you.e donethis+ you can import the ma.en project into your preferred I(&+ Intelli: I(&A or &clipse-

$irst+ create a folder to contain your Selenium project files- Then+ to use *a.en+ you need a pom-%ml file- This can be created #ith a te%teditor- We #ont teach the details of pom-%ml files or for using *a.en since there are already e%cellent references on this- "our pom-%ml file#ill loo' something li'e this- !reate this file in the folder you created for your project-

<;"ml ersion*'+5* encoding*JT%-3*;><proKect "mlns*http?//maen+apache+org/&N/+5+5*  "mlns?"si*http?//www+w.+org/#55'/N,$chema-instance*  "si?schema,ocation*http?//maen+apache+org/&N/+5+5 http?//maen+apache+org/"sd/maen-+5+5+"sd*>  <modelVersion>+5+5</modelVersion>  <groupPd>Ny$el#5&roK</groupPd>  <artiactPd>Ny$el#5&roK</artiactPd>  <ersion>'+5</ersion>  <dependencies>  <dependency>  <groupPd>org+seleniumh=+selenium</groupPd>  <artiactPd>selenium-Kaa</artiactPd>  <ersion>#+.+5</ersion>  </dependency>  <dependency>  <groupPd>com+opera</groupPd>  <artiactPd>operadrier</artiactPd>  </dependency>  </dependencies>

Page 52: About Sellinum

8/11/2019 About Sellinum

http://slidepdf.com/reader/full/about-sellinum 52/173

Page 53: About Sellinum

8/11/2019 About Sellinum

http://slidepdf.com/reader/full/about-sellinum 53/173

ython

If you are using Python for test automation then you probably are already familiar #ith de.eloping in Python- To add Selenium to yourPython en.ironment run the follo#ing command from a command,line-

pip install selenium

Pip re0uires pip to be installed+ pip also has a dependency on setuptools-Teaching Python de.elopment itself is beyond the scope of this document+ ho#e.er there are many resources on Python and li'elyde.elopers in your organi/ation can help you get up to speed-

*uby

If you are using 2uby for test automation then you probably are already familiar #ith de.eloping in 2uby- To add Selenium to your 2ubyen.ironment run the follo#ing command from a command,line-

gem install selenium-webdrier

Teaching 2uby de.elopment itself is beyond the scope of this document+ ho#e.er there are many resources on 2uby and li'ely de.elopers inyour organi/ation can help you get up to speed-

erl

Perl bindings are pro.ided by a third party+ please refer to any of their documentation on ho# to install G get started- There is one 'no#n Perlbinding as of this #riting-

H

PHP bindings are pro.ided by a third party+ please refer to any of their documentation on ho# to install G get started- There are three 'no#nbindings at this time1 By !hibimagic By u'as/ olc/yns'i and By the $aceboo'

7igrating from Selenium )&1

$or those #ho already ha.e test suites #ritten using Selenium F-8+ #e ha.e pro.ided tips on ho# to migrate your e%isting code to Selenium7-8- Simon Ste#art+ the lead de.eloper for Selenium 7-8+ has #ritten an article on migrating from Selenium F-8- We.e included this as anappendi%-

*igrating $rom Selenium 2! to Selenium Web(ri.er

Page 54: About Sellinum

8/11/2019 About Sellinum

http://slidepdf.com/reader/full/about-sellinum 54/173

Introducing the Selenium-Web+ri'er AI by ,3ample

Web(ri.er is a tool for automating #eb application testing+ and in particular to .erify that they #or' as e%pected- It aims to pro.ide afriendly API thats easy to e%plore and understand+ easier to use than the Selenium,2! ;F-8< API+ #hich #ill help to ma'e your tests easier toread and maintain- Its not tied to any particular test frame#or'+ so it can be used e0ually #ell in a unit testing or from a plain old DmainEmethod- This section introduces Web(ri.ers API and helps get you started becoming familiar #ith it- Start by setting up a Web(ri.er

project if you ha.ent already- This #as described in the pre.ious section+ Setting 5p a Selenium,Web(ri.er Project-6nce your project is set up+ you can see that Web(ri.er acts just as any normal library1 it is entirely self,contained+ and you usually dontneed to remember to start any additional processes or run any installers before using it+ as opposed to the pro%y ser.er #ith Selenium,2!-

Note1 additional steps are re0uired to use !hrome (ri.er+ 6pera (ri.er+ Android (ri.er and iPhone (ri.er

"oure no# ready to #rite some code- An easy #ay to get started is this e%ample+ #hich searches for the term D!heeseE on >oogle and thenoutputs the result pages title to the console-

pacage org+open=a+selenium+e"ampleR

import org+open=a+selenium+OyR

import org+open=a+selenium+ebDrierRimport org+open=a+selenium+eblementRimport org+open=a+selenium+ireo"+%ireo"DrierRimport org+open=a+selenium+support+ui+"pectedConditionRimport org+open=a+selenium+support+ui+ebDrieraitR

public class $elenium#"ample   public static oid main($tring67 args)   // Create a new instance o the %ireo" drier  // Qotice that the remainder o the code relies on the interaceE

// not the implementation+  ebDrier drier new %ireo"Drier()R

  // :nd now use this to isit Woogle  drier+get(*http?//www+google+com*)R  // :lternatiely the same thing can be done lie this  // drier+naigate()+to(*http?//www+google+com*)R

  // %ind the te"t input element by its name  eblement element drier+indlement(Oy+name(*=*))R

  // nter something to search or  element+sendXeys(*Cheese!*)R

Page 55: About Sellinum

8/11/2019 About Sellinum

http://slidepdf.com/reader/full/about-sellinum 55/173

  // Qow submit the orm+ ebDrier will ind the orm or us rom the element  element+submit()R

  // Chec the title o the page  $ystem+out+println(*&age title is? * drier+getTitle())R 

// Woogle9s search is rendered dynamically with Yaa$cript+  // ait or the page to loadE timeout ater '5 seconds  (new ebDrierait(drierE '5))+until(new "pectedCondition<Ooolean>()   public Ooolean apply(ebDrier d)   return d+getTitle()+to,owerCase()+startsith(*cheese!*)R  F  F)R

  // $hould see? *cheese! - Woogle $earch*  $ystem+out+println(*&age title is? * drier+getTitle())R 

//Close the browser

  drier+=uit()R  FF

In upcoming sections+ you #ill learn more about ho# to use Web(ri.er for things such as na.igating for#ard and bac'#ard in yourbro#sers history+ and ho# to test #eb sites that use frames and #indo#s- We also pro.ide a more thorough discussions and e%amples-

Selenium-Web+ri'er AI Commands and Operations

2etching a ageThe first thing youre li'ely to #ant to do #ith Web(ri.er is na.igate to a page- The normal #ay to do this is by calling DgetE1

drier+get(*http?//www+google+com*)R

(ependent on se.eral factors+ including the 6SGBro#ser combination+ Web(ri.er may or may not #ait for the page to load- In somecircumstances+ Web(ri.er may return control before the page has finished+ or e.en started+ loading- To ensure robustness+ you need to #aitfor the element;s< to e%ist in the page using &%plicit and Implicit Waits-

Page 56: About Sellinum

8/11/2019 About Sellinum

http://slidepdf.com/reader/full/about-sellinum 56/173

6ocating @I ,lements $Web,lements(

ocating elements in Web(ri.er can be done on the Web(ri.er instance itself or on a Web&lement- &ach of the language bindings e%pose aD$ind &lementE and D$ind &lementsE method- The first returns a Web&lement object other#ise it thro#s an e%ception- The latter returns alist of Web&lements+ it can return an empty list if no (6* elements match the 0uery-

The D$indE methods ta'e a locator or 0uery object called DByE- DByE strategies are listed belo#-

By I+

This is the most efficient and preferred #ay to locate an element- !ommon pitfalls that 5I de.elopers ma'e is ha.ing non,uni0ue ids on apage or auto,generating the id+ both should be a.oided- A class on an html element is more appropriate than an auto,generated id-

&%ample of ho# to find an element that loo's li'e this1

<di id*coolestidgetah*>+++</di>

eblement element drier+indlement(Oy+id(*coolestidgetah*))R

By Class Name

D!lassE in this case refers to the attribute on the (6* element- 6ften in practical use there are many (6* elements #ith the same classname+ thus finding multiple elements becomes the more practical option o.er finding the first element-

&%ample of ho# to find an element that loo's li'e this1

<di class*cheese*><span>Cheddar</span></di><di class*cheese*><span>Wouda</span></di>

,ist<eblement> cheeses drier+indlements(Oy+classQame(*cheese*))R

By Tag Name

The (6* Tag Name of the element-

&%ample of ho# to find an element that loo's li'e this1

<irame src*+++*></irame>

eblement rame drier+indlement(Oy+tagQame(*irame*))R

Page 57: About Sellinum

8/11/2019 About Sellinum

http://slidepdf.com/reader/full/about-sellinum 57/173

By Name

$ind the input element #ith matching name attribute-

&%ample of ho# to find an element that loo's li'e this1

<input name*cheese* type*te"t*/>

eblement cheese drier+indlement(Oy+name(*cheese*))R

By 6in% Te3t

$ind the lin' element #ith matching .isible te%t-

&%ample of ho# to find an element that loo's li'e this1

<a hre*http?//www+google+com/search;=cheese*>cheese</a>>

eblement cheese drier+indlement(Oy+linTe"t(*cheese*))R

By artial 6in% Te3t

$ind the lin' element #ith partial matching .isible te%t-

&%ample of ho# to find an element that loo's li'e this1

<a hre*http?//www+google+com/search;=cheese*>search or cheese</a>>

eblement cheese drier+indlement(Oy+partial,inTe"t(*cheese*))R

By CSS

i'e the name implies it is a locator strategy by css- Nati.e bro#ser support is used by default+ so please refer to w3c css selectors

Ghttp:66www.w3.org6*67""6selectorsI for a list of generally a.ailable css selectors- If a bro#ser does not ha.e nati.e support for css0ueries+ then Si//le is used- I& =+ and $$K-8 currently use Si//le as the css 0uery engine-

Be#are that not all bro#sers #ere created e0ual+ some css that might #or' in one .ersion may not #or' in another-

&%ample of to find the cheese belo#1

<di id*ood*><span class*dairy*>mil</span><span class*dairy aged*>cheese</span></di>

Page 58: About Sellinum

8/11/2019 About Sellinum

http://slidepdf.com/reader/full/about-sellinum 58/173

Page 59: About Sellinum

8/11/2019 About Sellinum

http://slidepdf.com/reader/full/about-sellinum 59/173

Jathe3pression

Html@nit+ri'er

2irefo3+ri'er

Internet,3plorer+ri'er

;De%ampleE<

GGINP5T 8 7 8

Sometimes HT* elements do not need attributes to be e%plicitly declared because they #ill default to 'no#n .alues- $or e%ample+ theDinputE tag does not re0uire the DtypeE attribute because it defaults to Dte%tE- The rule of thumb #hen using %path in Web(ri.er is that youshould not e%pect to be able to match against these implicit attributes-

@sing Da'aScript

"ou can e%ecute arbitrary ja.ascript to find an element and as long as you return a (6* &lement+ it #ill be automatically con.erted to aWeb&lement object-

Simple e%ample on a page that has j4uery loaded1

eblement element (eblement) ((Yaascript"ecutor)drier)+e"ecute$cript(*return Z(9+cheese9)657*)R

$inding all the input elements to the e.ery label on a page1

,ist<eblement> labels drier+indlements(Oy+tagQame(*label*))R,ist<eblement> inputs (,ist<eblement>) ((Yaascript"ecutor)drier)+e"ecute$cript(  *ar labels arguments657E inputs 67R or (ar i5R i < labels+lengthR i)*   *inputs+push(document+getlementOyPd(labels6i7+get:ttribute(9or9)))R F return inputsR*E labels)R

@ser Input - 2illing In 2orms

We.e already seen ho# to enter te%t into a te%tarea or te%t field+ but #hat about the other elements? "ou can DtoggleE the state ofchec'bo%es+ and you can use Dclic'E to set something li'e an 6PTI6N tag selected- (ealing #ith S&&!T tags isnt too bad1

eblement select drier+indlement(Oy+tagQame(*select*))R,ist<eblement> allptions select+indlements(Oy+tagQame(*option*))Ror (eblement option ? allptions)   $ystem+out+println($tring+ormat(*Value is? [s*E option+get:ttribute(*alue*)))R  option+clic()RF

This #ill find the first DS&&!TE element on the page+ and cycle through each of its 6PTI6Ns in turn+ printing out their .alues+ and

Page 60: About Sellinum

8/11/2019 About Sellinum

http://slidepdf.com/reader/full/about-sellinum 60/173

selecting each in turn- As you #ill notice+ this isnt the most efficient #ay of dealing #ith S&&!T elements- Web(ri.ers support classesinclude one called DSelectE+ #hich pro.ides useful methods for interacting #ith these-

$elect select new $elect(drier+indlement(Oy+tagQame(*select*)))Rselect+deselect:ll()Rselect+selectOyVisibleTe"t(*dam*)R

This #ill deselect all 6PTI6Ns from the first S&&!T on the page+ and then select the 6PTI6N #ith the displayed te%t of D&damE-6nce you.e finished filling out the form+ you probably #ant to submit it- 6ne #ay to do this #ould be to find the DsubmitE button and clic'it1

drier+indlement(Oy+id(*submit*))+clic()R

Alternati.ely+ Web(ri.er has the con.enience method DsubmitE on e.ery element- If you call this on an element #ithin a form+ Web(ri.er#ill #al' up the (6* until it finds the enclosing form and then calls submit on that- If the element isnt in a form+ then theQo$uchlement"ception #ill be thro#n1

element+submit()R

7o'ing Bet0een Windo0s and 2rames

Some #eb applications ha.e many frames or multiple #indo#s- Web(ri.er supports mo.ing bet#een named #indo#s using the Ds#itchToEmethod1

drier+switchTo()+window(*windowQame*)R

All calls to drier #ill no# be interpreted as being directed to the particular #indo#- But ho# do you 'no# the #indo#s name? Ta'e aloo' at the ja.ascript or lin' that opened it1

<a hre*somewhere+html* target*windowQame*>Clic here to open a new window</a>

Alternati.ely+ you can pass a D#indo# handleE to the Ds#itchTo;<-#indo#;<E method- no#ing this+ its possible to iterate o.er e.ery open#indo# li'e so1

or ($tring handle ? drier+getindowLandles())   drier+switchTo()+window(handle)RF

"ou can also s#itch from frame to frame ;or into iframes<1

Page 61: About Sellinum

8/11/2019 About Sellinum

http://slidepdf.com/reader/full/about-sellinum 61/173

drier+switchTo()+rame(*rameQame*)R

Its possible to access subframes by separating the path #ith a dot+ and you can specify the frame by its inde% too- That is1

drier+switchTo()+rame(*rameQame+5+child*)R

#ould go to the frame named DchildE of the first subframe of the frame called DframeNameE- All frames are e'aluated as if from 9top9&

opup +ialogs

Starting #ith Selenium 7-8 beta F+ there is built in support for handling popup dialog bo%es- After you.e triggered an action that opens apopup+ you can access the alert #ith the follo#ing1

:lert alert drier+switchTo()+alert()R

This #ill return the currently open alert object- With this object you can no# accept+ dismiss+ read its contents or e.en type into a prompt-This interface #or's e0ually #ell on alerts+ confirms+ and prompts- 2efer to the :a.a(ocs or 2uby(ocs for more information-

Na'igationK History and 6ocation

&arlier+ #e co.ered na.igating to a page using the DgetE command ; drier+get(*http?//www+e"ample+com*)< As you.e seen+Web(ri.er has a number of smaller+ tas',focused interfaces+ and na.igation is a useful tas'- Because loading a page is such a fundamentalre0uirement+ the method to do this li.es on the main Web(ri.er interface+ but its simply a synonym to1

drier+naigate()+to(*http?//www+e"ample+com*)R

To reiterate1 Dnaigate()+to()E and Dget()E do e%actly the same thing- 6nes just a lot easier to type than the otherZ

The Dna.igateE interface also e%poses the ability to mo.e bac'#ards and for#ards in your bro#sers history1

drier+naigate()+orward()Rdrier+naigate()+bac()R

Please be a#are that this functionality depends entirely on the underlying bro#ser- Its just possible that something une%pected may happen#hen you call these methods if youre used to the beha.iour of one bro#ser o.er another-

Coo%ies

Before #e lea.e these ne%t steps+ you may be interested in understanding ho# to use coo'ies- $irst of all+ you need to be on the domain thatthe coo'ie #ill be .alid for- If you are trying to preset coo'ies before you start interacting #ith a site and your homepage is large G ta'es a

Page 62: About Sellinum

8/11/2019 About Sellinum

http://slidepdf.com/reader/full/about-sellinum 62/173

#hile to load an alternati.e is to find a smaller page on the site+ typically the 989 page is small ;http1GGe%ample-comGsome989page <

// Wo to the correct domaindrier+get(*http?//www+e"ample+com*)R

// Qow set the cooie+ This one9s alid or the entire domainCooie cooie new Cooie(*ey*E *alue*)Rdrier+manage()+addCooie(cooie)R

// :nd now output all the aailable cooies or the current JI,$et<Cooie> allCooies drier+manage()+getCooies()Ror (Cooie loadedCooie ? allCooies)   $ystem+out+println($tring+ormat(*[s -> [s*E loadedCooie+getQame()E loadedCooie+getValue()))RF

// Mou can delete cooies in . ways// Oy namedrier+manage()+deleteCooieQamed(*CooieQame*)R// Oy Cooiedrier+manage()+deleteCooie(loadedCooie)R// r all o themdrier+manage()+delete:llCooies()R

Changing the @ser Agent

This is easy #ith the $irefo% (ri.er1

%ireo"&roile proile new %ireo"&roile()Rproile+add:dditional&reerence(*general+useragent+oerride*E *some J: string*)RebDrier drier new %ireo"Drier(proile)R

+rag And +rop

Heres an e%ample of using the Actions class to perform a drag and drop- Nati.e e.ents are re0uired to be enabled-

eblement element drier+indlement(Oy+name(*source*))Reblement target drier+indlement(Oy+name(*target*))R

(new :ctions(drier))+drag:ndDrop(elementE target)+perorm()R

Page 63: About Sellinum

8/11/2019 About Sellinum

http://slidepdf.com/reader/full/about-sellinum 63/173

+ri'er Specifics and Tradeoffs

Selenium-Web+ri'er"s +ri'ers

Web(ri.er is the name of the 'ey interface against #hich tests should be #ritten+ but there are se.eral implementations- These include1

Html@nit +ri'er

This is currently the fastest and most light#eight implementation of Web(ri.er- As the name suggests+ this is based on Html5nit- Html5nitis a ja.a based implementation of a WebBro#ser #ithout a >5I- $or any language binding ;other than ja.a< the Selenium Ser.er is re0uiredto use this dri.er-

@sage

ebDrier drier new LtmlJnitDrier()R

ros

• $astest implementation of Web(ri.er

• A pure :a.a solution and so it is platform independent-

• Supports :a.aScript

Cons

• &mulates other bro#sers :a.aScript beha.iour ;see belo#<

Da'aScript in the Html@nit +ri'er

None of the popular bro#sers uses the :a.aScript engine used by Html5nit ;2hino<- If you test :a.aScript using Html5nit the results maydiffer significantly from those bro#sers-

When #e say D:a.aScriptE #e actually mean D:a.aScript and the (6*E- Although the (6* is defined by the WK! each bro#ser has itso#n 0uir's and differences in their implementation of the (6* and in ho# :a.aScript interacts #ith it- Html5nit has an impressi.elycomplete implementation of the (6* and has good support for using :a.aScript+ but it is no different from any other bro#ser1 it has its o#n0uir's and differences from both the WK! standard and the (6* implementations of the major bro#sers+ despite its ability to mimic otherbro#sers-

Page 64: About Sellinum

8/11/2019 About Sellinum

http://slidepdf.com/reader/full/about-sellinum 64/173

With Web(ri.er+ #e had to ma'e a choice do #e enable Html5nits :a.aScript capabilities and run the ris' of teams running into problemsthat only manifest themsel.es there+ or do #e lea.e :a.aScript disabled+ 'no#ing that there are more and more sites that rely on :a.aScript?We too' the conser.ati.e approach+ and by default ha.e disabled support #hen #e use Html5nit- With each release of both Web(ri.er andHtml5nit+ #e reassess this decision1 #e hope to enable :a.aScript by default on the Html5nit at some point-

,nabling Da'aScript

If you cant #ait+ enabling :a.aScript support is .ery easy1

LtmlJnitDrier drier new LtmlJnitDrier(true)R

This #ill cause the Html5nit (ri.er to emulate $irefo% K-=s :a.aScript handling by default-

2irefo3 +ri'er

!ontrols the $irefo% bro#ser using a $irefo% plugin- The $irefo% Profile that is used is stripped do#n from #hat is installed on the machineto only include the Selenium Web(ri.er-%pi ;plugin<- A fe# settings are also changed by default ;see the source to see #hich ones< $irefo%

(ri.er is capable of being run and is tested on Windo#s+ *ac+ inu%- !urrently on .ersions K-=+ F8+ latest , F+ latest

@sage

ebDrier drier new %ireo"Drier()R

ros

• 2uns in a real bro#ser and supports :a.aScript

• $aster than the Internet &%plorer (ri.er 

Cons

• Slo#er than the Html5nit (ri.er 

7odifying the 2irefo3 rofile

Suppose that you #anted to modify the user agent string ;as abo.e<+ but you.e got a tric'ed out $irefo% profile that contains do/ens ofuseful e%tensions- There are t#o #ays to obtain this profile- Assuming that the profile has been created using $irefo%s profile manager;ireo" -&roileNanager<1

Page 65: About Sellinum

8/11/2019 About Sellinum

http://slidepdf.com/reader/full/about-sellinum 65/173

&roilesPni all&roiles new &roilesPni()R%ireo"&roile proile all&roiles+get&roile(*ebDrier*)Rproile+set&reerences(*oo+bar*E #.)RebDrier drier new %ireo"Drier(proile)R

Alternati.ely+ if the profile isnt already registered #ith $irefo%1

%ile proileDir new %ile(*path/to/top/leel/o/proile*)R%ireo"&roile proile new %ireo"&roile(proileDir)Rproile+add:dditional&reerences(e"tra&res)RebDrier drier new %ireo"Drier(proile)R

As #e de.elop features in the $irefo% (ri.er+ #e e%pose the ability to use them- $or e%ample+ until #e feel nati.e e.ents are stable on$irefo% for inu%+ they are disabled by default- To enable them1

%ireo"&roile proile new %ireo"&roile()Rproile+setnableQatieents(true)RebDrier drier new %ireo"Drier(proile)R

Info

See the $irefo% section in the #i'i page for the most up to date info-

Internet ,3plorer +ri'er

This dri.er is controlled by a -dll and is thus only a.ailable on Windo#s 6S- &ach Selenium release has its core functionality tested against.ersions =+ and @ on OP+ and C on Windo#s-

@sage

ebDrier drier new Pnternet"plorerDrier()R

ros

• 2uns in a real bro#ser and supports :a.aScript #ith all the 0uir's your end users see-

Page 66: About Sellinum

8/11/2019 About Sellinum

http://slidepdf.com/reader/full/about-sellinum 66/173

Cons

• 6b.iously the Internet &%plorer (ri.er #ill only #or' on Windo#sZ

• !omparati.ely slo# ;though still pretty snappy 1<

• OPath is not nati.ely supported in most .ersions- Si//le is injected automatically #hich is significantly slo#er than other bro#sers

and slo#er #hen comparing to !SS selectors in the same bro#ser-

!SS is not nati.ely supported in .ersions = and - Si//le is injected instead-• !SS selectors in I& @ and C are nati.e+ but those bro#sers dont fully support !SSK

Info

See the Internet &%plorer section of the #i'i page for the most up to date info- Please ta'e special note of the 2e0uired !onfigurationsection-

Chrome +ri'er

!hrome (ri.er is maintained G supported by the !hromium project iteslf- Web(ri.er #or's #ith !hrome through the chromedri.er binary;found on the chromium projects do#nload page<- "ou need to ha.e both chromedri.er and a .ersion of chrome bro#ser installed-chromedri.er needs to be placed some#here on your systems path in order for Web(ri.er to automatically disco.er it- The !hrome bro#seritself is disco.ered by chromedri.er in the default installation path- These both can be o.erridden by en.ironment .ariables- Please refer tothe #i'i for more information-

@sage

ebDrier drier new ChromeDrier()R

ros• 2uns in a real bro#ser and supports :a.aScript

• Because !hrome is a Web'it,based bro#ser+ the !hrome (ri.er may allo# you to .erify that your site #or's in Safari- Note that

since !hrome uses its o#n 3@ :a.aScript engine rather than Safaris Nitro engine+ :a.aScript e%ecution may differ-

Cons

• Slo#er than the Html5nit (ri.er 

Page 67: About Sellinum

8/11/2019 About Sellinum

http://slidepdf.com/reader/full/about-sellinum 67/173

Info

See our #i'i for the most up to date info- *ore info can also be found on the do#nloads page

.etting running 0ith Chrome +ri'er

(o#nload the !hrome (ri.er e%ecutable and follo# the other instructions on the #i'i page

Opera +ri'er

See the 6pera (ri.er #i'i article in the Selenium Wi'i for information on using the 6pera (ri.er-

ihone +ri'er

See the iPhone (ri.er #i'i article in the Selenium Wi'i for information on using the *ac i6S (ri.er-

Android +ri'er

See the Android (ri.er #i'i article in the Selenium Wi'i for information on using the Android (ri.er-

Alternati'e Bac%-,ndsK 7i3ing Web+ri'er and *C Technologies

Web+ri'er-Bac%ed Selenium-*C

The :a.a .ersion of Web(ri.er pro.ides an implementation of the Selenium,2! API- These means that you can use the underlyingWeb(ri.er technology using the Selenium,2! API- This is primarily pro.ided for bac'#ards compatibility- It allo#s those #ho ha.ee%isting test suites using the Selenium,2! API to use Web(ri.er under the co.ers- Its pro.ided to help ease the migration path to Selenium,

Web(ri.er- Also+ this allo#s one to use both APIs+ side,by,side+ in the same test code-

Selenium,Web(ri.er is used li'e this1

// Mou may use any ebDrier implementation+ %ireo" is used here as an e"ampleebDrier drier new %ireo"Drier()R

// : *base url*E used by selenium to resole relatie JI,s $tring baseJrl *http?//www+google+com*R

// Create the $elenium implementation

Page 68: About Sellinum

8/11/2019 About Sellinum

http://slidepdf.com/reader/full/about-sellinum 68/173

Page 69: About Sellinum

8/11/2019 About Sellinum

http://slidepdf.com/reader/full/about-sellinum 69/173

JI,(*http?//www+google+com/*)E capabilities)RebDrier drier new IemoteebDrier(e"ecutorE capabilities)R

There are currently some major limitations #ith this approach+ notably that find&lements doesnt #or' as e%pected- Also+ because #ereusing Selenium !ore for the hea.y lifting of dri.ing the bro#ser+ you are limited by the :a.aScript sandbo%-

*unning Standalone Selenium Ser'er for use 0ith *emote+ri'ers$rom Seleniums (o#nload page do#nload selenium,ser.er,standalone,U.ersionQ-jar and optionally I&(ri.erSer.er- If you plan to #or'#ith !hrome+ do#nload it from >oogle !ode-

5npac' I&(ri.erSer.er andGor chromedri.er and put them in a directory #hich is on the _PATH G `PATH` , the Selenium Ser.er shouldthen be able to handle re0uests for I& G !hrome #ithout additional modifications-

Start the ser.er on the command line #ith

Kaa -Kar <pathSto>/selenium-serer-standalone-<ersion>+Kar

If you #ant to use nati.e e.ents functionality+ indicate this on the command line #ith the option-Dwebdrier+enable+natie+eents'

$or other command line options+ e%ecute

Kaa -Kar <pathSto>/selenium-serer-standalone-<ersion>+Kar -help

In order to function properly+ the follo#ing ports should be allo#ed incoming T!P connections1 9999+ 8L9,L ;or t#ice as many ports as thenumber of concurrent instances you plan to run<- 5nder Windo#s+ you may need to unbloc' the applications as #ell-

Additional *esources"ou can find further resources for Web(ri.er in Web(ri.ers #i'i

6f course+ dont hesitate to do an internet search on any Selenium topic+ including Selenium,Web(ri.ers dri.ers- There are 0uite a fe#blogs on Selenium along #ith numerous posts on .arious user forums- Additionally the Selenium 5sers >roup is a great resource-http1GGgroups-google-comGgroupGselenium,users

Page 70: About Sellinum

8/11/2019 About Sellinum

http://slidepdf.com/reader/full/about-sellinum 70/173

Ne3t Steps

This chapter has simply been a high le.el #al'through of Web(ri.er and some of its 'ey capabilities- 6nce getting familiar #ith theSelenium,Web(ri.er API you #ill then #ant to learn ho# to build test suites for maintainability+ e%tensibility+ and reduced fragility #henfeatures of the A5T fre0uently change- The approach most Selenium e%perts are no# recommending is to design your test code using thePage 6bject (esign Pattern along #ith possibly a Page $actory- Selenium,Web(ri.er pro.ides support for this by supplying a Page$actory

class in :a.a and !- This is presented+along #ith other ad.anced topics+ in the ne%t chapter- Also+ for high,le.el description of thistechni0ue+ you may #ant to loo' at the Test (esign !onsiderations chapter- Both of these chapters present techni0ues for #riting moremaintainable tests by ma'ing your test code more modular-

Table Of Contents

• Web(ri.er1 Ad.anced 5sage

• &%plicit and Implicit Waits 

•2emoteWeb(ri.er 

• Ad.anced5serInteractions  

• Bro#ser Startup *anipulation 

• HT*L 

• Paralleli/ing "our Test 2uns 

Web+ri'erK Ad'anced @sage,3plicit and Implicit Waits

Waiting is ha.ing the automated tas' e%ecution elapse a certain amount of time before continuing #ith the ne%t step-

,3plicit Waits

An e%plicit #aits is code you define to #ait for a certain condition to occur before proceeding further in the code- The #orst case of this is

Page 71: About Sellinum

8/11/2019 About Sellinum

http://slidepdf.com/reader/full/about-sellinum 71/173

Thread-sleep;<+ #hich sets the condition to an e%act time period to #ait- There are some con.enience methods pro.ided that help you #ritecode that #ill #ait only as long as re0uired- Web(ri.erWait in combination #ith &%pected!ondition is one #ay this can be accomplished-

ebDrier drier new %ireo"Drier()Rdrier+get(*http?//somedomain/urlSthatSdelaysSloading*)Reblement myDynamiclement (new ebDrierait(drierE '5))  +until("pectedConditions+presencelement,ocated(Oy+id(*myDynamiclement*)))R

This #aits up to F8 seconds before thro#ing a Timeout&%ception or if it finds the element #ill return it in 8 , F8 seconds- Web(ri.erWait bydefault calls the &%pected!ondition e.ery L88 milliseconds until it returns successfully- A successful return is for &%pected!ondition type isBoolean return true or not null return .alue for all other &%pected!ondition types-

This e%ample is also functionally e0ui.alent to the first Implicit Waits e%ample-

,3pected Conditions

There are some common conditions that are fre0uently come across #hen automating #eb bro#sers- isted belo# are Implementations ofeach- :a.a happens to ha.e con.ienence methods so you dont ha.e to code an &%pected!ondition class yourself or create your o#n utility

pac'age for them-• &lement is !lic'able , it is (isplayed and &nabled-

ebDrierait wait new ebDrierait(drierE '5)Reblement element wait+until("pectedConditions+elementToOeClicable(Oy+id(*someid*)))R

The &%pected!onditions pac'age ;:a.a< ;Python< ;-N&T< contains a set of predefined conditions to use #ith Web(ri.erWait-

Implicit Waits

An implicit #ait is to tell Web(ri.er to poll the (6* for a certain amount of time #hen trying to find an element or elements if they are not

immediately a.ailable- The default setting is 8- 6nce set+ the implicit #ait is set for the life of the Web(ri.er object instance-

ebDrier drier new %ireo"Drier()Rdrier+manage()+timeouts()+implicitlyait('5E TimeJnit+$CQD$)Rdrier+get(*http?//somedomain/urlSthatSdelaysSloading*)Reblement myDynamiclement drier+indlement(Oy+id(*myDynamiclement*))R

*emoteWeb+ri'er

Page 72: About Sellinum

8/11/2019 About Sellinum

http://slidepdf.com/reader/full/about-sellinum 72/173

Ta%ing a Screenshot

import Kaa+io+%ileRimport Kaa+net+JI,R

import org+open=a+selenium+utputTypeRimport org+open=a+selenium+Taes$creenshotRimport org+open=a+selenium+ebDrierRimport org+open=a+selenium+remote+:ugmenterRimport org+open=a+selenium+remote+DesiredCapabilitiesRimport org+open=a+selenium+remote+IemoteebDrierR

public class Testing  

public oid myTest() throws "ception   ebDrier drier new IemoteebDrier(  new JI,(*http?//localhost?/wd/hub*)E

DesiredCapabilities+ireo"())R 

drier+get(*http?//www+google+com*)R 

// IemoteebDrier does not implement the Taes$creenshot class  // i the drier does hae the Capabilities to tae a screenshot  // then :ugmenter will add the Taes$creenshot methods to the instance  ebDrier augmentedDrier new :ugmenter()+augment(drier)R  %ile screenshot ((Taes$creenshot)augmentedDrier)+  get$creenshot:s(utputType+%P,)R  FF

@sing a 2irefo3rofile%ireo"&roile p new %ireo"&roile()R// set something on the proile+++DesiredCapabilities dc DesiredCapabilities+ireo"()Rdc+setCapability(%ireo"Drier+&I%P,E p)RebDrier drier new IemoteebDrier(dc)R

Page 73: About Sellinum

8/11/2019 About Sellinum

http://slidepdf.com/reader/full/about-sellinum 73/173

@sing ChromeOptions

Chromeptions options new Chromeptions()R// set some optionsDesiredCapabilities dc DesiredCapabilities+chrome()Rdc+setCapability(Chromeptions+C:&:OP,PTME options)RebDrier drier new IemoteebDrier(dc)R

Ad'anced@serInteractions

The Actions class;es< allo# you to build a !hain of Actions and perform them- There are too many possible combinations to count- Belo#are a fe# of the common interactions that you may #ant to use- $or a full list of actions please refer to the API docs :a.a ! 2uby Python

The Ad.anced 5ser Interactions re0uire nati.e e.ents to be enabled- Heres a table of the current support *atri% for nati.e e.ents1

platform I,; I,: I,8 I,= 224&;22)1

VChromestable

Chromebeta

Chromede' Opera Android iOS

Windo#sOP

" " " nGa " " " " " ? " RF nGa

Windo#s

nGa nGa " " " " " " " ? " RF nGa

inu%;5buntu<

nGa nGa nGa nGa " R7 " R7 " " " ? " RF nGa

*ac 6SO nGa nGa nGa nGa N N " " " ? " RF N

*obile(e.ice

nGa nGa nGa nGa nGa ? nGa nGa nGa ? " N

RF / F, 7, K, 9 0 5sing the emulator

R7 / F, 7 0 With e%plicitly enabling nati.e e.ents

Bro0ser Startup 7anipulation

Todo

Topics to be included1

Page 74: About Sellinum

8/11/2019 About Sellinum

http://slidepdf.com/reader/full/about-sellinum 74/173

• restoring coo'ies

• changing firefo% profile

• running bro#sers #ith plugins

@sing a ro3y

Internet ,3plorer

The easiest and recommended #ay is to manually set the pro%y on the machine that #ill be running the test- If that is not possible or you#ant your test to run #ith a different configuration or pro%y+ then you can use the follo#ing techni0ue that uses a !apababilities object- Thistemporarily changes the systems pro%y settings and changes them bac' to the original state #hen done-

$tring &IM *localhost?3535*R

org+open=a+selenium+&ro"y pro"y new org+open=a+selenium+&ro"y()Rpro"y+setLttp&ro"y(&IM)  +set%tp&ro"y(&IM)

  +set$sl&ro"y(&IM)RDesiredCapabilities cap new DesiredCapabilities()Rcap+setCapability(CapabilityType+&IME pro"y)R

ebDrier drier new Pnternet"plorerDrier(cap)R

Chrome

Is basically the same as internet e%plorer- It uses the same configuration on the machine as I& does ;on #indo#s<- 6n *ac it uses the SystemPreference ,Q Net#or' settings- 6n inu% it uses ;on 5buntu< System Q Preferences Q Net#or' Pro%y Preferences ;Alternati.ely inDGetcGen.ironmentE set http\pro%y<- As of this #riting it is un'no#n ho# to set the pro%y programmatically-

2irefo3

$irefo% maintains its pro%y configuration in a profile- "ou can preset the pro%y in a profile and use that $irefo% Profile or you can set it onprofile that is created on the fly as is sho#n in the follo#ing e%ample-

$tring &IM *localhost?3535*R

org+open=a+selenium+&ro"y pro"y new org+open=a+selenium+&ro"y()Rpro"y+setLttp&ro"y(&IM)

Page 75: About Sellinum

8/11/2019 About Sellinum

http://slidepdf.com/reader/full/about-sellinum 75/173

Page 76: About Sellinum

8/11/2019 About Sellinum

http://slidepdf.com/reader/full/about-sellinum 76/173

• Handling HTTPS and Security Popups 

• Supporting Additional Bro#sers and Bro#ser !onfigurations 

• Troubleshooting !ommon Problems 

Selenium ) $Selenium *C(

Introduction

As you can read in Brief History of The Selenium Project+ Selenium 2! #as the main Selenium project for a long time+ before theWeb(ri.erGSelenium merge brought up Selenium 7+ the ne#est and more po#erful tool-

Selenium F is still acti.ely supported ;mostly in maintenance mode< and pro.ides some features that may not be a.ailable in Selenium 7 fora #hile+ including support for se.eral languages ;:a.a+ :a.ascript+ 2uby+ PHP+ Python+ Perl and !< and support for almost e.ery bro#ser out

there-

Ho0 Selenium *C Wor%s

$irst+ #e #ill describe ho# the components of Selenium 2! operate and the role each plays in running your test scripts-

*C Components

Selenium 2! components are1

•The Selenium Ser.er #hich launches and 'ills bro#sers+ interprets and runs the Selenese commands passed from the test program+and acts as an H& pro%y+ intercepting and .erifying HTTP messages passed bet#een the bro#ser and the A5T-

• !lient libraries #hich pro.ide the interface bet#een each programming language and the Selenium 2! Ser.er-

Here is a simplified architecture diagram---- 

The diagram sho#s the client libraries communicate #ith the Ser.er passing each Selenium command for e%ecution- Then the ser.er passesthe Selenium command to the bro#ser using Selenium,!ore :a.aScript commands- The bro#ser+ using its :a.aScript interpreter+ e%ecutesthe Selenium command- This runs the Selenese action or .erification you specified in your test script-

Page 77: About Sellinum

8/11/2019 About Sellinum

http://slidepdf.com/reader/full/about-sellinum 77/173

Selenium Ser'er

Selenium Ser.er recei.es Selenium commands from your test program+ interprets them+ and reports bac' to your program the results ofrunning those tests-

The 2! ser.er bundles Selenium !ore and automatically injects it into the bro#ser- This occurs #hen your test program opens the bro#ser;using a client library API function<- Selenium,!ore is a :a.aScript program+ actually a set of :a.aScript functions #hich interprets and

e%ecutes Selenese commands using the bro#sers built,in :a.aScript interpreter-The Ser.er recei.es the Selenese commands from your test program using simple HTTP >&TGP6ST re0uests- This means you can use anyprogramming language that can send HTTP re0uests to automate Selenium tests on the bro#ser-

Client 6ibraries

The client libraries pro.ide the programming support that allo#s you to run Selenium commands from a program of your o#n design- Thereis a different client library for each supported language- A Selenium client library pro.ides a programming interface ;API<+ i-e-+ a set offunctions+ #hich run Selenium commands from your o#n program- Within each interface+ there is a programming function that supportseach Selenese command-

The client library ta'es a Selenese command and passes it to the Selenium Ser.er for processing a specific action or test against theapplication under test ;A5T<- The client library also recei.es the result of that command and passes it bac' to your program- "our programcan recei.e the result and store it into a program .ariable and report it as a success or failure+ or possibly ta'e correcti.e action if it #as anune%pected error-

So to create a test program+ you simply #rite a program that runs a set of Selenium commands using a client library API- And+ optionally+ ifyou already ha.e a Selenese test script created in the Selenium,I(&+ you can generate the "elenium *7 code- The Selenium,I(& cantranslate ;using its &%port menu item< its Selenium commands into a client,dri.ers API function calls- See the Selenium,I(& chapter forspecifics on e%porting 2! code from Selenium,I(&-

InstallationInstallation is rather a misnomer for Selenium- Selenium has set of libraries a.ailable in the programming language of your choice- "oucould do#nload them from do#nloads page

6nce you.e chosen a language to #or' #ith+ you simply need to1

• Install the Selenium 2! Ser.er-

• Set up a programming project using a language specific client dri.er-

Page 78: About Sellinum

8/11/2019 About Sellinum

http://slidepdf.com/reader/full/about-sellinum 78/173

Installing Selenium Ser'er

The Selenium 2! ser.er is simply a :a.a Ear file ;seleniumserverstandaloneGversionnumberI.Ear<+ #hich doesnt re0uire any specialinstallation- :ust do#nloading the /ip file and e%tracting the ser.er in the desired directory is sufficient-

*unning Selenium Ser'er

Before starting any tests you must start the ser.er- >o to the directory #here Selenium 2!s ser.er is located and run the follo#ing from acommand,line console-

 ja.a ,jar selenium,ser.er,standalone,U.ersion,numberQ-jar

This can be simplified by creating a batch or shell e%ecutable file ;-bat on Windo#s and -sh on inu%< containing the command abo.e- Thenma'e a shortcut to that e%ecutable on your des'top and simply double,clic' the icon to start the ser.er-

$or the ser.er to run youll need :a.a installed and the PATH en.ironment .ariable correctly configured to run it from the console- "ou canchec' that you ha.e :a.a correctly installed by running the follo#ing on a console-

 ja.a ,.ersion

If you get a .ersion number ;#hich needs to be F-L or later<+ youre ready to start using Selenium 2!-

@sing the Da'a Client +ri'er

• (o#nload Selenium ja.a client dri.er /ip from the SeleniumH4 do#nloads page-

• &%tract selenium,ja.a,U.ersion,numberQ-jar file

• 6pen your desired :a.a I(& ;&clipse+ NetBeans+ Intelli:+ Net#ea.er+ etc-<

• !reate a ja.a project-

•Add the selenium,ja.a,U.ersion,numberQ-jar files to your project as references-

• Add to your project classpath the file selenium,ja.a,U.ersion,numberQ-jar-

• $rom Selenium,I(&+ e%port a script to a :a.a file and include it in your :a.a project+ or #rite your Selenium test in :a.a using the

selenium,ja.a,client API- The API is presented later in this chapter- "ou can either use :5nit+ or TestNg to run your test+ or you can#rite your o#n simple main;< program- These concepts are e%plained later in this section-

• 2un Selenium ser.er from the console-

• &%ecute your test from the :a.a I(& or from the command,line-

$or details on :a.a test project configuration+ see the Appendi% sections !onfiguring Selenium 2! With &clipse and !onfiguring Selenium

Page 79: About Sellinum

8/11/2019 About Sellinum

http://slidepdf.com/reader/full/about-sellinum 79/173

2! With Intellij-

@sing the ython Client +ri'er

• Install Selenium .ia PIP+ instructions lin'ed at SeleniumH4 do#nloads page 

• &ither #rite your Selenium test in Python or e%port a script from Selenium,I(& to a python file-

•2un Selenium ser.er from the console

• &%ecute your test from a console or your Python I(&

$or details on Python client dri.er configuration+ see the appendi% Python !lient (ri.er !onfiguration-

@sing the &N,T Client +ri'er

• (o#nload Selenium 2! from the SeleniumH4 do#nloads page 

• &%tract the folder

• (o#nload and install N5nit ; Note1 "ou can use N5nit as your test engine- If youre not familiar yet #ith N5nit+ you can also #rite a

simple main;< function to run your tests ho#e.er N5nit is .ery useful as a test engine-<• 6pen your desired -Net I(& ;3isual Studio+ Sharp(e.elop+ *ono(e.elop<

• !reate a class library ;-dll<

• Add references to the follo#ing (s1 nmoc'-dll+ nunit-core-dll+ nunit- frame#or'-dll+ ThoughtWor's-Selenium-!ore-dll+

ThoughtWor's-Selenium-IntegrationTests-dll and ThoughtWor's-Selenium-5nitTests-dll

• Write your Selenium test in a -Net language ;!+ 3B-Net<+ or e%port a script from Selenium,I(& to a ! file and copy this code into

the class file you just created-

• Write your o#n simple main;< program or you can include N5nit in your project for running your test- These concepts are e%plained

later in this chapter-

• 2un Selenium ser.er from console

• 2un your test either from the I(&+ from the N5nit >5I or from the command line

$or specific details on -N&T client dri.er configuration #ith 3isual Studio+ see the appendi% -N&T client dri.er configuration-

@sing the *uby Client +ri'er

• If you do not already ha.e 2uby>ems+ install it from 2uby$orge 

• 2un gem install selenium-client 

• At the top of your test script+ add re=uire *selenium/client* 

Page 80: About Sellinum

8/11/2019 About Sellinum

http://slidepdf.com/reader/full/about-sellinum 80/173

• Write your test script using any 2uby test harness ;eg Test115nit+ *ini11Test or 2Spec<-

• 2un Selenium 2! ser.er from the console-

• &%ecute your test in the same #ay you #ould run any other 2uby script-

$or details on 2uby client dri.er configuration+ see the Selenium,!lient documentation

2rom Selenese to a rogramThe primary tas' for using Selenium 2! is to con.ert your Selenese into a programming language- In this section+ #e pro.ide se.eraldifferent language,specific e%amples-

Sample Test Script

ets start #ith an e%ample Selenese test script- Imagine recording the follo#ing test #ith Selenium,I(&-

open G

type 0 seleniumrc

clic'AndWait btn>

assertTe%tPresent 2esults forseleniumrc

 

Note1 This e%ample #ould #or' #ith the >oogle search page http1GG###-google-com

Selenese as rogramming Code

Here is the test script e%ported ;.ia Selenium,I(&< to each of the supported programming languages- If you ha.e at least basic 'no#ledge ofan object, oriented programming language+ you #ill understand ho# Selenium runs Selenese commands by reading one of these e%amples-To see an e%ample in a specific language+ select one of these buttons-

  /@@ :dd YJnit ramewor to your classpath i not already there  @ or this e"ample to wor  @/pacage com+e"ample+testsR

import com+thoughtwors+selenium+@R

import Ka a til rege &attern

Page 81: About Sellinum

8/11/2019 About Sellinum

http://slidepdf.com/reader/full/about-sellinum 81/173

import Kaa+util+rege"+&atternR

public class QewTest e"tends $eleneseTestCase   public oid setJp() throws "ception   setJp(*http?//www+google+com/*E *@ireo"*)R  F  public oid testQew() throws "ception   selenium+open(*/*)R

  selenium+type(*=*E *selenium rc*)R  selenium+clic(*btnW*)R  selenium+wait%or&ageTo,oad(*.5555*)R  assertTrue(selenium+isTe"t&resent(*Iesults @ or selenium rc*))R  FF

In the ne%t section #ell e%plain ho# to build a test program using the generated code-

rogramming /our Test

No# #ell illustrate ho# to program your o#n tests using e%amples in each of the supported programming languages- There are essentiallyt#o tas's1

• >enerate your script into a programming language from Selenium,I(&+ optionally modifying the result-

• Write a .ery simple main program that e%ecutes the generated code-

6ptionally+ you can adopt a test engine platform li'e :5nit or TestN> for :a.a+ or N5nit for -N&T if you are using one of those languages-

Here+ #e sho# language,specific e%amples- The language,specific APIs tend to differ from one to another+ so youll find a separatee%planation for each-

:a.a • ! 

• Python 

• 2uby 

• Perl+ PHP 

Da'a

$or :a.a+ people use either :5nit or TestN> as the test engine- Some de.elopment en.ironments li'e &clipse ha.e direct support for these

i l i Thi ' it i T hi :5 it T tN> i b d th f thi d t h t i l b f d

Page 82: About Sellinum

8/11/2019 About Sellinum

http://slidepdf.com/reader/full/about-sellinum 82/173

.ia plug,ins- This ma'es it e.en easier- Teaching :5nit or TestN> is beyond the scope of this document ho#e.er materials may be foundonline and there are publications a.ailable- If you are already a Dja.a,shopE chances are your de.elopers #ill already ha.e some e%perience#ith one of these test frame#or's-

"ou #ill probably #ant to rename the test class from DNe#TestE to something of your o#n choosing- Also+ you #ill need to change thebro#ser,open parameters in the statement1

selenium new Deault$elenium(*localhost*E E *@iehta*E *http?//www+google+com/*)R

The Selenium,I(& generated code #ill loo' li'e this- This e%ample has comments added manually for additional clarity-

pacage com+e"ample+testsR// e speciy the pacage o our tests

import com+thoughtwors+selenium+@R// This is the drier9s import+ Mou9ll use this or instantiating a// browser and maing it do what you need+

import Kaa+util+rege"+&atternR// $elenium-PD add the &attern module because it9s sometimes used or

// rege" alidations+ Mou can remoe the module i it9s not used in your// script+

public class QewTest e"tends $eleneseTestCase // e create our $elenium test case

  public oid setJp() throws "ception   setJp(*http?//www+google+com/*E *@ireo"*)R  // e instantiate and start the browser  F

  public oid testQew() throws "ception

  selenium+open(*/*)R  selenium+type(*=*E *selenium rc*)R  selenium+clic(*btnW*)R  selenium+wait%or&ageTo,oad(*.5555*)R  assertTrue(selenium+isTe"t&resent(*Iesults @ or selenium rc*))R  // These are the real test steps  FF

CU

Page 83: About Sellinum

8/11/2019 About Sellinum

http://slidepdf.com/reader/full/about-sellinum 83/173

CU

The -N&T !lient (ri.er #or's #ith *icrosoft-N&T- It can be used #ith any -N&T testing frame#or' li'e N5nit or the 3isual Studio 788LTeam System-

Selenium,I(& assumes you #ill use N5nit as your testing frame#or'- "ou can see this in the generated code belo#- It includes the using statement for N5nit along #ith corresponding N5nit attributes identifying the role for each member function of the test class-

"ou #ill probably ha.e to rename the test class from DNe#TestE to something of your o#n choosing- Also+ you #ill need to change thebro#ser,open parameters in the statement1

selenium new Deault$elenium(*localhost*E E *@iehta*E *http?//www+google+com/*)R

The generated code #ill loo' similar to this-

"ou can allo# N5nit to manage the e%ecution of your tests- 6r alternati.ely+ you can #rite a simple main;< program that instantiates the testobject and runs each of the three methods+ SetupTest;<+ TheNe#Test;<+ and Teardo#nTest;< in turn-

ython

Pyunit is the test frame#or' to use for Python- To learn Pyunit refer to its official documentation Uhttp1GGdocs-python-orgGlibraryGunittest-htmlQ\-

The basic test structure is1

*uby

Selenium,I(& generates reasonable 2uby+ but re0uires the old Selenium gem- This is a problem because the official 2uby dri.er forSelenium is the Selenium,!lient gem+ not the old Selenium gem- In fact+ the Selenium gem is no longer e.en under acti.e de.elopment-

Therefore+ it is ad.isable to update any 2uby scripts generated by the I(& as follo#s1

F- 6n line F+ change re=uire *selenium* to re=uire *selenium/client*

7- 6n line FF+ change $elenium??$eleniumDrier+new to $elenium??Client??Drier+new

"ou probably also #ant to change the class name to something more informati.e than D5ntitled+E and change the test methods name tosomething other than Dtest\untitled-E

Here is a simple e%ample created by modifying the 2uby code generated by Selenium I(&+ as described abo.e-

l H

Page 84: About Sellinum

8/11/2019 About Sellinum

http://slidepdf.com/reader/full/about-sellinum 84/173

erl5 H

The members of the documentation team ha.e not used Selenium 2! #ith Perl or PHP- If you are using Selenium 2! #ith either of theset#o languages please contact the (ocumentation Team ;see the chapter on contributing<- We #ould lo.e to include some e%amples from youand your e%periences+ to support Perl and PHP users-

6earning the AIThe Selenium 2! API uses naming con.entions that+ assuming you understand Selenese+ much of the interface #ill be self,e%planatory-Here+ ho#e.er+ #e e%plain the most critical and possibly less ob.ious aspects-

Starting the Bro0ser

setJp(*http?//www+google+com/*E *@ireo"*)R

&ach of these e%amples opens the bro#ser and represents that bro#ser by assigning a Dbro#ser instanceE to a program .ariable- Thisprogram .ariable is then used to call methods from the bro#ser- These methods e%ecute the Selenium commands+ i-e- li'e open or type or the

verify commands-

The parameters re0uired #hen creating the bro#ser instance are1

host Specifies the IP address of the computer #here the ser.er is located- 5sually+ this is the same machine as #here the client is running+ soin this case localhost  is passed- In some clients this is an optional parameter-

port Specifies the T!PGIP soc'et #here the ser.er is listening #aiting for the client to establish a connection- This also is optional in someclient dri.ers-

bro0ser 

The bro#ser in #hich you #ant to run the tests- This is a re0uired parameter-url 

The base url of the application under test- This is re0uired by all the client libs and is integral information for starting up the bro#ser,pro%y,A5T communication-

Note that some of the client libraries re0uire the bro#ser to be started e%plicitly by calling its start/0 method-

*unning Commands

Page 85: About Sellinum

8/11/2019 About Sellinum

http://slidepdf.com/reader/full/about-sellinum 85/173

*unning Commands

6nce you ha.e the bro#ser initiali/ed and assigned to a .ariable ;generally named DseleniumE< you can ma'e it run Selenese commands bycalling the respecti.e methods from the bro#ser .ariable- $or e%ample+ to call the type method of the selenium object1

selenium-type;Dfield,idE+Estring to typeE<

In the bac'ground the bro#ser #ill actually perform a type operation+ essentially identical to a user typing input into the bro#ser+ by usingthe locator and the string you specified during the method call-

*eporting *esults

Selenium 2! does not ha.e its o#n mechanism for reporting results- 2ather+ it allo#s you to build your reporting customi/ed to your needsusing features of your chosen programming language- Thats great+ but #hat if you simply #ant something 0uic' thats already done foryou? 6ften an e%isting library or test frame#or' can meet your needs faster than de.eloping your o#n test reporting code-

Test 2rame0or% *eporting Tools

Test frame#or's are a.ailable for many programming languages- These+ along #ith their primary function of pro.iding a fle%ible test enginefor e%ecuting your tests+ include library code for reporting results- $or e%ample+ :a.a has t#o commonly used test frame#or's+ :5nit andTestN>- -N&T also has its o#n+ N5nit-

We #ont teach the frame#or's themsel.es here thats beyond the scope of this user guide- We #ill simply introduce the frame#or'features that relate to Selenium along #ith some techni0ues you can apply- There are good boo's a.ailable on these test frame#or'sho#e.er along #ith information on the internet-

Test *eport 6ibraries

Also a.ailable are third,party libraries specifically created for reporting test results in your chosen programming language- These oftensupport a .ariety of formats such as HT* or P($-

Page 86: About Sellinum

8/11/2019 About Sellinum

http://slidepdf.com/reader/full/about-sellinum 86/173

Test *eports for *uby

Page 87: About Sellinum

8/11/2019 About Sellinum

http://slidepdf.com/reader/full/about-sellinum 87/173

Test *eports for *uby

• If 2Spec frame#or' is used for #riting Selenium Test !ases in 2uby then its HT* report can be used to generate a test report-

2efer to 2Spec 2eport for more-

Note

If you are interested in a language independent log of #hats going on+ ta'e a loo' at Selenium Ser.er ogging

Adding Some Spice to /our Tests

No# #ell get to the #hole reason for using Selenium 2!+ adding programming logic to your tests- Its the same as for any program-Program flo# is controlled using condition statements and iteration- In addition you can report progress information using IG6- In this section#ell sho# some e%amples of ho# programming language constructs can be combined #ith Selenium to sol.e common testing problems-

"ou #ill find as you transition from the simple tests of the e%istence of page elements to tests of dynamic functionality in.ol.ing multiple#eb,pages and .arying data that you #ill re0uire programming logic for .erifying e%pected results- Basically+ the Selenium,I(& does notsupport iteration and standard condition statements- "ou can do some conditions by embedding ja.ascript in Selenese parameters+ ho#e.eriteration is impossible+ and most conditions #ill be much easier in a programming language- In addition+ you may need e%ception handlingfor error reco.ery- $or these reasons and others+ #e ha.e #ritten this section to illustrate the use of common programming techni0ues to gi.eyou greater .erification po#er in your automated testing-

The e%amples in this section are #ritten in ! and :a.a+ although the code is simple and can be easily adapted to the other supportedlanguages- If you ha.e some basic 'no#ledge of an object,oriented programming language you shouldnt ha.e difficulty understanding thissection-

Iteration

Iteration is one of the most common things people need to do in their tests- $or e%ample+ you may #ant to to e%ecute a search multiple times-

6r+ perhaps for .erifying your test results you need to process a Dresult setE returned from a database-5sing the same >oogle search e%ample #e used earlier+ lets chec' the Selenium search results- This test could use the Selenese1

open G

type 0 seleniumrc

clic'AndWait btn>

assertTe%tPresent 2esults

for

Page 88: About Sellinum

8/11/2019 About Sellinum

http://slidepdf.com/reader/full/about-sellinum 88/173

forseleniumrc

type 0 seleniumide

clic'AndWait btn>

assertTe%tPresent 2esults forseleniumide

 

type 0 seleniumgrid

clic'AndWait btn>

assertTe%tPresent 2esults for

seleniumgrid

 

The code has been repeated to run the same steps K times- But multiple copies of the same code is not good program practice because itsmore #or' to maintain- By using a programming language+ #e can iterate o.er the search results for a more fle%ible and maintainablesolution-

In CUK

// Collection o $tring alues+$tring67 arr *ide*E *rc*E *grid*FR

// "ecute loop or each $tring in array 9arr9+

oreach ($tring s in arr)   sel+open(*/*)R  sel+type(*=*E *selenium * s)R  sel+clic(*btnW*)R  sel+wait%or&ageTo,oad(*.5555*)R  assertTrue(*"pected te"t? * s * is missing on page+*  E sel+isTe"t&resent(*Iesults @ or selenium * s))R F

Condition Statements

Page 89: About Sellinum

8/11/2019 About Sellinum

http://slidepdf.com/reader/full/about-sellinum 89/173

Condition Statements

To illustrate using conditions in tests #ell start #ith an e%ample- A common problem encountered #hile running Selenium tests occurs#hen an e%pected element is not a.ailable on page- $or e%ample+ #hen running the follo#ing line1

selenium+type(*=*E *selenium * s)R

If element 0 is not on the page then an e%ception is thro#n1

com+thoughtwors+selenium+$elenium"ception? III? lement = not ound

This can cause your test to abort- $or some tests thats #hat you #ant- But often that is not desirable as your test script has many othersubse0uent tests to perform-

A better approach is to first .alidate #hether the element is really present and then ta'e alternati.es #hen it it is not- ets loo' at this using:a.a-

// P element is aailable on page then perorm type operation+i(selenium+islement&resent(*=*))   selenium+type(*=*E *$elenium rc*)R

F else   $ystem+out+print(*lement? * = * is not aailable on page+*)F

The ad.antage of this approach is to continue #ith test e%ecution e.en if some 5I elements are not a.ailable on page-

,3ecuting Da'aScript from /our Test

:a.aScript comes .ery handy in e%ercising an application #hich is not directly supported by selenium- The get,'al method of selenium APIcan be used to e%ecute :a.aScript from selenium 2!-

!onsider an application ha.ing chec' bo%es #ith no static identifiers- In this case one could e.aluate :a.aScript from selenium 2! to get idsof all chec' bo%es and then e%ercise them-

public static $tring67 get:llChecbo"Pds ()   $tring script *ar inputPd new :rray()R*R// Create array in Kaa script+  script *ar cnt 5R*R // Counter or chec bo" ids+  script *ar input%ields new :rray()R*R // Create array in Kaa script+  script *input%ields window+document+getlementsOyTagQame(9input9)R*R // Collect inputelements+  script *or(ar i5R i<input%ields+lengthR i) *R // ,oop through the collected elements+  script *i(input%ields6i7+id !null *

  *\\ input%ields6i7+id !9undeined9 *

Page 90: About Sellinum

8/11/2019 About Sellinum

http://slidepdf.com/reader/full/about-sellinum 90/173

p  *\\ input%ields6i7+get:ttribute(9type9) 9checbo"9) *R // P input ield is o type chec bo"and input id is not null+  script *inputPd6cnt7input%ields6i7+id R* // $ae chec bo" id to inputPd array+  *cntR* // increment the counter+  *F* // end o i+  *F*R // end o or+  script *inputPd+to$tring()R* R// Conert array in to string+

  $tring67 checbo"Pds selenium+getal(script)+split(*E*)R // $plit the string+  return checbo"PdsR F

To count number of images on a page1

selenium+getal(*window+document+images+lengthR*)R

2emember to use #indo# object in case of (6* e%pressions as by default selenium #indo# is referred to+ not the test #indo#-

Ser'er OptionsWhen the ser.er is launched+ command line options can be used to change the default ser.er beha.iour-

2ecall+ the ser.er is started by running the follo#ing-

Z Kaa -Kar selenium-serer-standalone-<ersion-number>+Kar

To see the list of options+ run the ser.er #ith the -h option-

Z Kaa -Kar selenium-serer-standalone-<ersion-number>+Kar -h

"oull see a list of all the options you can use #ith the ser.er and a brief description of each- The pro.ided descriptions #ill not al#ays be

enough+ so #e.e pro.ided e%planations for some of the more important options-

ro3y Configuration

If your A5T is behind an HTTP pro%y #hich re0uires authentication then you should configure http-pro%yHost+ http-pro%yPort+http-pro%y5ser and http-pro%yPass#ord using the follo#ing command-

Z Kaa -Kar selenium-serer-standalone-<ersion-number>+Kar -Dhttp+pro"yLostpro"y+com -Dhttp+pro"y&ort3535-Dhttp+pro"yJserusername -Dhttp+pro"y&asswordpassword

7ulti-Windo0 7ode

Page 91: About Sellinum

8/11/2019 About Sellinum

http://slidepdf.com/reader/full/about-sellinum 91/173

7ulti Windo0 7ode

If you are using Selenium F-8 you can probably s'ip this section+ since multi#indo# mode is the default beha.ior- Ho#e.er+ prior to .ersionF-8+ Selenium by default ran the application under test in a sub frame as sho#n here- 

Some applications didnt run correctly in a sub frame+ and needed to be loaded into the top frame of the #indo#- The multi,#indo# mode

option allo#ed the A5T to run in a separate #indo# rather than in the default frame #here it could then ha.e the top frame it re0uired- 

$or older .ersions of Selenium you must specify multi#indo# mode e%plicitly #ith the follo#ing option1

-multiwindow

As of Selenium 2! F-8+ if you #ant to run your test #ithin a single frame ;i-e- using the standard for earlier Selenium .ersions< you can statethis to the Selenium Ser.er using the option

-singlewindow

Specifying the 2irefo3 rofile

$irefo% #ill not run t#o instances simultaneously unless you specify a separate profile for each instance- Selenium 2! F-8 and later runs in aseparate profile automatically+ so if you are using Selenium F-8+ you can probably s'ip this section- Ho#e.er+ if youre using an older.ersion of Selenium or if you need to use a specific profile for your tests ;such as adding an https certificate or ha.ing some addonsinstalled<+ you #ill need to e%plicitly specify the profile-

$irst+ to create a separate $irefo% profile+ follo# this procedure- 6pen the Windo#s Start menu+ select D2unE+ then type and enter one of thefollo#ing1

ireo"+e"e -proilemanager

ireo"+e"e -&

!reate the ne# profile using the dialog- Then #hen you run Selenium Ser.er+ tell it to use this ne# $irefo% profile #ith the ser.er command,line option firefo%&rofileemplate and specify the path to the profile using its filename and directory path-

-ireo"&roileTemplate *path to the proile*

Warning

Page 92: About Sellinum

8/11/2019 About Sellinum

http://slidepdf.com/reader/full/about-sellinum 92/173

This message may be multiline-

Page 93: About Sellinum

8/11/2019 About Sellinum

http://slidepdf.com/reader/full/about-sellinum 93/173

g y

Bro0ser-Side 6ogs

:a.aScript on the bro#ser side ;Selenium !ore< also logs important messages in many cases+ these can be more useful to the end,user thanthe regular Selenium Ser.er logs- To access bro#ser,side logs+ pass the -bro0serSide6og  argument to the Selenium Ser.er-

Kaa -Kar selenium-serer-standalone-<ersion-number>+Kar -browser$ide,og

-bro0serSide6og  must be combined #ith the -log argument+ to log bro#serSideogs ;as #ell as all other (&B5> le.el logging messages<to a file-

Specifying the ath to a Specific Bro0ser

"ou can specify to Selenium 2! a path to a specific bro#ser- This is useful if you ha.e different .ersions of the same bro#ser and you #ishto use a specific one- Also+ this is used to allo# your tests to run against a bro#ser not directly supported by Selenium 2!- When specifyingthe run mode+ use the custom specifier follo#ed by the full path to the bro#sers e%ecutable1

@custom <path to browser>

Selenium *C Architecture

Note

This topic tries to e%plain the technical implementation behind Selenium 2!- Its not fundamental for a Selenium user to 'no# this+ butcould be useful for understanding some of the problems you might find in the future-

To understand in detail ho# Selenium 2! Ser.er #or's and #hy it uses pro%y injection and heightened pri.ilege modes you must firstunderstand the same origin policy-

The Same Origin olicy

Page 94: About Sellinum

8/11/2019 About Sellinum

http://slidepdf.com/reader/full/about-sellinum 94/173

g y

The main restriction that Selenium faces is the Same 6rigin Policy- This security restriction is applied by e.ery bro#ser in the mar'et and itsobjecti.e is to ensure that a sites content #ill ne.er be accessible by a script from another site- The Same 6rigin Policy dictates that anycode loaded #ithin the bro#ser can only operate #ithin that #ebsites domain- It cannot perform functions on another #ebsite- So fore%ample+ if the bro#ser loads :a.aScript code #hen it loads ###-mysite-com+ it cannot run that loaded code against ###-mysite7-com) e.en if thats another of your sites- If this #ere possible+ a script placed on any #ebsite you open #ould be able to read information on your

ban' account if you had the account page opened on other tab- This is called OSS ;!ross,site Scripting<-

To #or' #ithin this policy+ Selenium,!ore ;and its :a.aScript commands that ma'e all the magic happen< must be placed in the same originas the Application 5nder Test ;same 52<-

Historically+ Selenium,!ore #as limited by this problem since it #as implemented in :a.aScript- Selenium 2! is not+ ho#e.er+ restricted bythe Same 6rigin Policy- Its use of the Selenium Ser.er as a pro%y a.oids this problem- It+ essentially+ tells the bro#ser that the bro#ser is#or'ing on a single DspoofedE #ebsite that the Ser.er pro.ides-

Note

"ou can find additional information about this topic on Wi'ipedia pages about Same 6rigin Policy and OSS-

ro3y In!ection

The first method Selenium used to a.oid the The Same 6rigin Policy #as Pro%y Injection- In Pro%y Injection *ode+ the Selenium Ser.eracts as a client,configured RF HTT pro3y R7+ that sits bet#een the bro#ser and the Application 5nder Test- It then mas's the A5T under afictional 52 ;embedding Selenium,!ore and the set of tests and deli.ering them as if they #ere coming from the same origin<-

RF The pro%y is a third person in the middle that passes the ball bet#een the t#o parts- It acts as a D#eb ser.erE that deli.ers the A5T to thebro#ser- Being a pro%y gi.es Selenium Ser.er the capability of DlyingE about the A5Ts real 52-

R7 The bro#ser is launched #ith a configuration profile that has set localhost19999 as the HTTP pro%y+ this is #hy any HTTP re0uest thatthe bro#ser does #ill pass through Selenium ser.er and the response #ill pass through it and not from the real ser.er-

Here is an architectural diagram- 

As a test suite starts in your fa.orite language+ the follo#ing happens1

F- The clientGdri.er establishes a connection #ith the selenium,2! ser.er-7- Selenium 2! ser.er launches a bro#ser ;or reuses an old one< #ith a 52 that injects Selenium,!ores :a.aScript into the bro#ser,

loaded #eb page-

K- The client,dri.er passes a Selenese command to the ser.er-

Page 95: About Sellinum

8/11/2019 About Sellinum

http://slidepdf.com/reader/full/about-sellinum 95/173

9- The Ser.er interprets the command and then triggers the corresponding :a.aScript e%ecution to e%ecute that command #ithin thebro#ser- Selenium,!ore instructs the bro#ser to act on that first instruction+ typically opening a page of the A5T-

L- The bro#ser recei.es the open re0uest and as's for the #ebsites content from the Selenium 2! ser.er ;set as the HTTP pro%y for thebro#ser to use<-

=- Selenium 2! ser.er communicates #ith the Web ser.er as'ing for the page and once it recei.es it+ it sends the page to the bro#sermas'ing the origin to loo' li'e the page comes from the same ser.er as Selenium,!ore ;this allo#s Selenium,!ore to comply #iththe Same 6rigin Policy<-

- The bro#ser recei.es the #eb page and renders it in the frameG#indo# reser.ed for it-

Heightened ri'ileges Bro0sers

This #or'flo# in this method is .ery similar to Pro%y Injection but the main difference is that the bro#sers are launched in a special modecalled Heightened &rivileges+ #hich allo#s #ebsites to do things that are not commonly permitted ;as doing OSS+ or filling file uploadinputs and pretty useful stuff for Selenium<- By using these bro#ser modes+ Selenium !ore is able to directly open the A5T and readGinteract#ith its content #ithout ha.ing to pass the #hole A5T through the Selenium 2! ser.er-

Here is the architectural diagram- 

As a test suite starts in your fa.orite language+ the follo#ing happens1

F- The clientGdri.er establishes a connection #ith the selenium,2! ser.er-7- Selenium 2! ser.er launches a bro#ser ;or reuses an old one< #ith a 52 that #ill load Selenium,!ore in the #eb page-K- Selenium,!ore gets the first instruction from the clientGdri.er ;.ia another HTTP re0uest made to the Selenium 2! Ser.er<-9- Selenium,!ore acts on that first instruction+ typically opening a page of the A5T-L- The bro#ser recei.es the open re0uest and as's the Web Ser.er for the page- 6nce the bro#ser recei.es the #eb page+ renders it in

the frameG#indo# reser.ed for it-

Handling HTTS and Security opups

*any applications s#itch from using HTTP to HTTPS #hen they need to send encrypted information such as pass#ords or credit cardinformation- This is common #ith many of todays #eb applications- Selenium 2! supports this-

To ensure the HTTPS site is genuine+ the bro#ser #ill need a security certificate- 6ther#ise+ #hen the bro#ser accesses the A5T usingHTTPS+ it #ill assume that application is not trusted- When this occurs the bro#ser displays security popups+ and these popups cannot beclosed using Selenium 2!-

Page 96: About Sellinum

8/11/2019 About Sellinum

http://slidepdf.com/reader/full/about-sellinum 96/173

Page 97: About Sellinum

8/11/2019 About Sellinum

http://slidepdf.com/reader/full/about-sellinum 97/173

on the same machine- To do this use DlocalhostE as your connection parameter- We recommend beginning this #ay since it reduces thefl f l ' bl h h d h l ' d

Page 98: About Sellinum

8/11/2019 About Sellinum

http://slidepdf.com/reader/full/about-sellinum 98/173

influence of potential net#or'ing problems #hich youre getting started- Assuming your operating system has typical net#or'ing andT!PGIP settings you should ha.e little difficulty- In truth+ many people choose to run the tests this #ay-

If+ ho#e.er+ you do #ant to run Selenium Ser.er on a remote machine+ the connecti.ity should be fine assuming you ha.e .alid T!PGIPconnecti.ity bet#een the t#o machines-

If you ha.e difficulty connecting+ you can use common net#or'ing tools li'e ping+ telnet + ifconfig/)ni%06ipconfig ;Windo#s<+ etc to ensure

you ha.e a .alid net#or' connection- If unfamilar #ith these+ your system administrator can assist you-

@nable to 6oad the Bro0ser

6'+ not a friendly error message+ sorry+ but if the Selenium Ser.er cannot load the bro#ser you #ill li'ley see this error-

(055) Pnternal $erer rror

This could be caused by

• $irefo% ;prior to Selenium F-8< cannot start because the bro#ser is already open and you did not specify a separate profile- See the

section on $irefo% profiles under Ser.er 6ptions-• The run mode youre using doesnt match any bro#ser on your machine- !hec' the parameters you passed to Selenium #hen you

program opens the bro#ser-

• "ou specified the path to the bro#ser e%plicitly ;using DcustomE)see abo.e< but the path is incorrect- !hec' to be sure the path is

correct- Also chec' the user group to be sure there are no 'no#n issues #ith your bro#ser and the DcustomE parameters-

Selenium Cannot 2ind the A@T

If your test program starts the bro#ser successfully+ but the bro#ser doesnt display the #ebsite youre testing+ the most li'ely cause is yourtest program is not using the correct 52-

This can easily happen- When you use Selenium,I(& to e%port your script+ it inserts a dummy 52- "ou must manually change the 52 tothe correct one for your application to be tested-

2irefo3 *efused Shutdo0n While reparing a rofile

This most often occurs #hen your run your Selenium 2! test program against $irefo%+ but you already ha.e a $irefo% bro#ser sessionrunning and+ you didnt specify a separate profile #hen you started the Selenium Ser.er- The error from the test program loo's li'e this1

rror? Kaa+lang+Iuntime"ception? %ireo" reused shutdown while

preparing a proile

Page 99: About Sellinum

8/11/2019 About Sellinum

http://slidepdf.com/reader/full/about-sellinum 99/173

Heres the complete error message from the ser.er1

'1?#5?5.+4'4 PQ% - &reparing %ireo" proile+++'1?#5?#2+3## :IQ - WT /selenium-serer/drier/;cmdgetQewOrowser$ession\'@ireo"\#http[.a[#[#sage-webapp'+=a+idc+com LTT&/'+'Kaa+lang+Iuntime"ception? %ireo" reused shutdown while preparing a proile

  at org+open=a+selenium+serer+browserlaunchers+%ireo"Custom&roile,auncher+wait%or%ull&roileToOeCreated(%ireo"Custom&roile,auncher+Kaa?#22)+++Caused by? org+open=a+selenium+serer+browserlaunchers+%ireo"Custom&roile,auncherZ%ile,ocIemained"ception? ,oc ile still present! C?]DCJN^']Ksec],C:,$^']Temp]custom&roileDir#5.'.3]parent+loc

To resol.e this+ see the section on Specifying a Separate $irefo% Profile

ersioning roblems

*a'e sure your .ersion of Selenium supports the .ersion of your bro#ser- $or e%ample+ Selenium 2! 8-C7 does not support $irefo% K- Attimes you may be luc'y ;I #as<- But dont forget to chec' #hich bro#ser .ersions are supported by the .ersion of Selenium you are using-When in doubt+ use the latest release .ersion of Selenium #ith the most #idely used .ersion of your bro#ser-

,rror messageK $@nsupported ma!or&minor 'ersion <=&1( 0hile starting ser'er

This error says youre not using a correct .ersion of :a.a- The Selenium Ser.er re0uires :a.a F-L or higher-

To chec' double,chec' your ja.a .ersion+ run this from the command line-

Kaa -ersion

"ou should see a message sho#ing the :a.a .ersion-

Kaa ersion *'+0+5S52*Yaa(TN) # Iuntime nironmentE $tandard dition (build '+0+5S52-b5.)Yaa Lot$pot(TN) Client VN (build '+0+5S52-b5.E mi"ed mode)

If you see a lo#er .ersion number+ you may need to update the :2&+ or you may simply need to add it to your PATH en.ironment .ariable-

<1< error 0hen running the getNe0Bro0serSession command

Page 100: About Sellinum

8/11/2019 About Sellinum

http://slidepdf.com/reader/full/about-sellinum 100/173

If youre getting a 989 error #hile attempting to open a page on D http1GG###-google-comGselenium,ser.erG E+ then it must be because theSelenium Ser.er #as not correctly configured as a pro%y- The Dselenium,ser.erE directory doesnt e%ist on google-com it only appears toe%ist #hen the pro%y is properly configured- Pro%y !onfiguration highly depends on ho# the bro#ser is launched #ith firefo%+ ie%plore+opera+ or custom-

• ie%plore1 If the bro#ser is launched using ie%plore+ you could be ha.ing a problem #ith Internet &%plorers

pro%y settings- Selenium Ser.er attempts To configure the global pro%y settings in the Internet 6ptions!ontrol Panel- "ou must ma'e sure that those are correctly configured #hen Selenium Ser.er launches thebro#ser- Try loo'ing at your Internet 6ptions control panel- !lic' on the D!onnectionsE tab and clic' onDAN SettingsE-

• If you need to use a pro%y to access the application you #ant to test+ youll need to start Selenium

Ser.er #ith D,(http-pro%yHostE see the Pro%y !onfiguration for more details-

• "ou may also try configuring your pro%y manually and then launching the bro#ser #ith custom+ or

#ith iehta bro#ser launcher-

custom1 When using custom you must configure the pro%y correctly;manually<+

other#ise youll get a 989 error- (ouble,chec' that you.e configured your pro%y settings correctly- To chec'#hether you.e configured the pro%y correctly is to attempt to intentionally configure the bro#ser incorrectly- Tryconfiguring the bro#ser to use the #rong pro%y ser.er hostname+ or the #rong port- If you had successfullyconfigured the bro#sers pro%y settings incorrectly+ then the bro#ser #ill be unable to connect to the Internet+#hich is one #ay to ma'e sure that one is adjusting the rele.ant settings-

• $or other bro#sers ;firefo%+ opera< #e automatically hard,code the pro%y for you+ and so ther are no 'no#n issues #ith

this functionality- If youre encountering 989 errors and ha.e follo#ed this user guide carefully post your results to usergroup for some help from the user community-

ermission +enied ,rror

The most common reason for this error is that your session is attempting to .iolate the same,origin policy by crossing domain boundaries;e-g-+ accesses a page from http1GGdomainF and then accesses a page from http1GGdomain7< or s#itching protocols ;mo.ing fromhttp1GGdomainO to https1GGdomainO<-

This error can also occur #hen :a.aScript attempts to find 5I objects #hich are not yet a.ailable ;before the page has completely loaded<+ orl g il bl ; ft th g h t t d t b l d d< Thi i t t i ll t d ith A:AO g hi h 'i g

Page 101: About Sellinum

8/11/2019 About Sellinum

http://slidepdf.com/reader/full/about-sellinum 101/173

are no longer a.ailable ;after the page has started to be unloaded<- This is most typically encountered #ith A:AO pages #hich are #or'ing#ith sections of a page or subframes that load andGor reload independently of the larger page-

This error can be intermittent- 6ften it is impossible to reproduce the problem #ith a debugger because the trouble stems from raceconditions #hich are not reproducible #hen the debuggers o.erhead is added to the system- Permission issues are co.ered in some detail inthe tutorial- 2ead the section about the The Same 6rigin Policy+ Pro%y Injection carefully-

Handling Bro0ser opup Windo0s

There are se.eral 'inds of DPopupsE that you can get during a Selenium test- "ou may not be able to close these popups by running seleniumcommands if they are initiated by the bro#ser and not your A5T- "ou may need to 'no# ho# to manage these- &ach type of popup needs tobe addressed differently-

• HTTP basic authentication dialogs1 These dialogs prompt for a usernameGpass#ord to login to the site- To login to a site

that re0uires HTTP basic authentication+ use a username and pass#ord in the 52+ as described in 2$! FK@+ li'e this1open;Dhttp1GGmyusername1myuserpass#ord]mye%ample-comGblahGblahGblahE<-

• SS certificate #arnings1 Selenium 2! automatically attempts to spoof SS certificates #hen it is enabled as a pro%y see

more on this in the section on HTTPS- If your bro#ser is configured correctly+ you should ne.er see SS certificate#arnings+ but you may need to configure your bro#ser to trust our dangerous D!yber3illainsE SS certificate authority-Again+ refer to the HTTPS section for ho# to do this-

• modal :a.aScript alertGconfirmationGprompt dialogs1 Selenium tries to conceal those dialogs from you ;by replacing

#indo#-alert+ #indo#-confirm and #indo#-prompt< so they #ont stop the e%ecution of your page- If youre seeing analert pop,up+ its probably because it fired during the page load process+ #hich is usually too early for us to protect thepage- Selenese contains commands for asserting or .erifying alert and confirmation popups- See the sections on thesetopics in !hapter 9-

On 6inu35 0hy isn"t my 2irefo3 bro0ser session closing?

6n 5ni%Ginu% you must in.o'e Dfirefo%,binE directly+ so ma'e sure that e%ecutable is on the path- If e%ecuting $irefo% through a shellscript+ #hen it comes time to 'ill the bro#ser Selenium 2! #ill 'ill the shell script+ lea.ing the bro#ser running- "ou can specify the path tofirefo%,bin directly+ li'e this-

cmdgetQewOrowser$ession\'@ireo" /usr/local/ireo"/ireo"-bin\#http?//www+google+com

2irefo3 9chrome doesn"t 0or% 0ith custom profile

Page 102: About Sellinum

8/11/2019 About Sellinum

http://slidepdf.com/reader/full/about-sellinum 102/173

!hec' $irefo% profile folder ,Q prefs-js ,Q user\pref;Dbro#ser-startup-pageE+ 8< !omment this line li'e this1DGGuser\pref;Dbro#ser-startup-pageE+ 8<E and try again-

Is it o% to load a custom pop-up as the parent page is loading $i&e&5 before the parent page"s !a'ascript

0indo0&onload$( function runs(?No- Selenium relies on interceptors to determine #indo# names as they are being loaded- These interceptors #or' best in catching ne##indo#s if the #indo#s are loaded A$T&2 the onload;< function- Selenium may not recogni/e #indo#s loaded before the onload function-

roblems With erify Commands

If you e%port your tests from Selenium,I(&+ you may find yourself getting empty .erify strings from your tests ;depending on theprogramming language used<-

 Note: his section is not yet developed.

Safari and 7ultiWindo0 7ode

 Note: his section is not yet developed.

2irefo3 on 6inu3

6n 5ni%Ginu%+ .ersions of Selenium before F-8 needed to in.o'e Dfirefo%,binE directly+ so if you are using a pre.ious .ersion+ ma'e surethat the real e%ecutable is on the path-

6n most inu% distributions+ the real firefo%bin is located on1

/usr/lib/ireo"-"+"+"/

Where the %-%-% is the .ersion number you currently ha.e- So+ to add that path to the users path- you #ill ha.e to add the follo#ing toyour -bashrc file1

e"port &:TL*Z&:TL?/usr/lib/ireo"-"+"+"/*

If necessary+ you can specify the path to firefo%,bin directly in your test+ li'e this1

*@ireo" /usr/lib/ireo"-"+"+"/ireo"-bin*

I, and Style Attributes

Page 103: About Sellinum

8/11/2019 About Sellinum

http://slidepdf.com/reader/full/about-sellinum 103/173

If you are running your tests on Internet &%plorer and you cannot locate elements using their style attribute- $or e%ample1

//td68style*bacground-color?yellow*7

This #ould #or' perfectly in $irefo%+ 6pera or Safari but not #ith I&- I& interprets the 'eys in Jstyle as uppercase- So+ e.en if the sourcecode is in lo#ercase+ you should use1

//td68style*O:CXWIJQD-C,I?yellow*7

This is a problem if your test is intended to #or' on multiple bro#sers+ but you can easily code your test to detect the situation and try thealternati.e locator that only #or's in I&-

,rror encountered - Cannot con'ert ob!ect to primiti'e 'alue 0ith shut do0n of 9googlechrome bro0ser

To a.oid this error you ha.e to start bro#ser #ith an option that disables same origin policy chec's1

selenium+start(*command,ine%lags--disable-web-security*)R

Where can I As% uestions that Aren"t Ans0ered Here?

Try our user group

Table Of Contents

• Test (esign !onsiderations

• Introducing Test (esign 

• Types of Tests 

• 3alidating 2esults 

• ocation Strategies 

• Wrapping Selenium !alls 

• 5I *apping 

• Page 6bject (esign Pattern 

• (ata (ri.en Testing 

• (atabase 3alidation 

Page 104: About Sellinum

8/11/2019 About Sellinum

http://slidepdf.com/reader/full/about-sellinum 104/173

Test +esign Considerations

Introducing Test +esign

We.e pro.ided in this chapter information that #ill be useful to both those ne# to test automation and for the e%perienced 4A professional-Here #e describe the most common types of automated tests- We also describe design patterns commonly used in test automation forimpro.ing the maintenance and e%tensibily of your automation suite- The more e%perienced reader #ill find these interesting if not alreadyusing these techni0ues-

Types of Tests

What parts of your application should you test? That depends on aspects of your project1 user e%pectations+ time allo#ed for the project+priorities set by the project manager and so on- 6nce the project boundaries are defined though+ you+ the tester+ #ill certainly ma'e manydecisions on #hat to test-

We.e created a fe# terms here for the purpose of categori/ing the types of test you may perform on your #eb application- These terms areby no means standard+ although the concepts #e present here are typical for #eb,application testing-

Testing Static Content

The simplest type of test+ a content test + is a simple test for the e%istence of a static+ non,changing+ 5I element- $or instance

• (oes each page ha.e its e%pected page title? This can be used to .erify your test found an e%pected page after follo#ing a lin'-• (oes the applications home page contain an image e%pected to be at the top of the page?

• (oes each page of the #ebsite contain a footer area #ith lin's to the company contact page+ pri.acy policy+ and trademar's

information?

• (oes each page begin #ith heading te%t using the UhFQ tag? And+ does each page ha.e the correct te%t #ithin that header?

"ou 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 contentmanually- If+ for e%ample+ your application in.ol.es files being mo.ed to different locations+ content tests may pro.e .aluable-

Testing 6in%s

Page 105: About Sellinum

8/11/2019 About Sellinum

http://slidepdf.com/reader/full/about-sellinum 105/173

A fre0uent source of errors for #eb,sites is bro'en lin's or missing pages behind lin's- Testing in.ol.es clic'ing each lin' and .erifying thee%pected page- If static lin's are infre0uently changed then manual testing may be sufficient- Ho#e.er if your #eb designers fre0uently alterlin's+ or if files are occasionally relocated+ lin' tests should be automated-

2unction Tests

These #ould be tests of a specific function #ithin your application+ re0uiring some type of user input+ and returning some type of results-6ften a function test #ill in.ol.e multiple pages #ith a form,based input page containing a collection of input fields+ Submit and !anceloperations+ and one or more response pages- 5ser input can be .ia te%t,input fields+ chec' bo%es+ drop,do#n lists+ or any other bro#ser,supported input-

$unction tests are often the most comple% tests youll automate+ but are usually the most important- Typical tests can be for login+registration to the site+ user account operations+ account settings changes+ comple% data retrie.al operations+ among others- $unction teststypically mirror the user,scenarios used to specify the features and design or your application-

Testing +ynamic ,lements6ften a #eb page element has a uni0ue identifier used to uni0uely locate that element #ithin the page- 5sually these are implemented usingthe html tags id attribute or its name attribute- These names can be a static+ i-e unchanging+ string constant- They can also be dynamicallygenerated .alues that .ary each instance of the page- $or e%ample+ some #eb ser.ers might name a displayed document docK@=F oneinstance of a page+ and doc=F9@ on a different instance of the page depending on #hat document the user #as retrie.ing- A test script.erifying that a document e%ists may not ha.e a consistent identifier to use for locating that document- 6ften+ dynamic elements #ith.arying identifiers are on some type of result page based on a user action- This though certainly depends on the function of the #ebapplication-

Heres an e%ample-

<input type*checbo"* alue*true* id*add%orm?SPD2?SPD20?5?SPD24?5?  checOo"*/>

This sho#s an HT* tag for a chec' bo%- Its I( ;add$orm1\I(91\I(L181\I(C181chec'Bo%< is a dynamically generated .alue- The ne%ttime the same page is opened it #ill li'ely be a different .alue-

A!a3 Tests

Aja% is a technology #hich supports dynamically changing user interface elements #hich can dynamically change #ithout the bro#ser

ha.ing to reload the page+ such as animation+ 2SS feeds+ and real,time data updates among others- Theres a countless #ays Aja% can beused to update elements on a #eb page But the easy #ay to thin' of this is that in Aja%,dri.en applications data can retrie.ed from the

Page 106: About Sellinum

8/11/2019 About Sellinum

http://slidepdf.com/reader/full/about-sellinum 106/173

used to update elements on a #eb page- But+ the easy #ay to thin' of this is that in Aja% dri.en applications+ data can retrie.ed from theapplication ser.er and then displayed on the page #ithout reloading the entire page- 6nly a portion of the page+ or strictly the element itselfis reloaded-

alidating *esults

Assert 's& erify

When should you use an assert command and #hen should you use a .erify command? This is up to you- The difference is in #hat you #antto happen #hen the chec' fails- (o you #ant your test to terminate+ or to continue and simply record that the chec' failed?

Heres the trade,off- If you use an assert+ the test #ill stop at that point and not run any subse0uent chec's- Sometimes+ perhaps often+ that is#hat you #ant- If the test fails you #ill immediately 'no# the test did not pass- Test engines such as TestN> and :5nit ha.e plugins forcommonly used de.elopment en.ironments ;!hap L< #hich con.eniently flag these tests as failed tests- The ad.antage1 you ha.e animmediate .isual of #hether the chec's passed- The disad.antage1 #hen a chec' does fail+ there are other chec's #hich #ere ne.erperformed+ so you ha.e no information on their status-

In contrast+ .erify commands #ill not terminate the test- If your test uses only .erify commands you are guaranteed ;assuming noune%pected e%ceptions< the test #ill run to completion #hether the chec's find defects or not- The disad.antage1 you ha.e to do more #or'to e%amine your test results- That is+ you #ont get feedbac' from TestN> or :5nit- "ou #ill need to loo' at the results of a console printoutor a log output- And you #ill need to ta'e the time to loo' through this output e.ery time you run your test- If you are running hundreds oftests+ each #ith its o#n log+ this #ill be time,consuming+ and the immediate feedbac' of asserts #ill be more appropriate- Asserts are morecommonly used than .erifys due to their immediate feedbac'-

Trade-offsK assertTextPresent 5 assertElementPresent 5 assertText 

"ou should no# be familiar #ith these commands+ and the mechanics of using them- If not+ please refer to !hapter K first- Whenconstructing your tests+ you #ill need to decide

• (o I only chec' that the te%t e%ists on the page? ;verify6asserte%t&resent <

• (o I only chec' that the HT* element e%ists on the page? That is+ the te%t+ image+ or other content is not to be chec'ed+ only the

HT* tag is #hat is rele.ant- ;verify6assert'lement&resent <

• *ust I test both+ the element and its te%t content? ;verify6asserte%t <

There is no right ans#er- It depends on the re0uirements for your test- Which+ of course+ depend on the re0uirements for the applicationyoure testing- If in doubt+ use asserte%t  since this is the strictest type of chec'point- "ou can al#ays change it later but at least you #ont be

missing any potential failures-

5 if 6 i h ifi Thi f il if i h h HT* l ; < 62 h i h i i

Page 107: About Sellinum

8/11/2019 About Sellinum

http://slidepdf.com/reader/full/about-sellinum 107/173

5erify6asserte%t  is the most specific test  type- This can fail if either the HT* element ;tag< 62 the te%t is not #hat your test is e%pecting-Perhaps your #eb,designers are fre0uently changing the page and you dont #ant your test to fail e.ery time they do this because thechanges themsel.es are e%pected periodically- Ho#e.er+ assume you still need to chec' that something is on the page+ say a paragraph+ orheading te%t+ or an image- In this case you can use verify6assert'lement&resent - It #ill ensure that a particular type of element e%ists ;and ifusing OPath can ensure it e%ists relati.e to other objects #ithin the page<- But you dont care #hat the content is- "ou only care that a

specific element+ say+ an image+ is at a specific location->etting a feel for these types of decisions #ill come #ith time and a little e%perience- They are easy concepts+ and easy to change in yourtest-

6ocation Strategies

Choosing a 6ocation Strategy

There are multiple #ays of selecting an object on a page- But #hat are the trade offs of each of these locator types? 2ecall #e can locate an

object using• the elements I(

• the elements name attribute

• an OPath statement

• by a lin's te%t

• document object model ;(6*<

5sing an element I( or name locator is the most efficient in terms of test performance+ and also ma'es your test code more readable+assuming the I( or name #ithin the page source is #ell,named- OPath statements ta'e longer to process since the bro#ser must run itsOPath processor- OPath has been 'no#n to be especially slo# in Internet &%plorer .ersion - ocating .ia a lin's te%t is often con.enient

and performs #ell- This techni0ue is specific to lin's though- Also+ if the lin' te%t is li'ely to change fre0uently+ locating by the UaQ element#ould be the better choice-

Sometimes though+ you must use an OPath locator- If the page source does not ha.e an I( or name attribute you may ha.e no choice but touse an OPath locator- ;(6* locators are no longer commonly used since OPath can do e.erything they can and more- (6* locators area.ailable simply to support legacy tests-<

There is an ad.antage to using OPath that locating .ia I( or name attributes do not ha.e- With OPath ;and (6*< you can locate an object#ith respect to another object on the page- $or e%ample+ if there is a lin' that must occur #ithin the second paragraph #ithin a Udi.Q section+you can use OPath to specify this- With I( and name locators+ you can only specify that they occur on the page that is+ some#here on the

page- If you must test that an image displaying the company logo appears at the top of the page #ithin a header section OPath may be thebetter locator-6ocating +ynamic ,lements

Page 108: About Sellinum

8/11/2019 About Sellinum

http://slidepdf.com/reader/full/about-sellinum 108/173

better locator-6ocating +ynamic ,lements

As #as described earlier in the section on types of tests+ a dynamic element is a page element #hose identifer .aries #ith each instance ofthe page- $or e%ample+

<a class*button* id*adminLome%orm* onclic*return oam$ubmit%orm(9adminLome%orm9E  9adminLome%orm?SPD.39)R* hre**>View :rchied :llocation ents</a>

This HT* anchor tag defines a button #ith an I( attribute of DadminHome$ormE- Its a fairly comple% anchor tag #hen compared to mostHT* tags+ but it is still a static tag- The HT* #ill be the same each time this page is loaded in the bro#ser- Its I( remains constant #ithall instances of this page- That is+ #hen this page is displayed+ this 5I element #ill al#ays ha.e this Identifier- So+ for your test script to clic'this button you simply need to use the follo#ing selenium command-

clic adminLome%orm

6r+ in Selenium F-8

selenium+clic(*adminLome%orm*)R

"our application+ ho#e.er+ may generate HT* dynamically #here the identifier .aries on different instances of the #ebpage- $or instance+HT* for a dynamic page element might loo' li'e this-

<input type*checbo"* alue*true* id*add%orm?SPD2?SPD20?5?SPD24?5?checOo"*  name*add%orm?SPD2?SPD20?5?SPD24?5?checOo"*/>

This defines a chec'bo%- Its I( and name attributes ;both add$orm1\I(91\I(L181\I(C181chec'Bo%< are dynamically generated .alues- Inthis case+ using a standard locator #ould loo' something li'e the follo#ing-

clic add%orm?SPD2?SPD20?5?SPD24?5?checOo"

6r+ again in Selenium,2!

selenium+clic(*add%orm?SPD2?SPD20?5?SPD24?5?checOo"*)R

>i.en the dynamically generated Identifier+ this approach #ould not #or'- The ne%t time this page is loaded the Identifier #ill be a different.alue from the one used in the Selenium command and therefore+ #ill not be found- The clic' operation #ill fail #ith an Delement not foundEerror-

To correct this+ a simple solution #ould be to just use an OPath locator rather than trying to use an I( locator- So+ for the chec'bo% you cansimply use

clic //input

Page 109: About Sellinum

8/11/2019 About Sellinum

http://slidepdf.com/reader/full/about-sellinum 109/173

6r+ if it is not the first input element on the page ;#hich it li'ely is not< try a more detailed OPath statement-

clic //input6.7

6r

clic //di/p6#7/input6.7

If ho#e.er+ you do need to use the I( to locate the element+ a different solution is needed- "ou can capture this I( from the #ebsite beforeyou use it in a Selenium command- It can be done li'e this-

$tring67 checbo"ids selenium+get:ll%ields()R // Collect all input PDs on page+

or($tring checbo"id?checbo"ids)   i(checbo"id+contains(*add%orm*))   selenium+clic(checbo"id)R  FF

This approach #ill #or' if there is only one chec' bo% #hose I( contains the te%t add$orm-

6ocating A!a3 ,lements

As #as presented in the Test Types subsection abo.e+ a page element implemented #ith Aja% is an element that can be dynamically refreshed#ithout ha.ing to refresh the entire page- The best #ay to locate and .erify an Aja% element is to use the Selenium 7-8 Web(ri.er API- It#as specifically designed to address testing of Aja% elements #here Selenium F has some limitations-

In Selenim 7-8 you use the #ait$or;< method to #ait for a page element to become a.ailable- The parameter is a By object #hich is ho#Web(ri.er implements locators- This is e%plained in detail in the Web(ri.er chapters-

To do this #ith Selenium F-8 ;Selenium,2!< a bit more coding is in.ol.ed+ but it isnt difficult- The approach is to chec' for the element+ ifits not a.ailable #ait for a predefined period and then again rechec' it- This is then e%ecuted #ith a loop #ith a predetermined time,outterminating the loop if the element isnt found-

ets consider a page #hich brings a lin' ;lin'aja%in'< on clic' of a button on page ;#ithout refreshing the page< This could be handledby Selenium using a for loop-

// ,oop initialiAation+or (int second 5RR second)

  // P loop is reached 15 seconds then brea the loop+  i (second > 15) breaR

Page 110: About Sellinum

8/11/2019 About Sellinum

http://slidepdf.com/reader/full/about-sellinum 110/173

  // $earch or element *linaKa",in* and i aailable then brea loop+  try i (selenium+islement&resent(*linaKa",in*)) breaR F catch ("ception e) F

  // &ause or ' second+  Thread+sleep('555)R

F

This certainly isnt the only solution- Aja% is a common topic in the user forum and #e recommend searching pre.ious discussions to see#hat others ha.e done-

Wrapping Selenium Calls

As #ith any programming+ you #ill #ant to use utility functions to handle code that #ould other#ise be duplicated throughout your tests-6ne #ay to pre.ent this is to #rap fre0uently used selenium calls #ith functions or class methods of your o#n design- $or e%ample+ many

tests #ill fre0uently clic' on a page element and #ait for page to load multiple times #ithin a test-selenium+clic(element,ocator)Rselenium+wait%or&ageTo,oad(wait&eriod)R

Instead of duplicating this code you could #rite a #rapper method that performs both functions-

/@@ @ Clics and aits or page to load+ @ @ param element,ocator @ param wait&eriod @/public oid clic:ndait($tring element,ocatorE $tring wait&eriod)   selenium+clic(element,ocator)R  selenium+wait%or&ageTo,oad(wait&eriod)RF

QSafe Operations" for ,lement resence

Another common usage of #rapping Selenium methods is to chec' for presence of an element on page before carrying out some operation-

Page 111: About Sellinum

8/11/2019 About Sellinum

http://slidepdf.com/reader/full/about-sellinum 111/173

@I 7apping

Page 112: About Sellinum

8/11/2019 About Sellinum

http://slidepdf.com/reader/full/about-sellinum 112/173

A 5I map is a mechanism that stores all the locators for a test suite in one place for easy modification #hen identifiers or paths to 5Ielements change in the A5T- The test script then uses the 5I *ap for locating the elements to be tested- Basically+ a 5I map is a repositoryof test script objects that correspond to 5I elements of the application being tested-

What ma'es a 5I map helpful? Its primary purpose is ma'ing test script management much easier- When a locator needs to be edited+ there

is a central location for easily finding that object+ rather than ha.ing to search through test script code- Also+ it allo#s changing the Identifierin a single place+ rather than ha.ing to ma'e the change in multiple places #ithin a test script+ or for that matter+ in multiple test scripts-

To summari/e+ a 5I map has t#o significant ad.antages-

• 5sing a centrali/ed location for 5I objects instead of ha.ing them scattered throughout the script- This ma'es script maintenance

more efficient-

• !ryptic HT* Identifiers and names can be gi.en more human,readable names impro.ing the readability of test scripts-

!onsider the follo#ing+ difficult to understand+ e%ample ;in ja.a<-

public oid testQew() throws "ception   selenium+open(*http?//www+test+com*)R

  selenium+type(*login%orm?tbJsername*E *""""""""*)R  selenium+clic(*login%orm?btn,ogin*)R  selenium+clic(*adminLome%orm?Sactiitynew*)R  selenium+wait%or&ageTo,oad(*.5555*)R  selenium+clic(*addditent%orm?SPDcancel*)R  selenium+wait%or&ageTo,oad(*.5555*)R  selenium+clic(*adminLome%orm?Sactiityold*)R  selenium+wait%or&ageTo,oad(*.5555*)RF

This script #ould be hard to follo# for anyone not familiar #ith the A5Ts page source- &.en regular users of the application might ha.e

difficulty understanding #hat thus script does- A better script could be1public oid testQew() throws "ception   selenium+open(*http?//www+test+com*)R  selenium+type(admin+usernameE *""""""""*)R  selenium+clic(admin+loginbutton)R  selenium+clic(admin+eents+createneweent)R  selenium+wait%or&ageTo,oad(*.5555*)R  selenium+clic(admin+eents+cancel)R  selenium+wait%or&ageTo,oad(*.5555*)R  selenium+clic(admin+eents+iewoldeents)R

  selenium+wait%or&ageTo,oad(*.5555*)RF

Page 113: About Sellinum

8/11/2019 About Sellinum

http://slidepdf.com/reader/full/about-sellinum 113/173

No#+ using some comments and #hitespace along #ith the 5I *ap identifiers ma'es a .ery readable script-

public oid testQew() throws "ception

  // pen app url+

  selenium+open(*http?//www+test+com*)R

  // &roide admin username+  selenium+type(admin+usernameE *""""""""*)R

  // Clic on ,ogin button+  selenium+clic(admin+loginbutton)R

  // Clic on Create Qew ent button+  selenium+clic(admin+eents+createneweent)R  selenium+wait%or&ageTo,oad(*.5555*)R

  // Clic on Cancel button+  selenium+clic(admin+eents+cancel)R  selenium+wait%or&ageTo,oad(*.5555*)R

  // Clic on View ld ents button+  selenium+clic(admin+eents+iewoldeents)R  selenium+wait%or&ageTo,oad(*.5555*)RF

There are .arious #ays a 5I *ap can be implemented- 6ne could create a class or struct #hich only stores public String .ariables eachstoring a locator- Alternati.ely+ a te%t file storing 'ey .alue pairs could be used- In :a.a+ a properties file containing 'eyG.alue pairs is

probably best method-!onsider a property file prop.properties #hich assigns as aliases reader,friendly identifiers for 5I elements from the pre.ious e%ample-

admin+username login%orm?tbJsernameadmin+loginbutton login%orm?btn,oginadmin+eents+createneweent adminLome%orm?Sactiitynewadmin+eents+cancel addditent%orm?SPDcanceladmin+eents+iewoldeents adminLome%orm?Sactiityold

The locators #ill still refer to html objects+ but #e ha.e introduced a layer of abstraction bet#een the test script and the 5I elements- 3alues

Page 114: About Sellinum

8/11/2019 About Sellinum

http://slidepdf.com/reader/full/about-sellinum 114/173

7- The id,locators #ould be spread in multiple tests+ all tests that had to use this login page-

Applying the page object techni0ues this e%ample could be re#ritten li'e this in the follo#ing e%ample of a page object for a Sign,in page-

Page 115: About Sellinum

8/11/2019 About Sellinum

http://slidepdf.com/reader/full/about-sellinum 115/173

Applying the page object techni0ues this e%ample could be re#ritten li'e this in the follo#ing e%ample of a page object for a Sign in page-

/@@ @ &age bKect encapsulates the $ign-in page+ @/public class $ignPn&age

  priate $elenium seleniumR

  public $ignPn&age($elenium selenium)   this+selenium seleniumR  i(!selenium+getTitle()+e=uals(*$ign in page*))   throw new Pllegal$tate"ception(*This is not sign in pageE current page is? *  selenium+get,ocation())R  F  F

  /@@  @ ,ogin as alid user

  @  @ 8param userQame  @ 8param password  @ 8return Lome&age obKect  @/  public Lome&age loginValidJser($tring userQameE $tring password)   selenium+type(*usernameield*E userQame)R  selenium+type(*passwordield*E password)R  selenium+clic(*sign-in*)R  selenium+wait%or&ageTo,oad(*wait&eriod*)R

  return new Lome&age(selenium)R

  FF

and page object for a Home page could loo' li'e this-

/@@ @ &age bKect encapsulates the Lome &age @/public class Lome&age

  priate $elenium seleniumR

public Lome&age($elenium selenium)

Page 116: About Sellinum

8/11/2019 About Sellinum

http://slidepdf.com/reader/full/about-sellinum 116/173

  public Lome&age($elenium selenium)   i (!selenium+getTitle()+e=uals(*Lome &age o logged in user*))   throw new Pllegal$tate"ception(*This is not Lome &age o logged in userE current page*  *is? * selenium+get,ocation())R  F

  F

  public Lome&age manage&roile()   // &age encapsulation to manage proile unctionality  return new Lome&age(selenium)R  F

  /@Nore methods oering the serices represented by Lome &age  o ,ogged Jser+ These methods in turn might return more &age bKects  or e"ample clic on Compose mail button could return ComposeNail class obKect@/

F

So no#+ the login test #ould use these t#o page objects as follo#s-

/@@@ @ Tests login eature @/public class Test,ogin

  public oid test,ogin()   $ignPn&age signPn&age new $ignPn&age(selenium)R  Lome&age home&age signPn&age+loginValidJser(*userQame*E *password*)R  :ssert+assertTrue(selenium+islement&resent(*compose button*)E

  *,ogin was unsuccessul*)R  FF

There is a lot of fle%ibility in ho# the page objects may be designed+ but there are a fe# basic rules for getting the desired maintainability ofyour test code- Page objects themsel.es should ne.er be ma'e .erifications or assertions- This is part of your test and should al#ays be#ithin the tests code+ ne.er in an page object- The page object #ill contain the representation of the page+ and the ser.ices the page pro.ides.ia methods but no code related to #hat is being tested should be #ithin the page object-

There is one+ single+ .erification #hich can+ and should+ be #ithin the page object and that is to .erify that the page+ and possibly critical

elements on the page+ #ere loaded correctly- This .erification should be done #hile instantiating the page object- In the e%amples abo.e+both the SignInPage and HomePage constructors chec' that the e%pected page is a.ailable and ready for re0uests from the test-

Page 117: About Sellinum

8/11/2019 About Sellinum

http://slidepdf.com/reader/full/about-sellinum 117/173

A page object does not necessarily need to represent an entire page- The Page 6bject design pattern could be used to represent componentson a page- If a page in the A5T has multiple components+ it may impro.ed maintainability if there #as a separate page object for eachcomponent-

There are other design patterns that also may be used in testing- Some use a Page $actory for instantiating their page objects- (iscussing all

of these is beyond the scope of this user guide- Here+ #e merely #ant to introduce the concepts to ma'e the reader a#are of some of thethings that can be done- As #as mentioned earlier+ many ha.e blogged on this topic and #e encourage the reader to search for blogs on thesetopics-

+ata +ri'en Testing

(ata (ri.en Testing refers to using the same test ;or tests< multiple times #ith .arying data- These data sets are often from e%ternal filesi-e- -cs. file+ te%t file+ or perhaps loaded from a database- (ata dri.en testing is a commonly used test automation techni0ue used to .alidatean application against many .arying input- When the test is designed for .arying data+ the input data can e%pand+ essentially creatingadditional tests+ #ithout re0uiring changes to the test code-

In ythonK

The Python script abo.e opens a te%t file- This file contains a different search string on each line- The code then sa.es this in an array ofstrings+ and iterates o.er the array doing a search and assert on each string-

This is a .ery basic e%ample+ but the idea is to sho# that running a test #ith .arying data can be done easily #ith a programming or scriptinglanguage- $or more e%amples+ refer to the Selenium 2! #i'i for e%amples of reading data from a spreadsheet or for using the data pro.idercapabilities of TestN>- Additionally+ this is a #ell,'no#n topic among test automation professionals including those #ho dont use Seleniumso searching the internet on Ddata,dri.en testingE should re.eal many blogs on this topic-

+atabase alidationAnother common type of testing is to compare data in the 5I against the data actually stored in the A5Ts database- Since you can also dodatabase 0ueries from a programming language+ assuming you ha.e database support functions+ you can use them to retrie.e data and thenuse the data to .erify #hats displayed by the A5T is correct-

!onsider the e%ample of a registered email address to be retrie.ed from a database and then later compared against the 5I- An e%ample ofestablishing a (B connection and retrie.ing data from the (B could loo' li'e this-

In Da'aK

// ,oad Nicrosot $U, $erer YDOC drier+Class+orQame(*com+microsot+s=lserer+Kdbc+$U,$ererDrier*)R

Page 118: About Sellinum

8/11/2019 About Sellinum

http://slidepdf.com/reader/full/about-sellinum 118/173

// &repare connection url+$tring url *Kdbc?s=lserer?//'4#+'13+'+'35?'..RDatabaseQameT$TSDO*R

// Wet connection to DO+public static Connection con

DrierNanager+getConnection(urlE *username*E *password*)R

// Create statement obKect which would be used in writing DD, and DN,// $U, statement+public static $tatement stmt con+create$tatement()R

// $end $U, $,CT statements to the database ia the $tatement+e"ecuteUuery// method which returns the re=uested inormation as rows o data in a// Iesult$et obKect+

Iesult$et result stmt+e"ecuteUuery(*select top ' emailSaddress rom userSregisterStable*)R

// %etch alue o *emailSaddress* rom *result* obKect+$tring emailaddress result+get$tring(*emailSaddress*)R

// Jse the email:ddress alue to login to application+selenium+type(*userPD*E emailaddress)Rselenium+type(*password*E secret&assword)Rselenium+clic(*loginOutton*)Rselenium+wait%or&ageTo,oad(timeut)R:ssert+assertTrue(selenium+isTe"t&resent(*elcome bac* emailaddress)E *Jnable to log in or user*emailaddress)

This is a simple :a.a e%ample of data retrie.al from a database-

Table Of Contents

• Selenium,>rid

• 4uic' Start 

Page 119: About Sellinum

8/11/2019 About Sellinum

http://slidepdf.com/reader/full/about-sellinum 119/173

When to @se It

>enerally spea'ing theres t#o reasons #hy you might #ant to use Selenium >rid

Page 120: About Sellinum

8/11/2019 About Sellinum

http://slidepdf.com/reader/full/about-sellinum 120/173

>enerally spea'ing+ there s t#o reasons #hy you might #ant to use Selenium,>rid-

• To run your tests against multiple bro#sers+ multiple .ersions of bro#ser+ and bro#sers running on different operating systems-

• To reduce the time it ta'es for the test suite to complete a test pass-

Selenium,>rid is used to speed up the e%ecution of a test pass by using multiple machines to run tests in parallel- $or e%ample+ if you ha.e a

suite of F88 tests+ but you set up Selenium,>rid to support 9 different machines ;3*s or separate physical machines< to run those tests+ yourtest suite #ill complete in ;roughly< one,fourth the time as it #ould if you ran your tests se0uentially on a single machine- $or large testsuites+ and long,running test suite such as those performing large amounts of data,.alidation+ this can be a significant time,sa.er- Some testsuites can ta'e hours to run- Another reason to boost the time spent running the suite is to shorten the turnaround time for test results afterde.elopers chec',in code for the A5T- Increasingly soft#are teams practicing Agile soft#are de.elopment #ant test feedbac' asimmediately as possible as opposed to #ait o.ernight for an o.ernight test pass-

Selenium,>rid is also used to support running tests against multiple runtime en.ironments+ specifically+ against different bro#sers at thesame time- $or e%ample+ a grid of .irtual machines can be setup #ith each supporting a different bro#ser that the application to be testedmust support- So+ machine F has Internet &%plorer @+ machine 7+ Internet &%plorer C+ machine K the latest !hrome+ and machine 9 the latest$irefo%- When the test suite is run+ Selenium,>rid recei.es each test,bro#ser combination and assigs each test to run against its re0uiredbro#ser-

In addition+ one can ha.e a grid of all the same bro#ser+ type and .ersion- $or instance+ one could ha.e a grid of 9 machines each running Kinstances of $irefo% F7+ allo#ing for a ser.er,farm ;in a sense< of a.ailable $irefo% instances- When the suite runs+ each test is passed toSelenium,>rid #hich assigns the test to the ne%t a.ailable $irefo% instance- In this manner one gets test pass #here concei.ably F7 tests areall running at the same time in parallel+ significantly reducing the time re0uired to complete a test pass-

Selenium,>rid is .ery fle%ible- These t#o e%amples can be combined to allo# multiple instances of each bro#ser type and .ersion- Aconfiguration such as this #ould pro.ide both+ parallel e%ecution for fast test pass completion and support for multiple bro#ser types and.ersions simultaneously-

Selenium-.rid #&1

Selenium,>rid 7-8 is the latest release as of the #riting of this document ;LG7=G78F7<- It is 0uite different from .ersion F of Selenium,>rid-In 7-8 Selenium,>rid #as merged #ith the Selenium,2! ser.er- No#+ you only need to do#nload a single -jar file to get the remoteSelenium,2!,Ser.er and Selenium,>rid all in one pac'age-

Selenium-.rid )&1

3ersion F #as the first general release of Selenium,>rid If you are ne# to Selenium,>rid you should use .ersion 7 Its been updated and

Page 121: About Sellinum

8/11/2019 About Sellinum

http://slidepdf.com/reader/full/about-sellinum 121/173

3ersion F #as the first general release of Selenium,>rid- If you are ne# to Selenium,>rid you should use .ersion 7- It s been updated andhas ne# features+ and supports Selenium,Web(ri.er- egacy test systems may still be using .ersion F ho#e.er- Information on Selenium,>rid .ersion F may be found at the Selenium,>rid #ebsite-

Ho0 Selenium-.rid Wor%s>With a Hub and NodesA grid consists of a single hub+ and one or more nodes- Both are started using the selenium,ser.er-jar e%ecutable- We.e listed somee%amples in the follo#ing sections of this chapter-

The hub recei.es a test to be e%ecuted along #ith information on #hich bro#ser and platform ;i-e- WIN(6WS+ IN5O+ etc< #here the testshould be run- It 'no#s the configuration of each node that has been registered to the hub- 5sing this information it selects an a.ailablenode that has the re0uested bro#ser,platform combination- 6nce a node has been selected+ Selenium commands initiated by the test are sendthe the hub+ #hich passes them to the node assigned to that test- The node runs the bro#ser+ and e%ecutes the Selenium commands #ithinthat bro#ser against the application under test-

A diagram illustrates this- 2efer to the second diagram on this page ;the first one is illustrating Selenium,2!<- The second diagram #as for

Selenium,>rid F+ ho#e.er it still applies and is a good illustration of #hat #ere describing here- The only difference is one of terminology-2eplace the term Selenium 2emote !ontrol #ith Selenium,>rid node the diagram #ill match our description for Selenium,>rid 7-

Installation

Installation is simple- (o#nload the Selenium,Ser.er jar file from the SeleniumH0 #ebsites do#nload page- "ou #ant the lin' under thesection DSelenium,Ser.er ;formerly Selenium,2!<E-

Install it in a folder of your choice- "oull need to be sure the ja.a e%ecutable is on your e%ecution path so you can run it from the command,line- If it does not run correcly+ .erify your systems path .ariable includes the path to the ja.a-e%e-

Starting Selenium-.rid

>enerally you #ould start a hub first since nodes depend on a hub- This is not abolutely necessary ho#e.er+ since nodes can recogni/e #hena hub has been started and .ice,.ersa- $or learning purposes though+ it #ould easier to start the hub first+ other#ise youll see error messagesthat may not #ant to start off #ith your first time using Selenium,>rid-

Starting a Hub

To start a hub #ith default parameters+ run the follo#ing command from a command,line shell- This #ill #or' on all the supported

Page 122: About Sellinum

8/11/2019 About Sellinum

http://slidepdf.com/reader/full/about-sellinum 122/173

p g ppplatforms+ Windo#s inu%+ or *ac6s-

Kaa -Kar selenium-serer-standalone-#+#'+5+Kar -role hub

This starts a hub using default parameter .alues- Well e%plain these parameters in folo#ing subsections- Note that you #ill li'ely ha.e to

change the .ersion number in the jar filename depending on #hich .ersion of the selenium,ser.er youre using-

Starting a Node

To start a node using default parameters+ run the follo#ing command from a command,line-

Kaa -Kar selenium-serer-standalone-#+#'+5+Kar -role node -hub http?//localhost?/grid/register

This assumes the hub has been started abo.e using default parameters- The default port the hub uses to listen for ne# re0uests is port 9999-This is #hy port 9999 #as used in the 52 for locating the hub- Also the use of localhost assumes your node is running on the samemachine as your hub- $or getting started this is probably easiest- If running the hub and node on separate machines+ simply replace

localhost #ith the hostname of the remote machine running the hub-

WA2NIN>1 Be sure to turn off the fire#alls on the machine running your hub and nodes- 6ther#ise you may get connection errors-

Configuring Selenium-.rid

+efault Configuration

DSON Configuration 2ile

Configuring ia the Command-6ine Options

Hub Configuration

To run the hub using the default options simply specify ,role hub to the Selenim,Ser.er

Kaa -Kar selenium-serer-standalone-#+#'+5+Kar -hub

"ou should see the follo#ing logging output-

Yul '4E #5'# '5?1?#' :N org+open=a+grid+selenium+Wrid,auncher mainPQ%? ,aunching a selenium grid serer

Page 123: About Sellinum

8/11/2019 About Sellinum

http://slidepdf.com/reader/full/about-sellinum 123/173

PQ%? ,aunching a selenium grid serer#5'#-52-'4 '5?1?#0+53#?PQ%?osKs+$erer?Ketty-2+"+y-$Q:&$LT#5'#-52-'4 '5?1?#0+'0'?PQ%?osKsh+Conte"tLandler?started o+s+K+s+$erletConte"tLandler/EnullF#5'#-52-'4 '5?1?#0+'30?PQ%?osKs+:bstractConnector?$tarted $ocetConnector85+5+5+5?

Specifying the ort

The default port used by the hub is 9999- The port being referred to hear+ is the T!PGIP port used #hen the client+ that is+ the automatedtests connect to the Selenium,>rid hub- If another application on your computer is already using this port+ or if+ you already ha.e aSelenium,Ser.er started+ youll see the follo#ing message in the log output-

'5?01?.0+45 :IQ - %ailed to start? $ocet,istener585+5+5+5?"ception in thread *main* Kaa+net+Oind"ception? $elenium is already running on port + r some otherserice is+

If this occurs you can either shutdo#n the other process that is using port 9999+ or you can tell Selenium,>rid to use a different port for its

hub- 5se the ,port option for changing the port used by the hub-

Kaa -Kar selenium-serer-standalone-#+#'+5+Kar -role hub -port '

This #ill #or' e.en if another hub is already running on the same machine+ that is+ as long as theyre both not using port 999F-

"ou may+ ho#e.er+ #ant to see #hat process is using port 9999 so you can allo# the hub to use the default- To see the ports used by allrunning programs on your machine use the command-

netstat -a

This should #or' on all supported systems+ 5ni%Ginu%+ *ac6s+ and Windo#s although additional options beyond ,a may be re0uired-

Basically you need to display the process I( along #ith the port- In 5ni% you may grep the output ;use a pipe< from the port number toonly display those records youre concerned #ith-

Node Configuration

Timing arameters

Page 124: About Sellinum

8/11/2019 About Sellinum

http://slidepdf.com/reader/full/about-sellinum 124/173

  typically taes care o the client crashes+

Page 125: About Sellinum

8/11/2019 About Sellinum

http://slidepdf.com/reader/full/about-sellinum 125/173

Common ,rrors

@nable to acess the !arfile

Jnable to access Karile selenium-serer-standalone-#+#'+5+Kar

This error can occur #hen starting up either a hub or node- This means :a.a cannot find the selenium,ser.er jar file- &ither run the commandfrom the directory #here the selenium,ser.er,OOOO-jar file is stored+ or specify an e%plicit path to the jar-

Troubleshooting

Table Of Contents

• 5ser,&%tensions

• Introduction 

• Actions 

• AccessorsGAssertions  

• ocator Strategies 

• 5sing 5ser,&%tensions With Selenium,I(& 

• 5sing 5ser,&%tensions With Selenium 2! 

@ser-,3tensions N-': his section is close to completion, but it has not been reviewed and edited.

Introduction

&%tending Selenium by adding your o#n actions+ assertions and locator,strategies can be 0uite simple- Add :a.aScript methods to theSelenium object prototype and the PageBot object prototype- 6n startup+ Selenium #ill automatically loo' through methods on these

Page 126: About Sellinum

8/11/2019 About Sellinum

http://slidepdf.com/reader/full/about-sellinum 126/173

@sing @ser-,3tensions With Selenium-I+,

5ser,e%tensions are .ery easy to use #ith the selenium I(&-

Page 127: About Sellinum

8/11/2019 About Sellinum

http://slidepdf.com/reader/full/about-sellinum 127/173

y y

F- !reate your user e%tension and sa.e it as user,e%tensions-js- While this name isnt technically necessary+ its good practice to 'eepthings consistent-

7- 6pen $irefo% and open Selenium,I(&-K- !lic' on Tools+ 6ptions9- In Selenium !ore &%tensions clic' on Bro#se and find the user,e%tensions- js file- !lic' on 6-L- "our user,e%tension #ill not yet be loaded+ you must close and restart Selenium,I(&-=- In your empty test+ create a ne# command+ your user,e%tension should no# be an options in the !ommands dropdo#n-

@sing @ser-,3tensions With Selenium *C

If you >oogle DSelenium 2! user,e%tensionE ten times you #ill find ten different approaches to using this feature- Belo#+ is the officialSelenium suggested approach-

,3ampleCU

F- Place your user e%tension in the same directory as your Selenium Ser.er-7- If you are using client code generated by the Selenium,I(& you #ill need to ma'e a couple of small edits- $irst+ you #ill need to

create an LttpCommand&rocessor object #ith class scope ;outside the SetupTest method+ just belo# priate$tringOuilder eriicationrrorsR<

LttpCommand&rocessor procR

K- Ne%t+ instantiate that LttpCommand&rocessor object as you #ould the Deault$elenium object- This can be done in the

test setup-

proc new LttpCommand&rocessor(*localhost*E E *@ie"plore*E *http?//google+ca/*)R

9- Instantiate the (efaultSelenium object using the LttpCommand&rocessor object you created-

selenium new Deault$elenium(proc)R

L- Within your test code+ e%ecute your user,e%tension by calling it #ith the DoCommand() method of LttpCommand&rocessor-This method ta'es t#o arguments1 a string to identify the user,e%tension method you #ant to use and string array to pass arguments-

Notice that the first letter of your function is lo#er case+ regardless of the capitali/ation in your user,e%tension- Seleniumautomatically does this to 'eep common :a.aScript naming con.entions- Because :a.aScript is case sensiti.e+ your test #ill fail ifyou begin this command #ith a capital- inputParams is the array of arguments you #ant to pass to the :a.aScript user,e%tension- In

Page 128: About Sellinum

8/11/2019 About Sellinum

http://slidepdf.com/reader/full/about-sellinum 128/173

y g p p y g y p pthis case there is only one string in the array because there is only one parameter for our user e%tension+ but a longer array #ill mapeach inde% to the corresponding user,e%tension parameter- 2emember that user e%tensions designed for Selenium,I(& #ill only ta'et#o arguments-

string67 input&arams *Lello orld*FR

proc+DoCommand(*alertrapper*E input&arams)R

=- Start the test ser.er using the -user"tensions argument and pass in your user-e"tensions+Ks file-

Kaa -Kar selenium-serer+Kar -user"tensions user-e"tensions+Ks

Table Of Contents

• Selenium Web(ri.er !heat Sheet• 2ole Based Interfaces in Selenium Web(ri.er 

Selenium Web+ri'er Cheat Sheet

*ole Based Interfaces in Selenium Web+ri'er

6ne of the differences bet#een Selenium 2! and Selenium Web(ri.er is that the Web(ri.er APIs ma'e e%tensi.e use of Drole,based

interfacesE to allo# users to determine #hether a particular dri.er supports a feature- This can ma'e it hard to 'no# #hat features area.ailable #ithout first 'no#ing #hich interface to try and use- The 'ey interfaces are listed belo#-

Interface *ole +ocumentation

Has!apabilities Pro.idesaccess to thecapabilitiessupportedby this

:a.aHas!apabilities-ja.a

Interface *ole +ocumentation

dri.er-

: i t& t All th :

Page 129: About Sellinum

8/11/2019 About Sellinum

http://slidepdf.com/reader/full/about-sellinum 129/173

:a.ascript&%ecutor Allo#s thee%ecution ofarbitrary :Scommands-

:a.a:a.ascript&%ecutor-ja.a

2otatable Indicates#hether thedri.ersupportsrotating thedisplay;mostly justmobiledri.ers<-

:a.a 2otatable-ja.a

Ta'esScreenshot Pro.ides a

mechanismfor ta'ingscreenshots-

:a.a

Ta'esScreenshot-ja.a

org-open0a-selenium

Interface HasCapabilities

• All no#n Implementing !lasses1

Android(ri.er+ !hrome(ri.er+ $irefo%(ri.er+ Html5nit(ri.er+ Internet&%plorer(ri.er + IPhone(ri.er+ IPhoneSimulator(ri.er+2emoteWeb(ri.er+ Safari(ri.er+ Web(ri.erBac'edSelenium 

public interace LasCapabilities

5sed by classes to indicate that they can describe the !apabilities they possess- This can be used for run,time detection of features-

• 7ethod Summary

*ethods

Page 130: About Sellinum

8/11/2019 About Sellinum

http://slidepdf.com/reader/full/about-sellinum 130/173

7odifier and Type 7ethod and +escription

!apabilities get!apabilities() 

• 7ethod +etail

• getCapabilities

Capabilities getCapabilities()

2eturns1The capabilities of the current dri.er-

org-open0a-selenium

Interface Da'ascript,3ecutor

• All no#n Implementing !lasses1

Android(ri.er+ AndroidWeb(ri.er+ !hrome(ri.er+ &.ent$iringWeb(ri.er+ $irefo%(ri.er+ Html5nit(ri.er+Internet&%plorer(ri.er + IPhone(ri.er+ IPhoneSimulator(ri.er+ 2emoteWeb(ri.er+ Safari(ri.er 

public interace Yaascript"ecutor

Indicates that a dri.er can e%ecute :a.aScript+ pro.iding access to the mechanism to do so-

• 7ethod Summary

*ethods

7odifier and Type 7ethod and +escription

Kaa+lang+bKect e%ecuteAsyncScript(Kaa+lang+$tring scriptE Kaa+lang+bKect+++ args) 

&%ecute an asynchronous piece of :a.aScript in the conte%t of the currently selected frame or#indo#-

e%ecuteScript(Kaa lang $tring script Kaa lang bKect args)

Page 131: About Sellinum

8/11/2019 About Sellinum

http://slidepdf.com/reader/full/about-sellinum 131/173

Kaa+lang+bKecte%ecuteScript(Kaa+lang+$tring scriptE Kaa+lang+bKect+++ args) &%ecutes :a.aScript in the conte%t of the currently selected frame or #indo#-

• 7ethod +etail

• e3ecuteScript

Kaa+lang+bKect e"ecute$cript(Kaa+lang+$tring scriptE  Kaa+lang+bKect+++ args)

&%ecutes :a.aScript in the conte%t of the currently selected frame or #indo#- The script fragment pro.ided #ill bee%ecuted as the body of an anonymous function-

Within the script+ use document to refer to the current document- Note that local .ariables #ill not be a.ailable oncethe script has finished e%ecuting+ though global .ariables #ill persist-

If the script has a return .alue ;i-e- if the script contains a return statement<+ then the follo#ing steps #ill be ta'en1

• $or an HT* element+ this method returns a Web&lement

• $or a decimal+ a (ouble is returned

• $or a non,decimal number+ a ong is returned

• $or a boolean+ a Boolean is returned

• $or all other cases+ a String is returned-

• $or an array+ return a istU6bjectQ #ith each object follo#ing the rules abo.e- We support nested lists-

• 5nless the .alue is null or there is no return .alue+ in #hich null is returned

Arguments must be a number+ a boolean+ a String+ Web&lement+ or a ist of any combination of the abo.e- Ane%ception #ill be thro#n if the arguments do not meet these criteria- The arguments #ill be made a.ailable to the:a.aScript .ia the arguments magic .ariable+ as if the function #ere called .ia $unction-apply

Parameters1script , The :a.aScript to e%ecuteargs , The arguments to the script- *ay be empty

2eturns16ne of Boolean+ ong+ String+ ist or Web&lement- 6r null-

• e3ecuteAsyncScript

Kaa+lang+bKect e"ecute:sync$cript(Kaa+lang+$tring scriptE  Kaa+lang+bKect+++ args)

Page 132: About Sellinum

8/11/2019 About Sellinum

http://slidepdf.com/reader/full/about-sellinum 132/173

K g K g )

&%ecute an asynchronous piece of :a.aScript in the conte%t of the currently selected frame or #indo#- 5nli'ee%ecuting synchronous :a.aScript+ scripts e%ecuted #ith this method must e%plicitly signal they are finished byin.o'ing the pro.ided callbac'- This callbac' is al#ays injected into the e%ecuted function as the last argument-

The first argument passed to the callbac' function #ill be used as the scriptVs result- This .alue #ill be handled asfollo#s1

• $or an HT* element+ this method returns a Web&lement

• $or a number+ a ong is returned

• $or a boolean+ a Boolean is returned

• $or all other cases+ a String is returned-

• $or an array+ return a istU6bjectQ #ith each object follo#ing the rules abo.e- We support nested lists-

• 5nless the .alue is null or there is no return .alue+ in #hich null is returned

&%ample F1 Performing a sleep in the bro#ser under test-

long start $ystem+currentTimeNillis()R  ((Yaascript"ecutor) drier)+e"ecute:sync$cript(  *window+setTimeout(arguments6arguments+length - '7E 055)R*)R  $ystem+out+println(  *lapsed time? * $ystem+currentTimeNillis() - start)R 

&%ample 71 Synchroni/ing a test #ith an A:AO application1

eblement composeOutton drier+indlement(Oy+id(*compose-button*))R

  composeOutton+clic()R  ((Yaascript"ecutor) drier)+e"ecute:sync$cript(  *ar callbac arguments6arguments+length - '7R*   *mailClient+getComposeindowidget()+onload(callbac)R*)R  drier+switchTo()+rame(*composeidget*)R  drier+indlement(Oy+id(*to*))+sendXeys(*bog8e"ample+com*)R 

&%ample K1 Injecting a O*Http2e0uest and #aiting for the result1

  bKect response ((Yaascript"ecutor) drier)+e"ecute:sync$cript(  *ar callbac arguments6arguments+length - '7R*   *ar "hr new N,LttpIe=uest()R*

*"hr+open(9WT9E 9/resource/data+Kson9E true)R*

Page 133: About Sellinum

8/11/2019 About Sellinum

http://slidepdf.com/reader/full/about-sellinum 133/173

  "hr+open( WT E /resource/data+Kson E true)R   *"hr+onreadystatechange unction() *   * i ("hr+ready$tate ) *   * callbac("hr+responseTe"t)R*   * F*   *FR*   *"hr+send()R*)R  Y$QbKect Kson new Y$QbKect(($tring) response)R  assert=uals(*cheese*E Kson+get$tring(*ood*))R 

Script arguments must be a number+ a boolean+ a String+ Web&lement+ or a ist of any combination of the abo.e- Ane%ception #ill be thro#n if the arguments do not meet these criteria- The arguments #ill be made a.ailable to the:a.aScript .ia the arguments .ariable-

Parameters1script , The :a.aScript to e%ecute-

args , The arguments to the script- *ay be empty-2eturns1

6ne of Boolean+ ong+ String+ ist+ Web&lement+ or null-

org-open0a-selenium

Interface *otatable

• All no#n Implementing !lasses1

Android(ri.er+ AndroidWeb(ri.er 

public interace Iotatable

2epresents rotation of the bro#ser .ie# for orientation,sensiti.e de.ices- When using this #ith a real de.ice+ the de.ice should not bemo.ed so that the built,in sensors do not interfere-

• 7ethod Summary

*ethods

7 difi d T 7 h d d + i i

Page 134: About Sellinum

8/11/2019 About Sellinum

http://slidepdf.com/reader/full/about-sellinum 134/173

7odifier and Type 7ethod and +escription

Screen6rientation get6rientation() 

oidrotate(Screen6rientation orientation) !hanges the orientation of the bro#ser #indo#-

• 7ethod +etail

• rotate

oid rotate($creenrientation orientation)

!hanges the orientation of the bro#ser #indo#-Parameters1

orientation , the desired screen orientation

• getOrientation

$creenrientation getrientation()

2eturns1the current screen orientation of the bro#ser

org-open0a-selenium

Interface Ta%esScreenshot

• All no#n Implementing !lasses1

Android(ri.er+ AndroidWeb(ri.er+ !hrome(ri.er+ &.ent$iringWeb(ri.er+ $irefo%(ri.er+ Internet&%plorer(ri.er+IPhone(ri.er+ IPhoneSimulator(ri.er+ Safari(ri.er 

public interace Taes$creenshot

Indicates a dri.er that can capture a screenshot and store it in different #ays-

Page 135: About Sellinum

8/11/2019 About Sellinum

http://slidepdf.com/reader/full/about-sellinum 135/173

&%ample usage1

import static open=a+selenium+utputType+@R %ile screenshot%ile (($creenshot)drier)+get$creenshot:s(ile)R

 $tring screenshotOase1 (($creenshot)drier)+get$creenshot:s(base1)R 

See Also16utputType

• 7ethod Summary

*ethods

7odifier and Type 7ethod and +escription

<> getScreenshotAs(6utputType<> target) !apture the screenshot and store it in the specifiedlocation-

• 7ethod +etail

• getScreenshotAs

<> get$creenshot:s(utputType<> target)

  throws ebDrier"ception

!apture the screenshot and store it in the specified location-

$or Web(ri.er e%tending Ta'esScreenshot+ this ma'es a best effort depending on the bro#ser to return the follo#ingin order of preference1

• &ntire page

• !urrent #indo#

• 3isible portion of the current frame

• The screenshot of the entire display containing the bro#ser

$or Web&lement e%tending Ta'esScreenshot this ma'es a best effort depending on the bro#ser to return the follo#ing

Page 136: About Sellinum

8/11/2019 About Sellinum

http://slidepdf.com/reader/full/about-sellinum 136/173

$or Web&lement e%tending Ta'esScreenshot+ this ma'es a best effort depending on the bro#ser to return the follo#ingin order of preference1 , The entire content of the HT* element , The .isisble portion of the HT* element

Type Parameters1 , 2eturn type for getScreenshotAs-

Parameters1target , target type+ ]see 6utputType

2eturns16bject in #hich is stored information about the screenshot-

Thro#s1Web(ri.er&%ception , on failure-

&N,T client dri'er configuration-N&T client (ri.er can be used #ith *icrosoft 3isual Studio- To !onfigure it #ith 3isual Studio do as $ollo#ing-

• aunch 3isual Studio and na.igate to $ile Q Ne# Q Project-

Page 137: About Sellinum

8/11/2019 About Sellinum

http://slidepdf.com/reader/full/about-sellinum 137/173

 

• Select 3isual ! Q !lass ibrary Q Name your project Q !lic' on 6 button-

Page 138: About Sellinum

8/11/2019 About Sellinum

http://slidepdf.com/reader/full/about-sellinum 138/173

 

•A !lass ;-cs< is created- 2ename it as appropriate-

Page 139: About Sellinum

8/11/2019 About Sellinum

http://slidepdf.com/reader/full/about-sellinum 139/173

• 5nder right hand pane of Solution &%plorer right clic' on 2eferences Q Add 2eferences-

Page 140: About Sellinum

8/11/2019 About Sellinum

http://slidepdf.com/reader/full/about-sellinum 140/173

 

• Select follo#ing dll files , nmoc'-dll+ nunit-core-dll+ nunit-frame#or'-dll+ThoughtWor's- Selenium-!ore-dll+

ThoughtWor's-Selenium-IntegrationTests-dll+ ThoughtWor's-Selenium-5nitTests-dll and clic' on 6' button

Page 141: About Sellinum

8/11/2019 About Sellinum

http://slidepdf.com/reader/full/about-sellinum 141/173

 

With This 3isual Studio is ready for Selenium Test !ases-

Table Of Contents

• Importing Sel7-8 Project into &clipse using *a.en 

• Importing Sel7-8 Project into Intelli: 5sing *a.en 

Importing Sel#&1 ro!ect into ,clipse using 7a'en6nce you ha.e created your pom-%ml file in your project+ you can ha.e ma.en autogenerate the project files necessary for eclipse #ith asimple command1

mn eclipse?eclipse

Then open eclipse- !hoose your #or'space or create a ne# one- 6nce the &clipse I(& loads+ do the follo#ing1

$ile ,Q Import--- >eneral ,Q &%isting Projects into Wor'space !lic' ne%t Ne%t to DSelect root (irectory1E clic' DBro#seEbutton locate the project folder containing your pom-%ml and clic' o'- "our project should appear in the DProjectsE bo%l d li ' fi i h

Page 142: About Sellinum

8/11/2019 About Sellinum

http://slidepdf.com/reader/full/about-sellinum 142/173

already clic' finish

If you ha.ent already+ install the m7eclipse plugin then right clic' on your project and select *a.en ,Q &nable (ependency *anagement-

Importing Sel#&1 ro!ect into IntelliD @sing 7a'en$e are currently working on this appendi%. he information provided here is accurate, although it may not be finished.

In this appendi% #e pro.ide the steps+ including screen captures+ sho#ing ho# to create a Selenium 7-8 ja.a client,dri.er project in Intelli:I(&A- These steps assume you ha.e already used ma.en #ith a pom-%ml file to set up the project- This process is described in the Selenium7-8 chapter- "ou must ha.e follo#ed that process before you can perform these steps- This appendi% then sho#s you ho# to import thema.en,created Selenium 7-8 ja.a project into Intelli:-

$irst+ open Intelli: and from the entry page+ clic' !reate Ne# Project-

Page 143: About Sellinum

8/11/2019 About Sellinum

http://slidepdf.com/reader/full/about-sellinum 143/173

$rom the Ne# Project dialog select Import Project from &%ternal *odel- 

Page 144: About Sellinum

8/11/2019 About Sellinum

http://slidepdf.com/reader/full/about-sellinum 144/173

$rom the list of project types+ select ma.en- 

No# you #ill see a dialog allo#ing you to set project options including the projects root directory- 

!lic' the --- button to set the root folder-

Page 145: About Sellinum

8/11/2019 About Sellinum

http://slidepdf.com/reader/full/about-sellinum 145/173

No# the settings dialog #ill sho# the directory you just selected-

Page 146: About Sellinum

8/11/2019 About Sellinum

http://slidepdf.com/reader/full/about-sellinum 146/173

Page 147: About Sellinum

8/11/2019 About Sellinum

http://slidepdf.com/reader/full/about-sellinum 147/173

This ne%t dialog sho#s the name of your ma.en project as specified in the pom-%ml file- Select your ma.en project and continue-

Page 148: About Sellinum

8/11/2019 About Sellinum

http://slidepdf.com/reader/full/about-sellinum 148/173

Page 149: About Sellinum

8/11/2019 About Sellinum

http://slidepdf.com/reader/full/about-sellinum 149/173

Page 150: About Sellinum

8/11/2019 About Sellinum

http://slidepdf.com/reader/full/about-sellinum 150/173

Page 151: About Sellinum

8/11/2019 About Sellinum

http://slidepdf.com/reader/full/about-sellinum 151/173

Page 152: About Sellinum

8/11/2019 About Sellinum

http://slidepdf.com/reader/full/about-sellinum 152/173

Page 153: About Sellinum

8/11/2019 About Sellinum

http://slidepdf.com/reader/full/about-sellinum 153/173

The ma.en project do#nload many dependencies ;libraries< #hen you originally ran m.n install- No# in Intelli: you can see all theselibraries- These ne%t t#o screen captures sho#s the libraries you should no# ha.e in your project-

Page 154: About Sellinum

8/11/2019 About Sellinum

http://slidepdf.com/reader/full/about-sellinum 154/173

Page 155: About Sellinum

8/11/2019 About Sellinum

http://slidepdf.com/reader/full/about-sellinum 155/173

Page 156: About Sellinum

8/11/2019 About Sellinum

http://slidepdf.com/reader/full/about-sellinum 156/173

Before you can start #riting Selenium code+ you still need to create a module and at least one :a.a class ;a -ja.a file<- $irst select theProjects root in Intelli: and right clic'-

Page 157: About Sellinum

8/11/2019 About Sellinum

http://slidepdf.com/reader/full/about-sellinum 157/173

Page 158: About Sellinum

8/11/2019 About Sellinum

http://slidepdf.com/reader/full/about-sellinum 158/173

Page 159: About Sellinum

8/11/2019 About Sellinum

http://slidepdf.com/reader/full/about-sellinum 159/173

Page 160: About Sellinum

8/11/2019 About Sellinum

http://slidepdf.com/reader/full/about-sellinum 160/173

Select :a.a *odule and enter a name for the ne# module-

Page 161: About Sellinum

8/11/2019 About Sellinum

http://slidepdf.com/reader/full/about-sellinum 161/173

Page 162: About Sellinum

8/11/2019 About Sellinum

http://slidepdf.com/reader/full/about-sellinum 162/173

Page 163: About Sellinum

8/11/2019 About Sellinum

http://slidepdf.com/reader/full/about-sellinum 163/173

Page 164: About Sellinum

8/11/2019 About Sellinum

http://slidepdf.com/reader/full/about-sellinum 164/173

No# #ere on the last dialog- Typically you dont need to select any technollogies here- 5nless you 'no# for a fact you #ill be using>roo.y or some other technology-

Page 165: About Sellinum

8/11/2019 About Sellinum

http://slidepdf.com/reader/full/about-sellinum 165/173

Page 166: About Sellinum

8/11/2019 About Sellinum

http://slidepdf.com/reader/full/about-sellinum 166/173

No# that the module is created+ your project should sho# the follo#ing structure- 

$inally+ you need to create a -ja.a file #ith a corresponding ja.a class-

Page 167: About Sellinum

8/11/2019 About Sellinum

http://slidepdf.com/reader/full/about-sellinum 167/173

$inally+ you need to create a -ja.a file #ith a corresponding ja.a class-

 

&nter the class name-

 

The -ja.a file should no# be created- It should loo' li'e this in your project-

Page 168: About Sellinum

8/11/2019 About Sellinum

http://slidepdf.com/reader/full/about-sellinum 168/173

If your project no# loo's li'e the one displayed abo.e+ youre done+ congratsZ And hope you enjoy coding your first Selenium automationZ

Table Of Contents

Page 169: About Sellinum

8/11/2019 About Sellinum

http://slidepdf.com/reader/full/about-sellinum 169/173

Table Of Contents

• Selenium F-8 :a.a !lient (ri.er !onfiguration

• !onfiguring Selenium,2! With &clipse • !onfiguring Selenium,2! With Intellij 

Selenium )&1 Da'a Client +ri'er ConfigurationIn >eneral configuration of Selenium,2! #ith any ja.a I(& #ould ha.e follo#ing steps1

• (o#nload Selenium,2! from the SeleniumH4 do#nloads page 

• Start any ja.a I(&

!reate ne# project• Add Dselenium,ja.a,U.ersion,numberQ-jarE to your project classpath

• 2ecord your test from Selenium,I(& and translate it to ja.a code ;Selenium I(& has automatic translation feature to generate tests in

.ariety of languages<

• 2un selenium ser.er from console

• 2un your test in the I(&

These points ha.e been delineated belo# #ith reference to &clipse and Intelli:1

Configuring Selenium-*C With ,clipse

,clipse is a multi,language soft#are de.elopment platform comprising an I(& and a plug,in system to e%tend it- It is #ritten primarily in:a.a and is used to de.elop applications in this language and+ by means of the .arious plug,ins+ in other languages as #ell as !G!JJ+ !obol+Python+ Perl+ PHP and more-

$ollo#ing lines describes configuration of Selenium,2! #ith &clipse , 3ersion1 K-K-8- ;&uropa 2elease<- It should not be too different forhigher .ersions of &clipse

• aunch &clipse-

Page 170: About Sellinum

8/11/2019 About Sellinum

http://slidepdf.com/reader/full/about-sellinum 170/173

Page 171: About Sellinum

8/11/2019 About Sellinum

http://slidepdf.com/reader/full/about-sellinum 171/173

• !lic' $inish Q !lic' on "es in 6pen Associated Perspecti.e pop up #indo#-

This #ould create Project >oogle in Pac'age &%plorerGNa.igator pane-

Page 172: About Sellinum

8/11/2019 About Sellinum

http://slidepdf.com/reader/full/about-sellinum 172/173

j g g p g p 

2ight clic' on src folder and clic' on Ne# Q $older

Name this folder as com and clic' on $inish button-

• This should get com pac'age insider src folder-

• $ollo#ing the same steps create core folder inside com 

SelTest!ase class can be 'ept inside core pac'age-

!reate one more pac'age inside src folder named testscripts- This is a place holder for test scripts-

 &lease notice this is about the organi!ation of proEect and it entirely depends on individuals choice 6 organi!ations standards. est scripts package can further be segregated depending upon the proEect reKuirements. 

• !reate a folder called lib inside project >oogle- 2ight clic' on Project name Q Ne# Q $older- This is a place holder for jar files to

project ;i-e- Selenium client dri.er+ selenium ser.er etc<

This #ould create lib folder in Project directory- 

• 2ight clic' on lib folder Q Build Path Q !onfigure build Path

• 5nder ibrary tab clic' on Add &%ternal :ars to na.igate to directory #here jar files are sa.ed- Select the jar files #hich are to be

added and clic' on 6pen button-

After ha.ing added jar files clic' on 6 button-

Page 173: About Sellinum

8/11/2019 About Sellinum

http://slidepdf.com/reader/full/about-sellinum 173/173

 

Added libraries #ould appear in Pac'age &%plorer as follo#ing1

 

Configuring Selenium-*C With Intelli!

• Watch this e%cellent tutorial by Simon Ste#art on starting a Selenium project #ith Intelli: