1. Introduction
Test Automation for WebApplications:
Testautomationmeansusinga software tool torun repeatable testsagainstthe applicationtobe
tested.Forregressiontestingthisprovidesthatresponsiveness.
There are manyadvantagestotest automation.Mostare relatedtothe repeatabilityof the tests
and the speedatwhichthe testscan be executed.
Testautomationhasspecificadvantagesforimprovingthe long-termefficiencyof asoftware team’s
testingprocesses.Testautomationsupports:
o Frequentregressiontesting
o Rapidfeedbacktodevelopers
o Virtuallyunlimitediterationsof testcase execution
o Supportfor Agile andextremedevelopmentmethodologies
o Disciplineddocumentationof testcases
o Customizeddefectreporting
o Findingdefectsmissedbymanual testing
To Automate or Not to Automate?
Is automationalwaysadvantageous?Whenshouldone decidetoautomate testcases?
It isnot alwaysadvantageoustoautomate testcases.There are timeswhenmanual testingmay
be more appropriate.
o If an applicationhasaverytightdeadline,
o there iscurrentlynotestautomationavailable,and
o it’simperative thatthe testinggetdone withinthattime frame
Selenium’sTool Suite
Selenium2(aka.SeleniumWebDriver)
o Selenium2.0is the product of that effort.Itsupportsthe WebDriverAPIandunderlying
technology,alongwiththe Selenium1technologyunderneaththe WebDriverAPIfor
maximumflexibilityinportingyourtests.
Selenium1(aka.SeleniumRCorRemote Control)
o SeleniumRCwasthe main Seleniumprojectforalongtime.Now Selenium1is
deprecatedandisnotactivelysupported(mostlyinmaintenance mode).
SeleniumIDE
o A prototypingtool forbuildingtestscripts.Itisa Firefox pluginandprovidesaneasy-to-
use interface fordeveloping automatedtests.SeleniumIDEhasa recordingfeature,
whichrecordsuseractionsas theyare performedandthenexportsthemasa reusable
scriptin one of many programminglanguagesthatcanbe laterexecuted.
o Note:EventhoughSeleniumIDEhasa “Save” feature thatallowsuserstokeepthe tests
ina table-basedformatforlaterimportandexecution,itisnotdesignedtorunyour test
2. passesnoris itdesignedtobuildall the automatedtestsyouwill need.Specifically,
SeleniumIDEdoesn’tprovide iterationorconditional statementsfortestscripts.The
Seleniumdevelopersencourage bestpracticesintestautomationwhichalwaysrequires
some amountof programming.SeleniumIDEissimplyintendedasarapidprototyping
tool.The Seleniumdevelopersrecommendforserious,robusttestautomationeither
Selenium2or Selenium1to be usedwithone of the many supportedprogramming
languages.
Selenium-Grid
o Selenium-Gridallowsthe SeleniumRCsolutiontoscale forlarge testsuitesandfortest
suitesthatmustbe run inmultiple environments.SeleniumGridallowsyoutorunyour
testsinparallel,thatis,differenttestscanbe run at the same time on differentremote
machines.
SupportedBrowsers and Platforms
Selenium-WebDriver
o Google Chrome
o InternetExplorer6,7, 8, 9, 10 - 32 and 64-bitwhere applicable
o Firefox:latestESR,previousESR,currentrelease,one previousrelease
o Safari
o Opera
o HtmlUnit
o phantomjs
o Android(withSelendroidorappium)
o iOS(withios-driverorappium)
Selenium - IDE
Recording
Duringrecording,Selenium-IDEwill automaticallyinsertcommandsintoyourtestcase basedon
your actions.Typically,thiswill include:
o clickingalink - clickor clickAndWaitcommands
o enteringvalues - type command
o selectingoptionsfromadrop-downlistbox- selectcommand
o clickingcheckboxesorradiobuttons - click command
Here are some “gotchas” to be aware of:
o The type command mayrequire clickingonsome otherareaof the webpage forit to
record.
o Followingalinkusuallyrecordsaclickcommand. You will oftenneedtochange thisto
clickAndWaittoensure yourtestcase pausesuntil the new page iscompletelyloaded.
Otherwise,yourtestcase will continue runningcommandsbefore the page hasloaded
all itsUI elements.Thiswillcause unexpected testcase failures.
3. SeleniumCommands– “Selenese”
A commandtellsSeleniumwhattodo.Seleniumcommandscome inthree “flavors”:Actions,
Accessors,andAssertions.
o Actionsare commandsthat generallymanipulatethe state of the application.Theydo
thingslike “clickthislink”and“selectthatoption”.If anActionfails,orhas an error,the
executionof the currenttestisstopped.
Many Actionscan be calledwiththe “AndWait”suffix,e.g.“clickAndWait”.Thissuffix
tellsSeleniumthatthe actionwill cause the browsertomake acall to the server,and
that Seleniumshouldwaitforanew page to load.
o Accessorsexamine the state of the applicationandstore the resultsinvariables,e.g.
“storeTitle”.Theyare alsousedtoautomaticallygenerateAssertions.
o Assertionsare like Accessors,buttheyverifythatthe state of the applicationconforms
to whatis expected.Examplesinclude “make sure the page title isX”and“verifythat
thischeckbox ischecked”.
All SeleniumAssertionscanbe usedin3 modes:“assert”,“verify”,and”waitFor”.For
example,youcan“assertText”,“verifyText”and“waitForText”.Whenan“assert”fails,
the testis aborted.Whena “verify”fails,the testwillcontinueexecution,loggingthe
failure.Thisallowsasingle “assert”toensure thatthe applicationisonthe correctpage,
followedbya bunchof “verify”assertionstotestformfieldvalues,labels,etc.
“waitFor”commandswaitfor some conditiontobecome true (whichcanbe useful for
testingAjax applications).Theywillsucceedimmediatelyif the conditionisalreadytrue.
However,theywillfail andhaltthe testif the conditiondoesnotbecome true withinthe
currenttimeoutsetting(see the setTimeoutactionbelow).
Assertionor Verification?
Choosingbetween“assert”and“verify”comesdowntoconvenience andmanagementof
failures.There’sverylittle pointcheckingthatthe firstparagraphon the page is the correct one
if your testhas alreadyfailedwhencheckingthatthe browserisdisplayingthe expectedpage.If
you’re noton the correct page,you’ll probablywanttoabortyour testcase so thatyou can
investigatethe cause andfix the issue(s)promptly.Onthe otherhand,youmay wantto check
manyattributesof a page withoutabortingthe testcase onthe firstfailure asthiswill allow you
to reviewall failuresonthe page andtake the appropriate action. Effectivelyan“assert”will fail
the testand abort the current testcase,whereasa“verify”will fail the testandcontinue torun
the testcase.
The bestuse of thisfeature isto logicallygroupyourtestcommands,andstart eachgroup with
an “assert”followedbyone ormore “verify”testcommands.
verifyTextPresent
o The command verifyTextPresentisusedtoverifyspecifictextexistssomewhere onthe
page.It takesa single argument–the textpatterntobe verified.
o Use verifyTextPresentwhenyouare interestedinonlythe textitself beingpresenton
the page.Do not use thiswhenyoualsoneedto testwhere the textoccurson the page.
4. verifyElementPresent
o Use thiscommandwhenyoumusttestfor the presence of a specificUIelement,rather
than itscontent.Thisverificationdoesnotcheckthe text,onlythe HTML tag. One
commonuse is to checkfor the presence of animage.
o The first(and only) parameterisalocator fortellingthe Selenese commandhow tofind
the element.
o verifyElementPresentcanbe usedtocheck the existenceof anyHTML tag withinthe
page.You can check the existence of links,paragraphs,divisions<div>,etc.
verifyText
o Use verifyTextwhenboththe textanditsUI elementmustbe tested.verifyTextmust
use a locator. If youchoose an XPathor DOMlocator,you can verifythatspecifictext
appearsat a specificlocationonthe page relativetootherUI componentsonthe page.
Locating Elements
For manySeleniumcommands,atargetis required.Thistargetidentifiesanelementinthe contentof
the webapplication,andconsistsof the locationstrategyfollowedbythe locationinthe format
locatorType=location.
Locatingby Identifier
o Thisis probablythe mostcommonmethodof locatingelementsandisthe catch-all
defaultwhennorecognizedlocatortype isused.With thisstrategy,the firstelement
withthe idattribute value matchingthe locationwill be used.If noelementhasa
matchingidattribute,thenthe firstelementwithaname attribute matchingthe
locationwill be used.
o Example:identifier=loginForm.Since the identifiertype of locatoristhe default,the
identifier=inthe example above isnotnecessary.
Locatingby ID
o Thistype of locatoris more limitedthanthe identifierlocatortype,butalsomore
explicit.Use thiswhenyouknow anelement’sid attribute.
Locatingby Name
o The name locatortype will locate the firstelementwithamatchingname attribute.If
multiple elementshave the same value foraname attribute,thenyoucan use filtersto
furtherrefine yourlocationstrategy.The defaultfiltertype isvalue (matchingthe value
attribute).
o Examples:
name=username
name=continue value=Clear
name=continue Clear
name=continue type=button
***Note: Unlike some typesof XPathandDOMlocators,the three typesof locatorsabove allow
Seleniumtotesta UI elementindependentof itslocationonthe page.Soif the page structure and
organizationisaltered,the testwillstillpass.Youmayor may not wantto alsotest whetherthe page
5. structure changes.Inthe case where webdesignersfrequentlyalterthe page,butitsfunctionalitymust
be regressiontested,testingviaidandname attributes,orreallyviaanyHTML property,becomesvery
important.
Locatingby XPath
o XPathis the language usedforlocatingnodesinanXML document.XPathextends
beyond(aswell assupporting) the simple methodsof locatingbyidorname attributes,
and opensupall sorts of new possibilitiessuchaslocatingthe thirdcheckbox onthe
page.
o One of the mainreasonsforusingXPathis whenyoudon’thave a suitable idorname
attribute forthe elementyouwishtolocate.Youcan use XPathto eitherlocate the
elementinabsoluteterms(notadvised),orrelative to anelementthatdoeshave anid
or name attribute.XPathlocatorscan alsobe usedto specifyelementsviaattributes
otherthan idand name.
o Absolute XPathscontainthe locationof all elementsfromthe root(html) andasa result
are likelytofail with onlythe slightestadjustmenttothe application.Byfindinganearby
elementwithanidorname attribute (ideallyaparentelement) youcanlocate your
target elementbasedonthe relationship.Thisismuchlesslikelytochange andcan
make your testsmore robust.
o Since onlyxpathlocatorsstart with“//”,it isnot necessarytoinclude the xpath=label
whenspecifyinganXPathlocator.
o Examples:
xpath=/html/body/form[1] - Absolutepath(wouldbreakif the HTML was
changedonlyslightly)
//form[1] - Firstform elementinthe HTML
xpath=//form[@id='loginForm'] - The formelementwithattribute named‘id’
and the value ‘loginForm’
xpath=//form[input/@name='username'] - Firstformelementwithaninput
childelementwithattribute named‘name’andthe value ‘username’
//input[@name='username'] - Firstinputelementwithattributenamed‘name’
and the value ‘username’
//form[@id='loginForm']/input[1] - Firstinputchildelementof the form
elementwithattribute named‘id’andthe value ‘loginForm’
//input[@name='continue'][@type='button'] - Inputwithattribute named
‘name’andthe value ‘continue’andattribute named‘type’andthe value
‘button’
//form[@id='loginForm']/input[4] - Fourthinputchildelementof the form
elementwithattribute named ‘id’andvalue ‘loginForm’
LocatingHyperlinksbyLinkText
o Thisis a simple methodof locatingahyperlinkinyourwebpage byusingthe textof the
link.If twolinkswiththe same textare present,thenthe firstmatchwill be used.
<html>
<body>
<p>Are you sure you want to do this?</p>
6. <a href="continue.html">Continue</a>
<a href="cancel.html">Cancel</a>
</body>
<html>
o Example:link=Continue
Locatingby DOM
o The DocumentObjectModel representsanHTML documentand can be accessedusing
JavaScript.ThislocationstrategytakesJavaScriptthatevaluatestoanelementonthe
page,whichcan be simplythe element’slocationusingthe hierarchical dottednotation.
o Since onlydomlocatorsstart with“document”,itisnot necessarytoinclude the dom=
label whenspecifyingaDOMlocator.
<html>
<body>
<form id="loginForm">
<input name="username" type="text" />
<input name="password" type="password" />
<input name="continue" type="submit" value="Login" />
<input name="continue" type="button" value="Clear" />
</form>
</body>
<html>
o Examples:
dom=document.getElementById('loginForm') (3)
dom=document.forms['loginForm'] (3)
dom=document.forms[0] (3)
document.forms[0].username (4)
document.forms[0].elements['username'] (4)
document.forms[0].elements[0] (4)
document.forms[0].elements[3] (7)
Locatingby CSS
o CSS (CascadingStyle Sheets) isalanguage fordescribingthe renderingof HTML and XML
documents.CSSusesSelectorsforbindingstyle propertiestoelementsinthe document.
<html>
<body>
<form id="loginForm">
<input class="required" name="username" type="text" />
<input class="required passfield" name="password"
type="password" />
<input name="continue" type="submit" value="Login" />
<input name="continue" type="button" value="Clear" />
</form>
7. </body>
<html>
o Examples:
css=form#loginForm(3)
css=input[name="username"] (4)
css=input.required[type="text"] (4)
css=input.passfield(5)
css=#loginForminput[type="button"] (7)
css=#loginForminput:nth-child(2) (5)
***Note: Most experiencedSeleniumusersrecommendCSSastheirlocatingstrategyof choice asit’s
considerablyfasterthanXPathandcan findthe mostcomplicatedobjectsinanintrinsicHTML
document.
Matching Text Patterns
Examplesof commandswhichrequire patternsare verifyTextPresent,verifyTitle,verifyAlert,
assertConfirmation,verifyText,andverifyPrompt.Andashasbeenmentionedabove,linklocatorscan
utilize apattern.Patternsallowyoutodescribe,viathe use of special characters,whattextisexpected
rather thanhavingto specifythattextexactly.
GlobbingPatterns
o Most people are familiarwithglobbingasitisutilizedinfilename expansionataDOS or
Unix/Linux commandlinesuchasls *.c. In thiscase,globbingisusedtodisplayall the
filesendingwitha.c extensionthatexistinthe currentdirectory.Globbingisfairly
limited.Onlytwospecial charactersare supportedinthe Seleniumimplementation:
* whichtranslatesto“match anything,”i.e.,nothing,asingle character,ormany
characters.
[ ] (characterclass) whichtranslatesto“match any single characterfoundinside
the square brackets.”A dash(hyphen) canbe usedas a shorthandto specifya
range of characters (whichare contiguousinthe ASCIIcharacterset).A few
exampleswill make the functionalityof acharacterclass clear:
[aeiou] matchesanylowercase vowel
[0-9] matchesanydigit
[a-zA-Z0-9] matchesanyalphanumericcharacter
o Usinga patternforboth a linkanda simple testthatthe linkworked(suchasthe
verifyTitle does) cangreatlyreduce the maintenance forsuchtestcases.
RegularExpressions
o Regularexpressionpatternsare the mostpowerful of the three typesof patternsthat
Selenese supports.Regularexpressionsare alsosupportedbymosthigh-level
programminglanguages,manytexteditors,andahost of tools,includingthe Linux/Unix
command-lineutilitiesgrep,sed,andawk.
8. PATTERN MATCH
. any single character
[ ] character class:any single characterthat appearsinside the brackets
* quantifier:0or more of the precedingcharacter(orgroup)
+ quantifier:1or more of the precedingcharacter(orgroup)
? quantifier:0or 1 of the precedingcharacter(or group)
{1,5} quantifier:1through5 of the precedingcharacter(or group)
|
alternation:the character/grouponthe leftorthe character/groupon the
right
( ) grouping:oftenusedwithalternationand/orquantifier
o Regularexpressionpatternsprefixedwitheither
regexp:case-sensitive
regexpi:iscase-insensitive
o Probablythe mostcommonlyusedregularexpressionpattern–.*(“dotstar”).Thistwo-
character sequence canbe translatedas“0 or more occurrencesof anycharacter” or
more simply,“anythingornothing.”Itisthe equivalentof the one-characterglobbing
pattern* (asingle asterisk).
Exact
o The exact type of Seleniumpatternisof marginal usefulness.Itusesnospecial
characters at all.So,if you neededtolookforan actual asteriskcharacter(whichis
special forbothglobbingandregularexpressionpatterns),the exactpatternwouldbe
one way to dothat.
o For example,if youwantedtoselectanitemlabeled“Real *”froma dropdown,the
followingcode mightworkorit mightnot.The asteriskinthe glob:Real *patternwill
match anythingornothing.So,if there wasan earlierselectoptionlabeled“Real
Numbers,”itwouldbe the optionselectedratherthanthe “Real *” option.
The “AndWait” Commands
The difference betweenacommandanditsAndWait alternative isthatthe regularcommand
(e.g.click) will dothe actionandcontinue withthe followingcommandasfastas it can, while
the AndWaitalternative (e.g.clickAndWait) tellsSeleniumtowaitforthe page to loadafterthe
actionhas beendone.
The AndWaitalternative isalwaysusedwhenthe actioncausesthe browsertonavigate to
anotherpage or reloadthe presentone.
Be aware,if youuse an AndWaitcommandfor an actionthat doesnottriggera
navigation/refresh,yourtestwillfail. Thishappensbecause Seleniumwill reachthe AndWait‘s
9. timeoutwithoutseeinganynavigationorrefreshbeingmade,causingSeleniumtoraise a
timeoutexception.
The waitFor Commands inAJAX applications
In AJAXdrivenwebapplications,dataisretrievedfromserverwithoutrefreshingthe page.Using
andWaitcommandswill notworkas the page isnot actuallyrefreshed.The bestapproach
wouldbe to waitforthe neededelementinadynamicperiodandthencontinue the execution
as soonas the elementisfound.
Thisis done usingwaitForcommands,aswaitForElementPresentorwaitForVisible,whichwait
dynamically,checkingforthe desiredconditioneverysecondandcontinuingtothe next
commandin the scriptas soonas the conditionismet.
Sequence ofEvaluation and Flow Control
Whena script runs,it simplyrunsinsequence,one commandafteranother.
Selenese,byitself,doesnotsupportconditionstatements(if-else,etc.) oriteration(for,while,
etc.).
Whenflowcontrol isneeded,there are three options:
o Run the scriptusingSelenium-RCandaclientlibrarysuchas Javaor PHP to utilize the
programminglanguage’sflowcontrol features.
o Run a small JavaScriptsnippetfromwithinthe scriptusingthe storeEval command.
o Install the goto_sel_ide.jsextension.
Store Commands and SeleniumVariables
See seleniumdocumentation
o storeElementPresent
o storeText
o storeEval
JavaScript and Selenese Parameters
See seleniumdocumentation
o JavaScriptUsage withScript Parameters
o JavaScriptUsage withNon-ScriptParameters
echo - The Selenese PrintCommand
Simple commandthatallowsyoutoprinttextto yourtest’soutput.
o Provide informationalprogressnotesinyourtestwhichdisplayonthe console asyour
testis running.
o Usedto provide contextwithinyourtestresultreports,whichcanbe useful forfinding
where a defectexistsona page inthe eventyourtestfindsaproblem.
o Finally,echostatementscanbe usedtoprint the contentsof Seleniumvariables.
Alerts,Popups,and Multiple Windows
10. The user mustrespondto alert/confirmboxes,aswell asmovingfocustonewlyopenedpopup
windows.Fortunately,SeleniumcancoverJavaScriptpop-ups.
Debugging
BreakpointsandStartpoints
o The Sel-IDEsupportsthe settingof breakpointsandthe abilitytostartand stopthe
runningof a test case,fromany pointwithinthe testcase.
o It isalso sometimesuseful toruna testcase fromsomewhere inthe middletothe end
of the testcase or upto a breakpointthatfollowsthe startingpoint.
SteppingThroughaTestcase
o To execute atestcase one commandat a time (“stepthrough”it),follow these steps:
o Start the testcase runningwiththe Runbuttonfrom the toolbar.
o Immediatelypause the executingtestcase withthe Pause button.
o Repeatedlyselectthe Stepbutton.
FindButton
o The Findbuttonis usedto see whichUIelementonthe currentlydisplayedwebpage(in
the browser) isusedinthe currentlyselectedSeleniumcommand.
o From Table view,selectanycommandthathas a locator parameter.Clickthe Find
button.Nowlookonthe webpage:There shouldbe abrightgreenrectangle enclosing
the elementspecifiedbythe locatorparameter.
Page Source for Debugging
o Often,whendebuggingatestcase,yousimplymustlookat the page source (the HTML
for the webpage you’re tryingtotest) todetermineaproblem.Firefox makesthiseasy.
Simplyright-clickthe webpage andselect‘View->Page Source.
o Alternatively,selectjustthatportionof the webpage forwhichyouwantto see the
source.Thenright-clickthe webpage andselectViewSelectionSource.
Locator Assistance
o Thisfeature can be veryuseful forlearningmore aboutlocators,andisoftenneededto
helpone buildadifferenttype of locatorthanthe type that was recorded.
Selenium WebDriver
Introducing WebDriver
The primarynewfeature inSelenium2.0is the integrationof the WebDriverAPI.WebDriveris
designedtoprovide asimpler,more concise programminginterfaceinadditiontoaddressing
some limitationsinthe Selenium-RCAPI.
WebDriverand the Selenium-Server
You may,or may not, needthe SeleniumServer,dependingonhow youintendtouse Selenium-
WebDriver.
11. SettingUp a Selenium-WebDriverProject
To install Seleniummeanstosetupa projectina developmentsoyoucanwrite a program using
Selenium.Howyoudothisdependsonyourprogramminglanguage andyourdevelopment
environment.
o Java
o C#
o Python
o Ruby
o Perl
o PHP
Selenium-WebDriverAPICommandsand Operations
Fetchinga Page
o The firstthingyou’re likelytowanttodo withWebDriverisnavigate toa page.The
normal wayto do thisis bycalling“get”:
Java
driver.get("http://www.google.com");
C#
driver.Url = "http://www.google.com";
LocatingUI Elements(WebElements)
o LocatingelementsinWebDrivercanbe done onthe WebDriverinstance itselforona
WebElement.Eachof the language bindingsexpose a“FindElement”and“Find
Elements”method.The firstreturnsaWebElementobjectotherwise itthrowsan
exception.The latterreturnsalistof WebElements,itcanreturnan emptylistif no
DOM elementsmatchthe query.
o The “Find” methodstake alocator or queryobjectcalled“By”.“By” strategiesare listed
below.
By ID (Thisisthe most efficientandpreferredwaytolocate an element)
By ClassName
By Tag Name
By Name
By LinkText
By Partial LinkText
By CSS
By XPATH
User Input– FillinginForms
o WebDriver’ssupportclassesincludeone called“Select”,whichprovidesuseful methods
for interactingwiththese.
Selectselect=new Select(driver.findElement(By.tagName("select")));
select.deselectAll();
select.selectByVisibleText("Edam");
o Once you’ve finishedfillingoutthe form, youprobablywanttosubmitit.One wayto do
thiswouldbe to findthe “submit”buttonandclickit:
12. driver.findElement(By.id("submit")).click();
o Alternatively,WebDriverhasthe convenience method“submit”oneveryelement.If
youcall thison an elementwithinaform, WebDriverwill walkupthe DOMuntil itfinds
the enclosingformandthencallssubmitonthat.
element.submit();
MovingBetweenWindowsandFrames
o Some web applicationshave manyframesormultiple windows.WebDriversupports
movingbetweennamedwindowsusingthe “switchTo”method:
driver.switchTo().window("windowName");
o You can alsoswitchfromframe to frame (or intoiframes):
driver.switchTo().frame("frameName");
PopupDialogs
o StartingwithSelenium2.0beta 1, there isbuiltinsupportforhandlingpopupdialog
boxes.Afteryou’vetriggeredanactionthat opensa popup,youcan accessthe alert
withthe following:
Alertalert= driver.switchTo().alert();
Navigation:HistoryandLocation
o Earlier,we coverednavigatingtoapage usingthe “get” command(
driver.get("http://www.example.com"))Asyou’ve seen,WebDriverhasa numberof
smaller,task-focusedinterfaces,andnavigationisauseful task.
driver.navigate().to("http://www.example.com");
o To reiterate:“navigate().to()”and“get()”doexactlythe same thing.One’sjustalot
easiertotype than the other!
The “navigate”interface alsoexposesthe abilitytomove backwardsandforwardsin
your browser’s history:
driver.navigate().forward();
driver.navigate().back();
Drag and Drop
o Here’san example of usingthe Actionsclasstoperformadrag and drop.Native events
are requiredtobe enabled.
WebElementelement=driver.findElement(By.name("source"));
WebElementtarget=driver.findElement(By.name("target"));
(newActions(driver)).dragAndDrop(element,target).perform();
WebDriver: Advanced Usage
Explicitand Implicit Waits
WARNING:Do notmix implicitandexplicitwaits.Doingsocancause unpredictable waittimes.For
example settinganimplicitwaitof 10s and an explicitwaitof 15 seconds,couldcause a timeouttooccur
after20 seconds.
13. ExplicitWaits
o An explicitwaitsiscode youdefine towaitfora certainconditiontooccur before
proceedingfurtherinthe code.The worstcase of thisisThread.sleep(),whichsetsthe
conditiontoan exacttime periodtowait.
o There are some convenience methodsprovidedthathelpyouwrite code thatwill wait
onlyas longas required.WebDriverWaitincombinationwithExpectedConditionisone
waythis can be accomplished.
o WebDriverWaitbydefaultcallsthe ExpectedConditionevery500 millisecondsuntil it
returnssuccessfully.A successfulreturnisforExpectedConditiontype isBooleanreturn
true or notnull returnvalue forall otherExpectedConditiontypes.
ExpectedConditions
There are some commonconditionsthatare frequentlycome across
whenautomatingwebbrowsers.Javahappenstohave convienence
methodssoyoudon’thave to code an ExpectedCondition classyourself
or create your ownutilitypackage forthem.
o ElementisClickable- itisDisplayedandEnabled.
ImplicitWaits
o An implicitwaitistotell WebDrivertopoll the DOMfor a certainamountof time when
tryingto findan elementorelementsif theyare notimmediatelyavailable.
Test Design Considerations
Types ofTests
What parts of your applicationshouldyoutest?Thatdependsonaspectsof yourproject:user
expectations,time allowedforthe project,prioritiessetbythe projectmanager andsoon.
o TestingStaticContent
The simplesttype of test,acontenttest,isa simple testforthe existence of a
static,non-changing,UIelement.
Doeseach page have itsexpectedpage title?Thiscanbe usedtoverify
your testfoundanexpectedpage afterfollowingalink.
Doesthe application’shome page containanimage expectedtobe at
the top of the page?
Doeseach page of the website containafooterareawithlinkstothe
companycontact page,privacypolicy,andtrademarksinformation?
Doeseach page beginwithheadingtextusingthe <h1> tag? And,does
each page have the correct textwithinthatheader?
o TestingLinks
If static linksare infrequentlychangedthenmanual testingmaybe sufficient.
Howeverif yourwebdesignersfrequentlyalterlinks,orif filesare occasionally
relocated,linktestsshouldbe automated.
o Functional Tests
14. These wouldbe testsof a specificfunctionwithinyourapplication,requiring
some type of userinput,and returningsome type of results.
Functiontestsare oftenthe mostcomplex testsyou’ll automate,butare usually
the most important.Typical testscanbe for login,registrationtothe site,user
account operations,accountsettingschanges,complexdataretrieval
operations,amongothers.Functionteststypicallymirrorthe user-scenarios
usedto specifythe featuresanddesignoryourapplication.
o TestingDynamicElements
Oftena webpage elementhasaunique identifierusedtouniquelylocate that
elementwithinthe page.Usuallythese are implementedusingthe html tag’s
‘id’attribute orits ‘name’attribute.Thesenamescanbe a static,i.e unchanging,
stringconstant.Theycan also be dynamicallygeneratedvaluesthatvaryeach
instance of the page.A testscriptverifyingthatadocumentexistsmaynothave
a consistentidentifiertouse forlocatingthatdocument.Often,dynamic
elementswithvaryingidentifiersare onsome type of resultpage basedona
useraction.
o Ajax Tests
Ajax isa technologywhichsupportsdynamicallychanginguserinterface
elementswhichcandynamicallychange withoutthe browserhavingtoreload
the page,such as animation,RSSfeeds,andreal-timedataupdatesamong
others.
ValidatingResults
o Assertvs.Verify
The difference isinwhatyouwantto happenwhenthe checkfails.Doyouwantyour
testto terminate,orto continue andsimplyrecordthatthe checkfailed?
If you use an assert,the testwill stopat that pointandnot run anysubsequent
checks.Sometimes,perhapsoften,thatiswhatyouwant.If the testfailsyou
will immediatelyknow the testdidnotpass.
The advantage:youhave an immediate visualof whetherthe checks
passed.
The disadvantage:whenacheckdoesfail,there are othercheckswhich
were neverperformed,soyouhave noinformationontheirstatus.
In contrast,verifycommandswill notterminate the test.
The advantage:If your testusesonlyverifycommandsyouare
guaranteed(assumingnounexpectedexceptions) the testwillrunto
completionwhetherthe checksfinddefectsornot.
The disadvantage:youhave todo more workto examine yourtest
results.Thatis,you won’tgetfeedbackfromTestNGorJUnit.You will
needtolookat the resultsof a console printoutora logoutput.
LocationStrategies
There are multiplewaysof selectinganobjectona page.But what are the trade offsof each of
these locatortypes?Recall we canlocate an objectusing
o ChoosingaLocation Strategy
the element’sID
15. Usingan elementIDor name locatoris the mostefficientintermsof
testperformance,andalsomakes yourtestcode more readable
the element’sname attribute
Usingan elementIDor name locatoris the mostefficientintermsof
testperformance,andalsomakesyourtestcode more readable
an XPathstatement
XPathstatementstake longertoprocesssince the browsermustrunits
XPathprocessor
If the page source doesnot have an ID or name attribute youmayhave
no choice butto use an XPath locator
WithXPath (andDOM) youcan locate an objectwithrespecttoanother
objectonthe page.
by a linkstext
Locatingvia a link’stextisoftenconvenientandperformswell.This
technique isspecifictolinksthough
documentobjectmodel (DOM)
(DOMlocatorsare no longercommonlyusedsince XPathcando
everythingtheycanandmore.DOMlocatorsare available simplyto
supportlegacytests.)
o LocatingDynamicElements
o LocatingAjax Elements
WrappingSeleniumCalls
As withanyprogramming,youwill wanttouse utilityfunctionstohandle code thatwould
otherwise be duplicatedthroughoutyourtests.One waytopreventthisistowrap frequently
usedseleniumcallswithfunctionsorclassmethodsof yourowndesign.
o ‘Safe Operations”forElementPresence
Checkfor presence of anelementonpage before carryingoutsome operation.
Thisis sometimescalleda‘safe operation’.
Usingsafe methodsisup to the testdeveloper’sdiscretion.Hence,if test
executionistobe continued,eveninthe wake of missingelementsonthe page,
thensafe methodscouldbe used,whilepostingamessage toalog aboutthe
missingelement.This,essentially,implementsa‘verify’withareporting
mechanismasopposedtoan abortive assert. Butif elementmustbe available
on page inorder to be able to carry out furtheroperations(i.e.loginbuttonon
home page of a portal) thenthissafe methodtechnique shouldnotbe used.
UI Mapping
A UI map isa mechanismthatstoresall the locatorsfora testsuite inone place foreasy
modificationwhenidentifiersorpathstoUI elementschange inthe AUT.The testscriptthen
usesthe UI Map for locatingthe elementstobe tested.Basically,aUI map isa repositoryof test
scriptobjectsthat correspondtoUI elementsof the applicationbeingtested
o To summarize,aUI map has twosignificantadvantages.
Usinga centralizedlocationforUIobjects insteadof havingthemscattered
throughoutthe script.Thismakesscriptmaintenance more efficient.
16. CrypticHTML Identifiersandnamescanbe givenmore human-readablenames
improvingthe readabilityof testscripts.
o There are variouswaysa UI Map can be implemented.One couldcreate aclassor struct
whichonlystorespublicStringvariableseachstoringalocator.Alternatively,atextfile
storingkeyvalue pairscouldbe used. InJava,a propertiesfile containingkey/valuepairs
isprobablybestmethod.
Page ObjectDesignPattern
o Page Objectisa DesignPatternwhichhasbecome popularintestautomationfor
enhancingtestmaintenanceandreducingcode duplication.A page objectisanobject-
orientedclassthatservesasan interface toa page of yourAUT. The teststhenuse the
methodsof thispage objectclasswhenevertheyneedtointeractwiththatpage of the
UI.
Data DrivenTesting
o Data DrivenTestingreferstousingthe same test(ortests) multiple timeswithvarying
data. These datasetsare oftenfromexternal filesi.e..csvfile,textfile,orperhaps
loadedfroma database.Data driventestingisacommonlyusedtestautomation
technique usedtovalidate anapplicationagainstmanyvaryinginput.
Database Validation
o Anothercommontype of testingistocompare data inthe UI againstthe data actually
storedinthe AUT’s database.Since youcan alsodo database queriesfroma
programminglanguage,assumingyouhave database supportfunctions,youcanuse
themto retrieve dataandthenuse the data to verifywhat’sdisplayedbythe AUTis
correct.
Selenium-Grid