0% found this document useful (0 votes)
15 views

200+ Selenium Interview Questions

Uploaded by

b540kc
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views

200+ Selenium Interview Questions

Uploaded by

b540kc
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 40

200+Sel

eni
um I
nter
viewQuest
ions

Sel
eni
um I
nterv
iewQuest
ions[
Cor
e
Sel
eni
um Concept
s]
WhatI
sSel
eni
um?WhyI
sItUsed?
Seleni
um i
sacr oss-pl
atfor
m andpor tableaut
omat i
ontest
ing
frameworkcreatedbyJasonHuggi nsi n2004.
Ithasseenseveralupgradessincethen, WebDri
ver2.0i
n2011,
and3.0in2016.Checkt hebelowSel enium t
imeli
ne.

WecanuseSel enium towrit


eaut omati
onscriptsfortesting
webappl icat i
ons.Ithelpsinreducingmanual test
ingefforts,
i
mpr ovespr oduct ivi
tyandquality
.
Cross-platf
or m meansaSel enium scri
ptwrit
tenononeOSsay
Windowscanr unonot hersupportedsyst
emssuchasLi nuxor
MacOSwi thoutmaki nganychanges.
Portablemeanst hesamescr iptcreat
edforadeskt op-based
devi
cecanr unondi ffer
entsuppor t
eddevicessuchast abl et
s,
mobi l
es,etc.
WhatIsSel
eni
um RC,
AndHowDoesI
tTal
kTo
ABrowser?
Sel
enium RCa.
k.a.Remot eContr
olcameoutinearl
y2004.
I
texposedasetofclientAPIswhichusetosendcommandsto
aserv
ertoperf
orm actionsonthebrowser.
WhatI
sSel
eni
um 2.
0,AndWhyI
sItSuper
iorTo
RC?
Selenium 2. 0a.k.
a.WebDri
verisasetofnati
veAPIswhich
dir
ect lysendcommandst ot hebrowseri
nsteadofdel
egat
ing
toaser ver.
I
tsr eleasecameouti n2011.Itpr
ov i
dedthenati
veWebDri
ver
APIi nterfacerepl
aci
ngtheoldcli
ent-
serv
erAPImodel.

1
WhatI
sSel
eni
um 3.
0,AndWhyI
sItSuper
iorTo
2.
0?
Itwasamaj orWebDr i
verupgradewhi chlandedupin2016.
Iti
ssuper i
orto2. 0becauseitimplementedt heW3C
specifi
cati
onsf orWebdr i
verAPIstomaket hem agl
obal
standard.
Unt i
l3.
0,itwast heSeleni
um communi t
ythatwassuppl y
ing
Webdr iversforspecif
icbrowsers.Butnow, theypr
ovidethei
r
respecti
vedr i
versthatsupportthestandardWebdr i
verAPI
i
nt er
face.
WhatIsTheLat
estSel
eni
um Webdr
iver
Ar
chit
ectur
e?
Bel
owblockdiagr
am expl
ainst
hel
atestar
chi
tect
ureSel
eni
um
Webdr
iversuppor
ts.

<i
mgcl ass=" al
igncentersize-f
ullwp-i
mage- 7170"
src="/
/cdn. t
echbeamer s.com/ wp-
content/uploads/2015/08/ Seleni
um-Webdr iver-
Archit
ecture.png"alt
="Selenium Webdr i
verAr chi
tectur
e"
width="537"height="251"srcset="//
cdn.techbeamer s.
com/wp-
content/uploads/2015/08/ Seleni
um-Webdr iver-
Archit
ecture.png537w, //cdn.t
echbeamer s.com/ wp-
content/uploads/2015/08/ Seleni
um-Webdr iver-
Archit
ect
ure-
300x140. png300w"si zes="(max-width:537px)100v w,537px
">
WhatAreTheDif
fer
entComponent
sOfThe
Sel
eni
um Framewor
k?
Sel
enium isanautomati
ondevelopmentki
tthatcomprisesthe
fol
l
owi ngcomponents.
▪ Sel enium I
DE:
AFiref
ox/chromeextensi
ontorecordandplaytheuseracti
ons
perf
ormedonawebpage.

▪ Seleni
um RC:
ASel
eni
um RemoteControl
whichexposesAPIsforscr
ipt
ing
t
est
sindi
ff
erentl
anguagesandalsorunsthem i
nbrowser
s.

2
▪ Sel enium Webdr i
ver:
Thesearenati
veAPI sthatdi
rectl
yinteractwi
tht
hebr owser
.
Theygi
vemor econtrolandfasterthant heRCAPIs.
▪ Sel enium Gr
id:
I
tprovi
desconcurrency.Withit
shel p,wecanspl
ittesti
ngand
runasetofcasesononemachi neandsomeonanot her
.

WhatAreTheBenef
it
sDoesWebDr
iverHas
OverSel
eni
um RC?
Selenium RChadacompl exar chitecture,wher easWebDr iver
remov edt hosecompl ications.Thebel owpoi ntsdi scusswhy
WebDr i
verisbet terthant heRC.
▪ Sel enium RCi sslowbecausei thasanaddi ti
onal
JavaScr iptlayerknownast hecor e.Ont hecont rary,
WebDr i
v erisfastasi tnat ivelyinteract swi ththebr owser
byut i
li
zi ngitsbuilt-
inengi ne.
▪ Sel enium cor ecan’ tignor et hedi sabl edel ement s,
wher easWebDr i
v erhandl est hepageel ement smor e
reali
stically
.
▪ Sel enium RChasamat uresetofAPI sbutsuf fersfrom
redundanci esandcompl i
cat edcommands.Ont heot her
hand, WebDr i
verAPI shav eacl eaneri nterfaceanddonot
haveanysuchpr oblems.
▪ Sel enium RCdoesn’ tpr ov idesuppor tf ortheHt mlUnit
browser ,whereast heWebDr iverhasaheadl essHt mlUnit
dri
ver .
▪ Sel enium RCi ncludesat estr esultgener atortopr oduce
HTMLr eports.WebDr i
v erdoesn’ thav eanybui lt-i
n
reporti
ngabi l
ity
.
WhatAr
eTheBenef
it
sOfSel
eni
um Aut
omat
ion?
Therear emanybenef i
tsofusingSelenium foraut
omat ed
test
ing.
▪ Opensour ce:SinceitisanOSS, sowedon’ thavetobear
anyli
censi
ngcostf orusingit
.
▪ Cr oss-
browser:Itworksonallstandardbrowserssuchas
Chrome,FF,I
E,andSaf ari.Wecanr unsamet hetestscr
ipt

3
i
nal l browser s.
▪ Mul ti
-language:Wecanchooseaf ami li
arprogr ammi ng
l
anguagef rom Jav a,Python,C#, Rubyt ousewi th
Seleni um.
▪ Cross- platform:I tprov i
dest estcompat ibil
it
yacr oss
Wi ndows, Linux,andMacOSX.Wecanr unsamet hetest
scriptonal lplatf
or ms.
▪ Concur r
ency :WithSel enium Gr id,wecanexecut e
thousandsoft est sinpar al
lel.
▪ CLIsuppor t:Wecancr eateat estsuitewi thhundr edsof
testsandl aunchi twithasi nglecommand.
▪ CIsuppor t:Jenki nsi sthebestCIt ool.Itprovidesa
Seleni um pl ugi ntoconf i
guret estsforni ghtl
yexecut i
on.
▪ Thi r
dpar tyintegrat i
on
▪ Freehel p:Wecangetqui ckt echnicalsuppor tfrom it
s
l
ar gecommuni ty.
▪ Test erf riendly :Anon- programmercanal soaut omate
usingSel eni um.I tisnott oocompl icatedt obe
usedonl ybyapr ogrammer .
▪ Ongoi ngpr oject:Act i
vedev elopmentandbugf ixesont he
l
atestpr oj ect.
WhatAr
eSomeDownsi
desToSel
eni
um
Aut
omati
on?
Sel
eni
um i
saper fectcli
nicaltooltoimper sonateuseract
ions
i
nabrowser.Howev er,i
talsohasaf ewl i
mi t
ati
onsgivenbelow.
▪ Doesn’ tsuppor tautomat i
onofWi ndowsappl i
cati
ons
▪ Can’tper for
m mobi l
eaut omationoni tsown
▪ Lacksagoodbui l
t-
inreporti
ng
▪ Not100%per fectforhandl i
ngdy nami cwebelements
▪ Poseschal l
engeswhi l
epr ocessingpopupsorf rames
▪ Nott hatef f
icienti
ncopi ngwi ththepagel oad
▪ Can’taut omat eacapt cha
WhatPr
ogr
ammi
ngLanguagesDoesSel
eni
um
Al
l
owToUse?
Sel
eni
um Webdr
iversuppor
tst
hef
oll
owi
ngpr
ogr
ammi
ng

4
l
anguages.
▪ Py t
hon
▪ Jav a
▪ C- Sharp
▪ Jav aScr
ipt
▪ Ruby
▪ PHP
▪ Per l
WhatAreTheOS/
Plat
for
msDoesSel
eni
um
Suppor
t?
Fol
l
owingi sthel
i
stofOS/
plat
for
mswhi
chSel
eni
um suppor
ts.
▪ Wi ndowsDesktop
▪ Wi ndowsMobile
▪ Li nux
▪ MacOSX
▪ I OS
▪ Andr oid
WhatTypesOfCasesCanYouAut
omat
eWi
th
Sel
eni
um?
WecanuseSel enium f
oraut
omat
ingt
hef
oll
owi
ngt
ypesof
cases.
▪ Funct i
onal cases
▪ Regr essiont estcases
▪ Accept ancet est
s
▪ Sani t
yt estcases
▪ Smoket esting
▪ End- t
o-endt estcases
▪ Cr oss-browsert ests
▪ I nt
egrationt est s
▪ Responsi venesscases

CanYouUseSeleni
um ForTest
ingRestAPIOr
WebServ
ices?
Sel
eni
um prov
idesNati
veAPIsforint
eract
ingwi
tht
hebrowser
usi
ngact
ionsandevents.TheRestAPIandthewebser
vices

5
don’
thaveanyUIandhencecan’
tbeaut
omat
edusi
ng
Sel
enium.

WhatAr
eTheDif
fer
entTypesOfWebDr
iver
API
sSuppor
tedI
nSeleni
um?

Foll
owingar ethewebdr i
verssuppor t
edinSel enium.
|WebDr i
v erName|WebDr i
verAPI|Suppor tedBr owser|
1GeckoDr iver(a.k.
a.Mar i
netto)| Fir
efoxDriver(
)| Fir
efox
2Microsof tWebDr i
ver(a.
k.a.Edge)| I
nternetExplorerDri
ver
()|
IE
3GoogleChr omeDr i
ver|Chr omeDr i
ver(
)| Chrome
4HTMLUni tDriver|WebCl i
ent ()|{Chrome, FF,I
E}
5OperaChr omi um Dr i
ver|Chr omeDr iver
()| Opera
6SafariDriver| Safari
Driv
er()| Safari
7AndroidDr i
ver,AndroidDri
ver ()|Androidbr owser
8iosDriver| IOSDr i
ver(
)|iosbr owser
9EventFiri
ngWebDr iver|EventFi r
ingWebDr iver
()|ALL

WhichOfTheWebDr
iverAPI
sIsTheFast
est
,
AndWhy?
Iti
snoneot herthant heHTMLUni tDr
iver
,whichisfast
erthan
allofit
scounterparts.
Thet echni
calreasoni sthattheHTMLUni tDri
verdoesn’t
executeinthebr owser.Itempl oysasimpleHTTPr equest-
responsemechani sm f ortestcaseexecuti
on.
Thismet hodisfarquickert hanstart
ingabrowsertocarryout
testexecuti
on.

WhatDoYouKnowAboutSel
eni
um I
DE?
Sel
enium I
DEi
sat r
endyFir
efox/
CHROMEbr owserext
ensi
on.
I
tpresent
sagraphi
cali
nter
facet
orecor
d,pl
ay,andsav
euser

6
act
ions.Testautomat i
onbegi nner
scanf indi
tconv eni
entfor
webautomat iontest
ing.Aftercapturi
ngawor kflow,wecan
al
soexpor tt
hest epsinv ar
iousformats.
Shi
nyaKasat aniwast hedev el
operwhocr eat
edt heSeleni
um
I
DE.Thei deacrossedhi smi ndwhilehewasi nvesti
gat
ingthe
JavaScri
ptcodeinsidetheSel eni
um core.Het hendidaproof
ofconceptanddev elopeditintoafull
-f
ledgedIDE.
WhatDoYouKnowAboutSel
enese?
Selenium I
DEhasabui lt-
inlinguisti
csy stem knownas
Selenese.Itisacol l
ectionofSel enium commandst operform
actionsonawebpage.
Forexampl e,i
tcandet ectbr okenl i
nksonapage, checkthe
presenceofawebel ement ,
Ajax, JavaScr i
ptalerts,andal ot
mor e.Therear emai nl
yt hreet y
pesofcommandi nSelenese.
▪ Act i
ons:I tcanalterthest ateofanappl i
cation.For
exampl e,youarecl i
ckingonal ink,selectingav al
uef r
om
thedrop-down, et
c.
▪ Accessor s:Thesecommandsmoni torthest ateofan
appl
icat i
onandcachei tintosomev ariable.For
exampl e,stor
eText Present,storeElement Pr esentetc.
▪ Asser tions:Thesecommandsal l
owaddi ngacheckpoi nt
orav erif
icati
onpoi nt.Theyconf i
rmt hecur rentstateofa
UIel
ement .

WhatDoYouKnowAboutSel
eni
um Gr
id?
Selenium Gri
disat oolwhichcandistri
but
etestsacross
mul t
iplebrowsersordif
ferentmachines.I
tenablesparal
l
el
execut i
onofthetestcases.Usingthis,
wecanconf i
guretor
un
thousandsoft estcasesconcurrent
lyonseparat
edev i
cesor
browser s.

WhatDoYouUseSel
eni
um Gr
id?
Sel
enium Gr
idal
l
owsthet
estcasestorunonmul t
ipl
e
pl
atf
ormsandbrowser
ssi
multaneousl
y,andhence,suppor
ts

7
di
str
ibut
edtesti
ng.
Thi
sabili
tyt
oparal
lel
i
zet
het
est
ingi
swhatmakesususet
he
Sel
enium Gr
id.

WhatAr
eThePr
os/
Benef
it
sOfUsi
ngSel
eni
um
Gr
id?
Ther
eareano.ofbenef it
sofusi ngt heSeleni
um Grid.
▪ Suppor tconcur
renttestexecut i
onandhencesav esusa
l
otofourt i
me.
▪ I tpresentsuswiththeabilit
yt oexecutetestcasesin
di
ffer
entbrowsers.
▪ Af t
ercreati
ngmul t
i-
machi nenodes, wecanusei tto
di
stri
butetest
sandexecut et hem.

WhatDoesAHubDoI
nSel
eni
um Gr
id?
Ahubisanalogoustoaser
verthatdr
ivest
hepar
all
elt
est
execut
ionondif
fer
entmachines.

WhatDoesANodeDoI
nSel
eni
um Gr
id?
Themachinewer egist
ert
oahubr epresent
sanode.The
regi
str
ati
onallowst hegri
dtof
etchnodeconf i
gurat
ionand
execut
etests.Therecouldbemult
iplenodesthatwecanbind
toaSeleni
um Gr i
d.

WhatI
sTheCommandToBi
ndANodeTo
Sel
eni
um Gr
id?
Pleasemakesur etodownloadt heSelenium-ser
verjarbef
ore
runningthebelowcommand.
j
av a–jar<seleni
um-ser
ver-
standalone-
x.xx.
x.j
ar>–rolenode
–hubht t
p://<nodeI
P>:4444/gri
d/regi
ster

8
Whi
chOfJava,
C-Shar
p,OrRubyCanWeUse
Wi
thSel
eni
um Gri
d?
▪ Jav a:Yes,wecan.Mor eover,
wecandopar al
lelt
esting
usingTest NGt outi
li
zetheSelenium gr
idfeatures.
▪ C-Shar p:Yes,wecan.Weneedt ouse“Galli
o”t orunour
testsconcur r
entl
yinthegrid.
▪ Ruby :Yes,wecan.We’ l
lusethe“ DeepTest”todistr
ibute
ourt estsacrossthegri
d.

WhatAreSeleni
um Gr
idExt
ras?WhatAddi
ti
onal
Feat
uresDoesItAddToSel
enium Gr
id?

Sel
eni
um Gr i
dExt r
asi sasetofmanagementscr ipt
st o
managenodesmor eefficiently .
Bel
owisasummar yofthef eat urespr ovi
dedbyext ras.
▪ Mor econt rol overthei ndiv i
dual nodes
▪ Kil
labr owserr unningt est sbyname
▪ Stopapr ocessorpr ogram byi tsPID
▪ Shiftthemouset oaspeci f
iccoor di
nate
▪ Retrievephy sicalmemor y( RAM)andper sist
entstorage
(Disk)usagest atisti
cs
▪ Aut oupgr adet onewerv er sionsofWebDr iver
▪ Reset /re-
st ar
tt estnodesaf t
eraspeci fi
edno.ofi ter
ations
▪ Cent rall
ymanaget heconf igurati
onofal lnodes
▪ Capt urescr eenshot sdur inger rorcondit
ions

WhatIsTheDiffer
enceBetweenMaxSessi
ons
Vs.MaxI
nstancesProper
ti
esOfSeleni
um Gri
d?

Sometimeswegetconf
usedwhil
ediffer
ent
iat
ingbetween
theMaxSessi
onsvs.MaxI
nst
ances.Let’
sunderst
andthe
dif
fer
encewit
hclar
it
y.

9
1.MaxI nstances:Itistheno.ofbr owseri nstances(ofthe
samev er si
ons)thatcanr unont her emotemachi ne.Checkthe
belowcommands.
-browser
browser Name=f i
refox,v
ersion=59,maxI nstances=3,
platf
orm=WI
NDOWS
-browser
browser Name=InternetExplorer,
version=11,maxInstances=3,
pl
a
tform=WI NDOWS
Itmeanswecanr unt hreeinstancesofbot hFir
efoxandI Eat
thesamet i
me.So, at otalofsixdifferentbrowsers(FF&I E)
couldruni nparal
lel.

2.MaxSessi on:Itdict
ateshowmanybr owsers(independentof
thetype&v ersion)canrunconcur rent
lyont heremot emachine.
Itsupersedesthe“ MaxInstances”sett
ing.
I
nt hepr ev
iousexampl e:Ifthevalueof“maxSessi on”isone,
thennomor ethanasi nglebrowserwoul drun.Whi l
eitsval
ueis
two,thenanyoft hesecombi nat
ions(2FF,2IE,1FF+1IE)canrun
atat i
me.

Sel
enium I
nter
viewQuest
ions[
Locat
ors
Rel
ated]

WhatAr
eTheLocat
orsSel
eni
um Suppor
ts?
Fol
l
owingisthelistofsuppor t
edlocat
orsbySelenium.
▪ I D:Uniqueforev er
ywebel ement
▪ Name:SameasI Dalthoughitisnotunique
▪ CSSSel ector:Worksonel ementtagsandat tr
ibut
es
▪ XPat h:Sear cheselementsintheDOM, Reli
ablebutslow
▪ Cl assname:Usest heclassnameat tr
ibute
▪ TagName:UsesHTMLt agstolocatewebel ements
▪ Li nkText:Usesanchort extt
olocatewebel ements

10
▪ Part
ialLi
nkText
:Usespar
ti
all
i
nkt
extt
ofi
ndweb
el
ement s

WhichOfTheI
d,Name,
XPat
h,OrCSSSel
ect
or
Shoul
dYouUse?

Ift
hepagehasuni
quenamesori
dent
if
ier
sav
ail
abl
e,t
henwe
shoul
dusethem.

I
ftheyarenotav
ail
abl
e,t
hengof
oraCSSsel
ect
orasi
tis
f
astert
hantheXPath.

Whennoneoft
hepr
efer
redl
ocat
orsi
spr
esent
,theny
oumay
t
rytheXPat
h.

WhatI
sXPat
h?HowDoesI
tWor
k?
XPat
hist
hemost-
usedl
ocat
orst
rat
egi
esSel
eni
um usest
o
fi
ndwebel
ement
s.

▪ I
tworksbynavigati
ngthroughtheDOM element
sand
att
ri
but
estolocatethetargetobj
ect
.Forexampl
e–at ext
boxorabutt
onorcheckboxes.

▪ Al
thoughitguaranteestogiveyoutheel
ementy
ouare
l
ookingaft
er.Butitisslowerthanascompar
edtoot
her
l
ocatorsl
i
keI D,name, orCSSselect
ors.

WhatDoesASi
ngl
eSl
ash“
/”MeanI
nXPat
h?
Asingl
e(for
ward)sl
ash“ /
”repr
esent
stheabsol
utepath.
I
nthiscase,
theXPathenginenavi
gat
estheDOM rightf
rom t
he
f
ir
stnode.
/
html/body/
div
/div[
2]/
input

11
WhatDoesADoubl
eSl
ash“
//”MeanI
nXPat
h?
Adoubl e(for
ward)Slash“/
/”r
epresentstherel
ati
vepath.
Inthiscase,theXPathengi
nesearchesforthematchi
ng
elementany whereintheDOM.
//div
/ /
input[
@id=’t
est’
]

WhatIsAnAbsol
uteXPat
h,Expl
ainWi
th
Example?

Anabsol ut
eXPat hwi l
lalwayssear
chf r
om therootnodeunt
ili
t
reachesthet ar
get .SuchanXPat hexpressi
onincl
udesthe
singl
ef or
war d-
slash( /)asthepref
ix.
/html/body/div
[1]/div[
5]/for
m/tabl
e/tbody/
tr[
3]/t
d/i
nput

WhatI
sARel
ati
veXPat
h,Ex
plai
nWi
thExampl
e?

Ar el
ati
veXPat hdoesn’thaveaspeci
fi
cpointtostar
t.I
tcan
beginnavigat
ionfrom anynodeinsi
detheDOM andcont i
nues.
SuchanXPat hexpr essi
onincl
udesthedoublefor
ward-sl
ash
(/
/ ),
asgivenbelow.
//div[
@id=app]
HowDoYouLocateAnEl
ementByPar
ti
all
y
Compar
ingI
tsAt
tri
but
esI
nXPath?

XPat hsuppor t
sthecontains(
)method.I
tallowspar
ti
all
y
mat chingofattri
but
e’svalue.
Ithelpswhent heattr
ibutesusedy
nami cvalueswhi
lehavi
ng
somef ixedpart
.
Seet hebel owexample-
xPat husage=>/ /*[
contains(
@cat
egory,'
tablet
')
]
i
d=t est_123
test_234
test_345

12
/
/input
[cont
ains(
@id,
‘t
est
_’
)]

Theaboveexpressi
onwoul
dmat chall
val
uesoft
hecat
egor
y
at
tri
but
ehavingtheword‘
tabl
et’
inthem.

HowDoYouLocat
eEl
ement
sBasedOnThe
TextI
nXPat
h?
Wecancallthetext
()method.Thebelowexpressi
onwi
l
lget
el
ement
st hathavetextnodesthatequal
‘Py
thon.’
xPat
husage=/ /a[
text(
)='
Python'
]

HowDoYouAccessThePar
entOfANodeWi
th
XPat
h?
Wecanuset hedoubl
edot(
“..
”)t
opointtotheparentofany
nodeusingtheXPath.
Forexample–Thel ocat
or/
/span[@id=”cur
rent
”]
/..wil
lretur
n
theparentofthespanel
ementmatchingidval
ueas‘current’
.

HowDoYouGetToTheNt
hSub-
ElementUsi
ng
TheXPat
h?
Wecanmodi fyt
heXPat hexpr
essiontogett
ot hent
helement
i
nt hefollowingways:
1.UseXPat hasanarraybyappendingthesquarebr
acket
s
withani ndex.
#Exampl e
tr[
2]
Theabov eXPathexpressi
onwill
retur
nthesecondrowofa
table.
2.Bycal l
ingposit
ion(
)intheXPathexpressi
on
#Exampl e
tr[
posit
ion()=4]

13
Theabov
eXPat
hwi
l
lgi
vet
hef
our
thr
ow.

HowDoYouUse“
Class”AsACSSSel
ect
or?
Wecanuset hebel
owsyntaxt
oaccessel
ementsusingthe
classCSSsel
ector
.
.<cl
ass>
e.g..
col
or
Itcanhel
ptosel
ectal
lel
ementsr
elat
edtothespeci
fiedcl
ass.

HowDoYouUse“
ID”AsACSSSel
ect
or?
Wecanuset hebelowsy
ntaxt
oaccessel
ement
susi
ngI
Das
theCSSselect
or.
#<ID>
e.g.#name

HowToSpeci
fyAt
tri
but
eVal
ueWhi
l
eUsi
ngThe
CSSSel
ect
or?
Her eisthesy nt
axtopr
ovi
det
heat
tri
but
eval
uewi
tht
heCSS
selector.
[att
ribute=val
ue]
e.g.[type=submit]

HowToAccessTheNt
hEl
ementUsi
ngTheCSS
Sel
ect
or?
Her ei
st hesy ntaxtoaccesst
hent
hat
tri
but
eusi
ngt
heCSS
selector.
<type>:nth-chi
ld(n)
e.g.tr
:nth-chil
d(4)

WhatI
sThePr
imar
yDi
ff
erenceBet
weenThe
14
XPat
hAndCSSSel
ect
ors?
Wit
ht heXPat
h,wecantr
aver
sebothfor
wardandbackwar
d,
whereasCSSsel
ect
oronlymovesf
orward.

Par
t–2:

Sel
eni
um I
nter
viewQuest
ions[
APIOr
CommandsRelated]

WhatAreTheSt
epsToCr
eat
eASi
mpl
eWeb
Dr
iverScr
ipt
?
Bel
owaretheminimalst
epst ocreateaWebDri
verscript.
▪ Launcht heFir
efoxorChromebr owserbycreati
ngt he
WebDri
verr
efpoint
ingtoChromDr i
ver/
Fir
efoxDrivercl
ass.

▪ Openwebsi tewww. google.
co.i
nusingt
heget (
)met hod.

15
▪ Waitforthewebpagetoload.
▪ Di
splayamessageont heconsol
ethatt
hewebpageget
s
l
oadedsuccessful
ly.
▪ Cl oset hebrowser
.
Sour
ceCode:
publi
cclassSimpl
eWebDri
verScri
pt{
publi
cstat
icvoi
dmain(
Stri
ng[]args){

WebDr
iverdr
iver=newFi
ref
oxDr
iver
();

St
ri
ngURL=" htt
ps:
//www.
googl
e.co.
in"
;
dr
iver
.get
(URL)
;

dr
iver
.manage(
).
ti
meout
s()
.i
mpl
i
cit
lyWai
t(
25,
TimeUni
t.
SECONDS)
;

Sy
stem.
out
.pr
int
ln(
"Webpageget
sloadedsuccessf
ull
y!
!"
);

dr
iver
.cl
ose(
);
}
}

WhatDoesFi
ref
oxDr
iverMean,
ACl
assOrAn
I
nter
face?

Fi
ref
oxDri
veri
saJav
acl
ass,
andi
timpl
ement
stheWebDr
iver
i
nter
face.

WhichIsTheSuperI
nter
faceOfSel
eni
um Web
Dr
iver
?
ThSearchCont
extact
sast
hesuperi
nter
facef
ort
heWeb
Dri
ver
.

I
tistheexter
nali
nterfacewhichhasonl
ytwomet
hods:
f
indElement(
)andfindElements(
)

16
WhatDoesTheWebdri
verDr
iver=New
Fi
ref
oxDri
ver
();
Mean?

Webdr
iverdr
iver=newFi
ref
oxDr
iver
();

Theabovel
ineofcoder epr
esentsthefoll
owing:
▪ Thedr iverisav ar
iableoftype‘Webdri
ver’i
nter
face.
▪ Wear einstant
iati
nganobj ectoftheFir
efoxDri
vercl
ass
andst
oringiti
ntot hedri
vervari
able.

WhyDoWeCr eateARefer
enceVari
ableOfTy
pe
Webdr
iver
,NotTheAct
ualBrowserType?
I
tisbecausewecoul duset hesameWebdr i
vervari
abl
et ohold
theobjectofanybr owser,suchastheChr omeDriv
er,I
EDriver
,
orSafariDr
iver,et
c.
#Wef ol
lowt hi
sappr oachasitcanwor kwit
hanybr owser
i
nstance.
WebDr iv
erdriver=newFi ref
oxDriv
er();
#Thisappr oachisrighttoobutwillworkonlyt
heFirefox.
Fir
efoxDriv
erdr i
ver=newFi ref
oxDriver
();

HowDoYouPassCr edent
ialsToAn
Aut
hent
icat
ionPopupInSeleni
um?
Wecombi net heusernameandpasswor dstr
ingsusingt
he
col
onsepar at
orandst uffthem betweenthe“htt
p:/
/”andthe
si
teURL.Seet hebel
owexampl e.
htt
p:/
/userid:
passcode@somesi t
e.com
e.
g.http:
//userid:
passcode@somesi te.
com

WhatAreTheDi
ff
erentExcept
ionsAv
ail
abl
eIn
Sel
eni
um?
Li
kemanypr
ogr
ammi
ngl
anguages,
Sel
eni
um al
sopr
ovi
des

17
except
ionhandl ing.Thest andar dexceptionsinSelenium ar
e
asfoll
ows.
▪ Ti meout Except ion:Thisoccur sifacommanddoesn’ t
fi
nishwi t
hint hespeci fi
eddur ati
on.
▪ NoSuchEl ement Exception:Thisoccur sift
hewebel ement
withthespeci fiedat t
ri
butesi snotpresentont hepage.
▪ El ement Not Visibl
eExcept i
on:Thi soccursift
heel ementi
s
notv i
sibl
ebutst il
lthereinsidetheDOM.
▪ St aleEl
ement Except i
on:Thisoccur sintheabsenceofan
elementt hatei t
hergotdel etedordet achedfr
om t heDOM.

WhatDoYouKnowAboutAnExcept
ionTestI
n
Sel
eni
um?
Anexcept i
ont esti
saspecial except
ionthatoccursinatest
class.
Suppose, wehav ecreatedatestcasethatcant hrow
anexcept i
on.
Inthiscase,the@Testannot ati
oncanhel pusspecifyt
he
excepti
ont hatcouldoccur.
Checkoutf rom thebelowexampl e.
@Test (
actualExcepti
on=Element NotVisi
bleExcepti
on.
class)

HowI
sAnAsser
tDi
ff
erentFr
om Ver
if
y?
▪ Assert
:Ital
lowsustov er
if
ytheresul
tofanexpr
essi
onor
anoperati
on.Ift
he“assert
”fai
l
s,thenitwi
ll
abor
tthetest
execut
ionandconti
nueswi t
hthenextcase.

▪ Ver
if
y:Ital
sooperat
esthesameastheasser
tdoes.
However,i
fthe“v
eri
fy”f
ail
s,t
heni
twon’
tabortt
hetest
i
nst
eadcont i
nueswit
hthenextst
ep.
WhatDi
ff
erenceDoYouMakeBet
weenSof
tVs.
Har
dAssertI
nSeleni
um?

18
▪ SoftAssert:Itaggregatestheerr
orsthatoccurr
eddur i
ng
thetestexecut i
on.Ifsuchanassertfai
ls,t
hecontrol
j
umpst othenextst ep.
▪ HardAsser t:Iti
mmedi atelyr
espondswi t
han
AssertExceptionandbr eaksthecur
renttest.Af
terthat
,
thenextcasei nthesequenceget sexecuted.

WhatAreTheDi
ff
erentWai
tsAv
ail
abl
eIn
WebDri
ver
?
I
nSeleni
um Webdr i
ver,thef ol
l
owingt
hreet
ypesofwai
t
mechani
smsar eavailable.
St
ati
cWai t–Thread.sleep(15000)
;
▪ I mplici
tWait–
▪ Expl i
citWait–
▪ Fl uentWait–

WhatI
sWebDr
iverI
mpl
i
citWai
t?
I
mpl i
citWait
:Iti
sawai tti
meoutwhichappli
est oaWebdriv
er
i
nstance.Iti
mpl i
esthatal
lacti
onsofthi
sinstancewi
llti
meout
onl
yafterwait
ingforadurati
onspecif
iedbytheimpli
citwai
t.
WebDriverdr
iver=newChr omeDri
ver(
);
dr
iver
.manage(
).
ti
meout
s()
.i
mpl
i
cit
lyWai
t(
15,
TimeUni
t.
SECONDS)
;
e1
e2
e3

dr
iver
.manage(
).
ti
meout
s()
.i
mpl
i
cit
lyWai
t(
10,
TimeUni
t.
SECONDS)
;
e4e5e6

dr
iver
.manage(
).
ti
meout
s()
.i
mpl
i
cit
lyWai
t(
0,Ti
meUni
t.
SECONDS)
;
e7e8e9

WhatI
sWebDr
iverExpl
i
citWai
t?
Expli
citWait
:Iti
sanexclusi
veti
meoutmet hodthatwor
ksby
addingcodetodelaytheexecut
ionunt
ilaspeci
fi
ccondi
tion
ari
ses.Iti
smor ecust
omizablei
ntermsthatwecansetitupto

19
waitforanysuitabl
esituat
ion.Usuall
y,weuseafewofthepr
e-
buil
tExpectedConditi
onst owaitforelement
stobecome
cl
ickable,
visi
ble,i
nvi
sible,
etc.

WebDr i
verdr
iver=newChr omeDr iv
er(
);
dri
ver.
get(
"ht
tp://t
arget_page_url
");
WebElementdy namicElement=( newWebDr i
ver
Wait
(dr
iver
, 15)
)
.unti
l
(Expect
edCondi ti
ons.presenceOf
Element
Locat
ed(
By .
id("
dynami
cEl
ement
")
));

WhatI
sTheCommandToEnterTextI
nThe
HTMLTextBoxUsi
ngSel
eni
um?
Wecandosobyusi ngt hesendKey s(
)met hod.
WebDri
verwebdr i
ver=newFi r
ef oxDriver
();
webdri
ver.
get(
"htt
ps://www. googl e.
com" )
;
webdri
ver.
fi
ndElement(By.xpath("<<xpath
expr
>>")
).
sendKeys("Selenium Intervi
ewQuest i
ons"
);

HowToEnterTextI
nTheHTMLTextBox
Wit
houtI
nvoki
ngTheSendKey
s()
?
Therei
saSel
enium Jav
ascri
ptExecut
orcl
assthatpr
ovi
des
methodst
operf
orm acti
onsontheHTMLel ements.
//Setupt
heJSobject
Javascri
ptExecutorj
s=(Javascri
ptExecut
or)
dri
ver
;
//Issuecommandt oent
erthetext
j
s.execut
eScr i
pt(
"document
.getEl
ement By
Id(
't
ext
box'
).
val
ue='
SomeText
';
")
;

WhatIsTheMethodToReadTheJavaScr
ipt
Var
iabl
eUsingSel
eni
um WebDri
ver
?
Agai
n,wecanut
il
izetheJavascr
ipt
Execut
orcl
asst
oreadt
he
val
ueofaJSvar
iable.Seet
hebelowcode.
//Setupt heJavaScri
ptobject
Javascr
iptExecut
orjscr
ipt=(Javascr
ipt
Executor)webdr
iver
;
//Readthesi t
etit
le
Str
ingstrTit
le=(Str
ing)
jscr
ipt.
execut
eScri
pt(
"ret
urndocument.
ti
tl
e")
;
System.
out .
pri
ntl
n("WebpageTitl
e:"+str
Titl
e);

20
WhatI
sTheCommandToReset/
ClearThe
HTMLTextBoxI
nSel
eni
um Webdri
ver
?
Seleni
um prov
idest
hecl
ear
()f
unct
iont
oresett
hev
aluei
nsi
de
thetextel
ement.
WebDriv
erwebdr i
ver=newFi r
efoxDriv
er()
;
webdr
iver.
get(
"htt
ps:/
/www. google.
com" )
;
webdr
iver.
fi
ndElement(By
.xpath(
"<<xpathexpr
>>"
)).
sendKey
s("
Sel
eni
um I
nter
view
Quest
ions"
);

webdr
iver
.f
indEl
ement
(By
.xpat
h("
<<xpat
hexpr
>>"
)).
clear
();

WhatIsTheCommandToGetTheVal
ueOfA
TextBoxI
nSeleni
um Webdr
iver
?
Sel
eni
um provi
dest
heget
Text
()f
unct
iont
oreadt
hev
alue
i
nsi
dethetextel
ement
.

@Test
publicvoi
dr eadText (
){
System.setProperty("
webdr i
ver.
chrome.dri
ver"
,"<<chromedri
ver
.exe>>"
);
WebDr i
verwebdr i
v er=newChr omeDr i
ver(
);
webdriv
er.get("
https://www. googl
e.com");
St
ringstrText=webdr i
v er
.f
indElement(By.
xpat
h( "
<<xpathexpr
>>"))
.get
Text
();
System.out.pr
int
ln("Textelementcont ai
ns:"+strText);
}
}
;

WhatI
sTheCommandToGetTheAt
tri
but
e
Val
ueI
nSeleni
um Webdr
iver
?
Sel
eni
um pr
ovi
destheget
Att
ribut
e(v
alue)f
unct
iont
oreadt
he
val
uei
nsi
dethetextel
ement
.

St
ringstrValue=
webdriv
er.f
indElement(
By.name("
<<at
trname>>"))
.get
Att
ri
but
e("
val
ue"
);
System.out.
print
ln(
"At
tri
buteval
ueis:
"+st r
Value);

21
WhatIsTheCommandToCl
i
ckOnAHy
per
li
nk
I
nSeleni
um Webdr
iver
?
Sel
eni
um providesthecl
ick()f
uncti
ont
ocli
ckonaHTMLli
nk.
webdr
iver.
fi
ndElement(
By .
li
nkText
("
Sel
eni
um I
nter
view
Quest
ions"
)).
cli
ck()
;

WhatI
sTheCommandToSubmi
tTheHTML
For
mInSel
eni
um Webdr
iver
?
Sel
eni
um provi
dest
hesubmit
()funct
iont
ofi
nalizeaHTML
for
m.
webdr
iver
.f
indEl
ement
(By
.i
d("
<<htmlf
orm>>"
)).
submit
();

Howev er
,wecanal
soachi
evet
hesameef
fectbycal
l
ingt
he
cl
ick(
)met hod.

WhatI
sTheCommandToPr essEnt
erInsi
de
TheHTMLTextBoxUsi
ngSeleni
um Webdri
ver
?
Sel
enium pr
ovi
desEnum Keymacrostosimulat
etheenter
act
ion.
webdriv
er.
fi
ndEl
ement(
By.xpat
h("
<<xpat
h>>"
)).
sendKey
s(Keys.
E
NTER);

WhatIsTheSeleni
um CommandToDel
ayTest
Execut
ionFor10Seconds?

22
I
nJav a,
wecanuset hefoll
owingmet hodtohal
ttheexecut
ion
foraspeci fi
edno.ofmi l
liseconds.
j
av a.
lang.Thread.sl
eep(l
ongmi ll
iseconds)
Tohal tfor10seconds, wecani ssuet hef
oll
owi
ngcommand:
Thread.sleep(10000)

I
sItMandat
oryToPref
ixTheURLWit
hHTTPOr
HTTPSWhil
eCall
ingTheWebDri
ver
’sGet
()
Method?
Yes,ift
heURLdoesn’tcontai
ntheHTTPprefi
x,t
hent
he
program wil
lthr
owanexcepti
on.
Hence,iti
smandator
yt opasstheHTTPorHTTPSprotocol
whilecall
i
ngthewebdriver
’sget(
)method.

WhatIsTheOtherMet
hodWhichGi
vesThe
SameEffectAsWeGetFr
om TheWebDriv
er’
s
Get
()?

Sel
eni
um pr
ovi
dest
he“nav
igat
e.to(
li
nk)
”method.I
tdoest
he
samethi
ngasweachi
evefr
om theget(
)cal
l
.

WhatIsThePri
nci
palDi
ff
erenceBet
ween“
GET”
And“NAVIGATE”Met
hods?
Getmet hodmakesapagetol
oadorext
ractsi
tssourceor
parsetheful
ltext
.Ont
hecont
rar
y,t
henavigat
emethodt r
acks
thehist
oryandcanper
for
m oper
ati
onsl
ikeref
resh,
back,and

23
f
orwar
d.

Forexample–Wel iketomov eforward,executesome


funct
ional
i
tyandt henmov ebackt othehomepage.
Wecanachi evethisbycall
ingtheSelenium’snav i
gate(
)API.
▪ Thedr iver.
get()methodwaitsuntilthepagefini
shloadi
ng.
▪ Thedr iver.
navigat
e()wil
lonlyredir
ectandr etur
n
immediatel
y.

HowCanIMoveBackAndFor
thI
nABr
owser
Usi
ngSel
eni
um?
Seleni
um prov idest hefol
lowi
ngmethodsformov i
ngbackand
for
thinabr owser .
1)nav i
gat
e().forwar d(
)–t omovetothenextwebpageasper
thebrowser’shi story
2)nav i
gat
e().back( )–t omovebacktotheprev
iouspageasper
thebrowser’shi story
3)nav i
gat
e().refresh()–torel
oadthecurr
entpage
4)nav i
gat
e().to(“URL”)–t ost
artanewbrowserwindowand
openingupt hespeci f
iedl
ink

WhatIsTheSel
eni
um CommandToFet
chThe
Cur
rentPageURL?
Toret
ri
ev ethecurr
entpageURL,
wecancal
lthe
get
CurrentURL(
)functi
on.
webdr
iver.
getCurr
entUrl
()
;

WhatI
sTheSel
eni
um CommandToSet
TheBr
owserMaxi
mized?
Wecanmaxi
mizet
hebr
owserwi
ndowbycal
l
ingSel
eni
um’
s

24
maximize(
)method.
I
tsetsthecur
rentwindowint
hemaximizedst
ate.
dr
iver
.manage()
.wi
ndow().
maximi
ze(
);

WhatIsTheSel
eni
um CommandToDel
ete
Sessi
onCooki
es?
Todelet
esessi
oncooki
es,wecani
nvoket
hedel
eteAl
l
Cooki
es(
)
method.
webdri
ver.
manage(
).
del
eteAl
l
Cooki
es(
);
St
ateTheDiffer
enceBetweenWeb
Dri
ver
’sGetWindowHandle(
)
AndGetWindowHandles(
)Methods?

webdri
ver.
get
WindowHandl
e()–Itgetsthehandleoftheact
ive
webpage.
webdri
ver.
get
WindowHandl
es()–Itgetsthel
istofhandlesf
or
al
lthepagesopenedatati
me.

PART–3:

St
ateTheDi
ff
erenceBetweenWebDr
iver
’s
Cl
ose(
)AndQuit(
)Methods?

25
Theset womet hodsper formt hesamet ask, i.
e., t
hecl osingof
thebr owser .Howev er,t hereisasl ightdiff
erence.
webdr iv er
.close( ):Itclosest heact iveWebDr iverinst ance.
webdr iv er
.qui t
(): I
tcl osesal lt
heWebDr i
verinst ancesopenedat
at i
me.
Statet hedi f
ferencebet weenWebdr i
ver’
sfindEl ement (
)and
fi
ndEl ement s()met hods?
Botht hesemet hodst rav ersetheDOM l ookingf ort het arget
webel ement .Howev er, therear esomebasi cdi fferences
betweent hem.
1.Thef i
ndEl ement ()met hodr eturnst hefi
rstWebEl ement
mat chi ngt helocat or,wher east hefindElement s( )fet chesal l
passingt hel ocat orcr i
t eria.
//Sy nt axoff i
ndEl ement ()
-
WebEl ementi tem =webdr i
ver.
f i
ndElement (
By .id("<<I D
value>>" ));
//Sy nt axoff i
ndEl ement s()-
List<WebEl ement >i t
ems=webdr iver.
fi
ndElement s( By.
id("<<I
D
value>>" ));
2.Anot herdi ff
er encei si fnoel ementi smat ched, thent he
fi
ndEl ement ()raisesNoSuchEl ement Exceptionwher eas
fi
ndEl ement s()r eturnsanempt yl
ist.
HowDoYouCheckI
fAnObj
ectI
sPr
esentOn
Mul
ti
plePages?
Wecanuset heisEl
ementPr
esent
()commandtover
if
ythe
objectonal
lpages.
assertTr
ue(
sel
enium.i
sEl
ementPr
esent
(l
ocat
or)
);
HowDoYouCheckForThePr esenceOfAWeb
El
ementAf
terTheSuccessf
ulPageLoad?
Wecanv eri
fythepresenceofawebel ementwit
ht hef oll
owing
code.
Whileusi
ngthebelowf uncti
on,dosupplysometimeoutv alue
(i
nseconds)tocheckt heel
ementi naregul
ari
nterval.
publi
cvoi
dcheckIfElementPresent
(St
ri
ngelement,inttimeout)
thr
owsException{

26
f
or( i
ntsec=0; ;sec++){
i
f(sec>=t i
meout )
fai
l(
"Timeout!Couldn'
tlocateel
ement.
"+el
ement
);
tr
y{
i
f(seleni
um. i
sElementPresent
(el
ement)
)
break;
}catch(Exceptionex){
}
Thread.sl
eep(1000);
}
}
HowToHandl
eWeb-
BasedAl
ert
s/Pop-
UpsI
n
Sel
eni
um?
WebDr
iverexposest hef ol
lowingAPIst ohandlesuchpopups.
▪ Di smiss():Ithandlesthealertbysimulati
ngtheCancel
button.
▪ Accept ()
:I thandlesthealertwindowbysi mulat
ingthe
Okaybut ton.
▪ Get Text():Youmaycal li
ttofindoutthetextshownbyt he
al
ert.
▪ SendKey s():Thi
smet hodsi mulateskeystr
okesinthealer
t
window.
HowToHandl
eWi
ndows-
BasedAl
ert
s/Pop-
Ups
I
nSel
eni
um?
Handli
ngawi ndow-basedpop- upi snotstrai
ght-f
orward.
Sel
enium onl ysupportswebappl icati
onsanddoesn’ tprovi
dea
waytoaut omat eWi ndows-basedappl i
cati
ons.Howev er,t
he
fol
l
owi ngappr oachescanhel p.
1Uset heRobotcl ass(Java-based)ut i
l
ityt
osimul at
ethe
keyboar dandmouseact ions.That’showy oucanhandl e
thewi ndowbasedpop.
2TheKey Pr essandKey Releasemet hodssi mulat
etheuser
pressingandr eleasi
ngaspeci f
ickeyont hekeyboard.
HowToHandl
eMul
ti
plePopupWi
ndowsI
n
Sel
eni
um?

27
Selenium pr ovidest heget Wi ndowHandl es()met hod,which
ret
ur nsthehandl esf orallopenpopups.
Wecanst orethem i ntoa<St ri
ng>v ari
ableandconv er
titinto
anar ray.
Afterthat, wecant raverset hear rayandnav igatetoaspecific
windowbyusi ngt hebel owcode.
dri
v er.
switchTo( )
.window( Ar r
ayIndex) ;
Alt
er nati
vely,wecanuset heJav aI teratorclasst oi
ter
ate
thr
ought hel i
stofhandl es.Findbel owist hecodet ohandl e
mul ti
plewi ndowsusi ngSel enium.
Str
inghMy Window=dr i
v er.
get WindowHandl e();
WebDr i
verpopup=nul l
;
I
terator<St r
ing>hWi ndows=dr i
v er.getWindowHandl es()
;
while(hWi ndows. hasNext ()){
StringhWi ndow=hWi ndows. next (
);
popup=dr iver.switchTo( )
.window( hWindow) ;
if(popup. getTitle()
.equals("Handl ingMul t
ipl
eWi ndows"){
break;
}
}
HowCanYouAccessADat
abaseFr
om
Sel
eni
um?
Selenium doesn’thav eadi rectAPIt oaccessadat abase.
Hence, wecanl ookf oritssuppor tint hepr ogr
ammi ng
l
anguagewechooset owor kwithSel enium.
Forill
ustrati
onpur poses, weusedJav awi t
hSel enium.
Javapr ov i
destheConnect i
oncl asst oinit
iateaconnect i
on
withthedat abase.Ithasaget Connect i
on()met hodt hatwe
needt ocal l
.Forthis,we’l
l makeaConnect ionObj ect.I
t’
ll
managet heconnect i
ont ot hedat abase.
Pleasenot e:Anappl icati
oncoul dhav eoneormor e
connect i
onsopenedt oadat abaseordi fferentdatabases.
Herei sashor tovervi
ewoft hest epst obeper formed.
▪ Fi r
stly,weestablishaconnect ionwi ththedat abase.
▪ Af terthat,
wecal lt
he
Dri
v erManager .
getConnect ion( )method.

28
▪ Thismethodacceptsast r
ingpointi
ngtothedatabase
URL.
▪ TheDr i
ver
Managercl asst
henattemptstofindadrivert
o
accessthedatabaseURL.
▪ Af teri
tfi
ndsasuitabledri
ver,
thecallt
othe
getConnect
ion()methodsucceeds.
Sy
ntax:
St
ri
ngurl="j
dbc:odbc:makeConnection";

Connect
ioncon=Dr
iver
Manager
.get
Connect
ion(
url
,"user
ID"
,
"
password")
;
HowToHandl
eAJAXCont
rol
sUsi
ngSel
eni
um?
Let’
sunder standthehandli
ngofAJAXwi thanexample.
ConsidertheGoogl esear
cht extbox,whichisanAjax
contr
ol.Whenev erwewri
tesomet exti
ntothebox,i
tshowsup
ali
stofaut o-suggestedv
alues.
Toaut omat ethisty
peofelement,weneedt ograbt
heabove
l
isti
nast r
ingassoonast heboxr eceivesinput
.Aft
erthat
,we
canspl i
tandt aketheval
uesonebyone.
HowToWor
kWi
thAJAXCont
rol
sInWebDr
iver
?
AJAXi sanacr onymf orAsynchronousJavaScr
iptandXML.It
i
si ndependentoft heopeni
ngandcl osi
ngtagsrequir
edfor
creati
ngv ali
dXML.
Somet i
mes, theWebDr i
verit
selfmanagestowor kwitht
heAjax
control
sandact i
ons.However,ifi
tdoesn’
tsucceed,t
hentr
y
outthebel owcode.
//Waiti
ngf orAjaxControl

WebElementAj axCtr
l=(newWebDr i
verWait
(dr
iver
,
10))
.unt
il
(ExpectedCondit
ions.
presenceOfEl
ementLocat
ed(
By.
&lt
;l
ocat
orType&gt ;
("
&lt
;l
ocatorValue&gt
;"
)))
;
WhatI
sAPageObj
ectI
nSel
eni
um WebDr
iver
?
Fir
stofal
l,boththesetermsbelongtothePageObj
ectModel
(POM),adesignpat t
erninSel
enium.Let’
snowseehoware
theydi
ff
erentfrom eachother
.
PageObjectisacl assinPOM corr
espondingt
oawebpage.I
t

29
capt
uresthefunctional
i
tyasfunct
ionsandobj
ect
sas
member s.
publ
icclassLogInPage
{
pr
ivat
eWebEl ementuser;
pr
ivat
eWebEl ementpass;

publ
i
cLogI
nPage(
){
}

publi
cvoi
dfindObj
ects(
){
user=br
owser.f
indEl
ement
(By.
i
d("
userName")
);
pass=browser.
fi
ndEl
ement(
By.
id(
"passwor
d")
);
}

publi
cvoidprocessLogIn(){
user.
sendKeys("
john")
;
pass.
sendKeys("password")
;
}
}
WhatI
sAPageFact
oryI
nSel
eni
um WebDr
iver
?
PageFact oryisamet hodt
osetupt
hewebel
ement
swi
thi
n
thepageobj ect.
publ
icclassLogI nPage
{
@FindBy (
id="user
Name")
pr
ivat
eWebEl ementuser
;

@FindBy
(id="
passwor
d")
pr
ivat
eWebElementpass;

publi
cLogInPage(){
PageFactory
.i
nit
Element
s(br
owser
,thi
s);
//Set
upt
he
membersasbr owser.
fi
ndEl
ement()
}

30
publi
cvoidprocessLogIn(){
user.
sendKeys("
john")
;
pass.
sendKeys("password")
;
}
}
WhatAreUserExt
ensi
ons,
AndHowDoYou
Cr
eateThem?
Userextensionsareasetoff unct
ionswrit
teninJav aScr
ipt.
Theyarepr esentinaseparat
eknownast heextensionfi
le.
Sel
enium IDEorSel eni
um RCaccessi tt
oact i
vatethe
ext
ensions.
Sel
enium’scor ehasaJav aScri
ptcodebase.So,wecanal so
useittocreatetheextensi
on.
Theextensionhasaspeci fi
cformat,asgivenbelow.
//sample
Sel
enium.pr ot
otype.
doFuncti
onName=f uncti
on(){

}
Thefunct
ionnamebeginswitha“do”prefi
x.I
tsi
gnal
s
Sel
enium t
oint
erpr
etthi
sfuncti
onasacommand.
I
tmeanswecancal lt
heabov efunct
ioninsi
deanyofourst
eps.
WhatIsTheRi
ghtWayToCapt
ureAScr
eenshot
I
nSeleni
um?
Somet i
mes, animagethanat r
acel ogcanhel
pusident
if
ythe
ri
ghtreasonf oranerr
or.Thecodei nthebel
owexamplewil
l
captur
et heimageandst oreitinaf il
e.
Importorg.apache.
commons. i
o.Fi
leUtil
s;
WebDr i
verins=newChr omeDr i
ver();
i
ns.get(
"htt
p://www.google.com/ "
);

Fil
escreen=
((
TakesScreenshot
)i
ns)
.getScr
eenshot
As(Out
putType.FI
LE);
//Nowy oucandowhat everyouneedtodowithit
,forexample
copysomewher e

31
Fi
l
eUt
il
s.copy
Fil
e(scr
een,
newFi
l
e("
c:\
tmp\
myscr
een.
png"
));
HowToSimul
ateMouseOverActi
onOnA
SubmenuOpt
ionUnderAHeaderMenu?
Usingt heAct ionsobject ,y
oucanf ir
stmov ethemenut i
tl
e,and
thenpr oceedt ot hepopupmenui tem andclicki
t.Don’
tatall
misst oi nvoket he“acti
ons. Perfor
m( )”att
heend.Checkout
thebel owJav acode:
Actionsact s=newAct ions(driv
er);
WebEl ementmenuHov erLink=
dri
ver .
findElement (
By .
li
nkText ("
Menuheadi ng"))
;
acts.mov eToElement(menuHov er
Link);
WebEl ementsubLi nk=
dri
ver .
findElement (
By .
cssSel ector
("#headerMenu.subLi
nk")
);
acts.mov eToElement(subLi nk);
acts.cl
ick( )
;
acts.perform();
HowToResol
veTheSSLCerti
fi
cat
eIssue
(
Secur
edConnect
ionEr
ror
)InFi
ref
oxWi t
h
WebDr
iver
?
Therecanbemanyr easonsf ort hesecur edconnectionerr
or.It
coul
dbebecauseoft hef oll
owi ng:
▪ Whi leasi t
eisgettingdev eloped, i
tmaynothav etheri
ght
SSLcer ti
fi
cate.
▪ Thesi temaybeusi ngasel f-
signedcer t
if
icat
e.
▪ TheSSLmaynothav econf i
gur edappr opriat
elyatthe
serverend.
Howev er
,youst i
llwanttotestt hesi te’sstandardfuncti
onali
ty
usi
ngSeleni um.Then,theideai st oswi t
chofftheSSLset ti
ng
andignoretheSSLer ror.
Checkoutt hebelowcodet odisabl et heSSLi nSelenium.
Fi
refoxPr
of i
lessl=newFi refoxPr ofi
le( )
;

ssl
.set
Accept
Unt
rust
edCer
ti
fi
cat
es(
true)
;

ssl
.set
AssumeUnt
rust
edCer
ti
fi
cat
eIssuer
(fal
se)
;

32
WebDr
iveri
ns=newFi
ref
oxDr
iver
(ssl
);
HowToResol
veTheSSLCer
ti
fi
cat
eIssueI
nIE?
Intheinter
netexpl
orer
,iti
ssomewhatt r
ivi
alt
oignor
etheSSL
err
or.Pleaseaddthebelowlineofcodeandsafel
yski
ptheSSL
i
ssue.
//Copyt hebel
owcodeaf teropeni
ngthebrowser
.

dr
iver
.navi
gat
e().
to(
"j
avascr
ipt
:document
.get
Element
ByI
d('
over
r
i
deli
nk')
.cl
i
ck(
)")
;
HowToHandl
eAPr
oxyUsi
ngSel
eni
um I
nJav
a?
Sel
enium i
mplementsaPROXYclasstoconf
igur
ethepr
oxy
.
Seebelowexample:
Str
ingset
PROXY=" 10.
0.0.
10:
8080";

org.
openqa. sel
enium. Proxyal l
owPr oxy=
new.org.openqa. selenium.Pr oxy()
;
al
lowPr oxy.setHTTPPr oxy(setPROXY)
.
set FtpProxy(setPROXY)
.
set SslProxy(setPROXY) ;
Desi
redCapabi li
ti
esal l
owCap=newDesi redCapabi
li
ti
es(
);
al
lowCap. set Capabili
ty(Capabi l
i
tyType.PROXY,all
owProxy)
;
WebDriv erdr i
ver=newFi refoxDriver(
all
owCap);
HowToHandl
eAPr
oxyUsi
ngSel
eni
um I
n
Pyt
hon?
f
rom sel
eni
um i
mpor
twebdr
iver

PROXY="
10.
0.0.
10:
8080"#I
P:PORTorHOST:
PORT

chr
ome_
opt=webdri
ver
.ChromeOpti
ons()
chr
ome_
opt.
add_
argument(
'-
-pr
oxy-
serv
er=%s'
%PROXY)

chr
ome=webdr
iver.
Chrome(opti
ons=chr
ome_
opt
)
chr
ome.
get
("
<<t
ar getURL>>")
WhatAr
eTest
NGAnnot
ati
onsFr
equent
lyUsed

33
Wi
thSel
eni
um?
TestNGannot at ionspr iori
tizethecall
ingofat estmet hodov er
other
s.Her ear et heonest ousewi thSel eni
um:
▪ @Bef oreSui te–t or unbef orealltests.
▪ @Af terSuite–t or unonl yonceafteralltests.
▪ @Bef oreCl ass–t or unonl yoncebef orethef i
rsttest
met hod.
▪ @Af terClass–t or unonl yonceaf terallt
het estmet hods
ofthecur rentcl assf inishexecuti
on.
▪ @Bef oreTest–t or unbef oreanyt estmet hodinsidethe
“Test”tag.
▪ @Af terTest–t or unaf teranytestmet hodi nsi
det he“Test”
tag.
WhatDoYouKnowAboutTest
NG@Par
amet
ers?
I
nTest NG,the“
@Parameters”isakeywordt
hatal
lowsthe
argumentstopassto“@Test”methods.
Pleaseref
ertothi
sTestNGtutori
alt
olearnmoreabout
parameter
s.
WhatI
sDat
aPr
ovi
derI
nTest
NG?
Thedat
aprovi
deri
saTestNGannot
ati
on.Ital
lowsyoutopass
par
ameter
sli
keaproper
tyfi
l
eoradatabasetoatestmethod.
WhatI
sMeantByGr
oupi
ngI
nTest
NG?
I
tisaninnovati
veTestNGfeatur
ethatdidn’
texisti
ntheJUnit
.
Youcanassignmethodswi t
hpropercontextandrefi
ne
groupi
ngsoftestmethods.
Youcannotonlyli
nkmet hodstogroupsbutalsotel
lgroupst
o
i
ncludeothergr
oups.
HowToAssociat
eASi
ngl
eTestToMul
ti
ple
GroupsI
nTest
NG?
TestNGframeworkall
owsmul t
ipl
etest
st or
unbyusingthe
testgr
oupfeat
ure.
Wecanassociateasingl
etesttomulti
plegr
oups,
asshowni n
thebel
owexampl e.
@Test(gr
oups={ "
regr
essi
on-t
esti
ng","
smoke-t
est
ing"}
)
I
sTest
NGCapabl
eOfRunni
ngMul
ti
pleSui
tes?
34
Yes,wecanr unmul ti
pletestNGsuit
esinthef
oll
owi
ngmanner
:
<suit
ename=" SuperSuit
e">
<suit
e-fi
l
es>
<suit
e-fi
lepath="subSuite1.xml
"/>
<suit
e-fi
lepath="subSuite2.xml
"/>
..
.
</suit
e-f
iles>
</suit
e>
Wecanal sorunv ari
oussui t
esinparal
l
elbyusi
nganAntt
ask.
Sel
eni
um Inter
viewQuest
ions[
Gener
al
Quest
ions]
WhatI
sAFramework?WhatAreTheDi
ff
erent
Ty
pesOfFr
ameworksAvai
labl
e?
Af r
amewor kisachar t
erofrul
esandbestpracti
cestosol
vea
problem systematical
ly.Ther
earevar
ioust
y pesofautomat
ion
fr
amewor ks.
Someoft hemostcommononesar easfol
lows:
▪ Dat a-Dri
venTestingFramework
▪ Key wor dDri
venTest i
ngFramework
▪ Hy bridTesti
ngFr amework
▪ Behav i
oural
Dr i
venFramework
WhatAreTheOpen-SourceFr
amewor
ks(
OSF)
DoesSel
enium Suppor
t?
Seleni
um canint
egr
atewi
tht
hef
oll
owi
ngOpenSour
ce
fr
amewor ks.
▪ JUni t
▪ Test NG
▪ Mav en
▪ Fi t
Nesse
▪ Xebi um
WhatIsThePrinci
pal
Dif
fer
enceBet
weenA
Dat
a-Dri
venFramework&AKeywordDri
ven
Fr
amewor k?
Dat
a-dr
ivenf
ramewor
k(DDF)

35
▪ InaDat a-driv
enf ramewor k,thetestcasel ogi
ci sthepar t
oft estscr i
pts.
▪ I tadv i
seskeepi ngt hei nputdat asepar ate.
▪ Usual l
y,t hetestcasesr ecei vethedat af r
om t heexter nal
fil
es( XLSorCSV)andst or ethem intov ariabl
es.Lat er
dur i
ngexecut ion, thev ariablesser v
easi nputaswel las
verifi
cationpoi nt s.
Key
wor d-dri
venf ramewor k( KDF)
▪ I nKDF, t herehappenst obeat ableofkey words.Ev ery
key wordei thermapst oanact i
onoranobj ect.
▪ Theact ionsr ef lectt hepr oductf uncti
onal it
y,andthe
objectsr epresenti tsr esour cessuchaswebel ement s,
commandort heDBURL, etc.
▪ Theyr emai ndet achedf rom t hetestaut omat ionsuite.
Hence, thecr eat ionoft het estscancont inuewi t
hor
withoutt heAUT( appl i
cat ionundert est )
.
▪ Thekey wor d-dr i
v ent est scov erthefull f
unct i
onali
tyoft he
appl i
cationundert est .
WhatIsTheDi
ffer
enceBet
weenHy
bri
dAnd
Dat
a-Dri
venFr
amework?
Ahybri
dframewor kisacombinationofbothdata-
dri
venand
key
word-dri
venSelenium f
ramewor ks.
Adata-
driv
enframewor kworksont heconceptofseparat
ing
dat
afrom thetest
s.Itsol
elydependsonthet esti
nputdat
a.
WhatAr
eTheTwoMostCommonPr
act
icesFor
Aut
omati
onTest
ing?
Thetwomostf r
equent
lyusedpract
icesforaut
omat i
onareas
fol
l
ows:
▪ Test -Dri
venDevel
opment(TDD)intr
oducedin2003
▪ Behav i
orDri
venDevel
opment(BDD)gotf i
rstheardi
n
2009
WhatI
sTest-
Dri
venDev
elopment(
TDD)
Fr
amework?
TDDa.
k.a.test
-dri
vendesi
gnisasof t
waredevel
opment
par
adi
gm thatproposestoconductunitt
est
ingf
requent
lyon

36
thesour cecode.Itrecommendst owr i
tetests,monit
or,and
ref
actort hecodeonf ail
ure.
TheconceptofTDDcamet olightwhileaf ewXP( Extr
eme
Programmi ng)dev el
opersconceivedi t
.
I
tintendst oprepareteststochecki fthecodebr eaksornot.
Aftereacht estcasefail
ure,t
hedev elopershouldfixandre-
run
thetestt overi
fythesame.Thi sprocessshoul drepeatunti
lal
l
unitsfuncti
onaspert hedesi
gn.
WhatI
sBehavi
orDr
ivenDev
elopment(
BDD)
Fr
amework?
BDDf oll
owsmostoft hepr
inciplesofTDDbutr eplacesitsuni
t-
centri
capproachwi t
hadomai n-centri
cdesign.
Iti
ntendstobr i
ngi ninput
snotonl yfrom theDevorQAbutan
arr
ayofst akeholderssuchasPr oductOwner s,Technical
Support,Manager s,andCustomer s.
Thegoal i
st oidentif
yandaut omat eappropri
ateteststhat
ref
lectthebehav i
orsoughtbyt hepr i
ncipalst
akeholders.
WhatAr
eTheMai
nTrait
sOfASof
twar
eTest
Aut
omati
onFr
amework?
Atestaut omat i
onframewor kshouldhav ethefol
lowi
ng
f
eatures.
▪ Fl exiblei nthepr ogr ammi nglanguageselecti
on
▪ Suppor tofkey wor dsandact ions
▪ Pr ov i
sionofdat asour cesforinput
▪ Al lowt estcasecr eat i
onandmodi fi
cation
▪ Def i
net estcasepr iority
▪ Manual orautomat edexecution
▪ Mai ntaint estresultshi st
ory
▪ Gener at etestmet ricssuchast estvs.codecover
age
▪ Repor tcr eati
on
▪ CIt oolintegrationsuchasJenki ns
▪ Cr oss- browserandcr oss-pl
atform support
WhatTypeOfTestFr
amewor
kDi
dYouCr
eat
e
Usi
ngSeleni
um?
Whi
l
erepl
yi
ngt
osuchquest
ions,
stayf
ocused,
andkeepy
our

37
answershor tandcr isp.Youcanst ar tbyt elli
ngaboutt he
di
ffer
entcomponent si ny ourf r
amewor kandt henexplai nthem
onebyone.
Hereisani l
lust rat ionf oryourhel p.
▪ Iwor kedonaf ramewor kbui ltont opoft hePageFact ory
framewor k.
▪ I ’
v ecr eat edapagecl assf orev erywebpagei nmy
appl icat ion.I tkeepst heobj ectsandt hehandl erfunct ions.
▪ Ev erypagecl asshasaf ollowupt estcl asswher eIcr eate
test sf orr el atedusecases.
▪ Iusedsepar atepackagest ohostt hepagesandt hei rtest
classes.I t’sabestpr act icet odot hatway .
▪ Thef r
amewor kal sohadal i
bpackagef orut i
li
tyandsome
standar dwr apperf unct ionsov erSel enium API s.
▪ Jav ai scaor epr ogrammi ngl anguageusedf orthispr oject.
Itwaspr i
mar il
ybecauset het eam hadpr ev i
ousJav a
exper ience.Al so, wecoul dut il
i
zet heTest NGannot ati
ons
andr epor tf eat ur es.
▪ Mostt estcasesar edat a- dri
v en.Theyr equi reinputf r
om
theext ernal dat asour ce.So, IusedJav apr operty
/ POI
classt or eadf rom t heCSV/ XLSf i
les.
▪ Weusedt heTest NGgr oupf eat uref orlabel ingtestcases
asP1, P2, andP3.
▪ TheLog4Jl ibr arypr ov i
dedt henecessar ysuppor tfor
traci ngi nourpr oject.
▪ I nst eadofusi ngt heTest NGr epor t
ing, wepr efer
redt he
Ext entr epor t.Ithasmor egr aphi cal optionsandgi vesan
i
n- dept hanal ysi soft her esults.
▪ Webui l
tt hef ramewor kwi tht hehel pofMav en.Also,
Jenki nspr ov idedsuppor tforaut omat edbui l
dand
execut ion.
▪ Bi tbucketal lowedust omanageoursour cecodeusi nggi t
reposi tories.
WhatAreChal
l
engesHaveYouFacedWit
h
Sel
eni
um?AndHowDi dYouOvercomeThem?
Her
ear
esomeoft
hepr
obl
emst
hatt
est
ersusual
l
yfacewhi
l
e

38
doi
ngaut omat ionwi thSel enium.
▪ Wr ongi mpl ement ation:Iusedt hepageobj ectmodelbut
hadi timpl ement edi ncor r
ect l
y .Mycl asseswer e
focussi ngont hewebel ement sr at hert hant heyshoul d
hav eresembl edt heuseract ions.
▪ Dupl i
cat ecode:Thepr ojecthadmanycat egor ypages.
Eachcat egor yhadadi fferentsear chf unct i
oni nsteadof
handl i
ngt hem atacent ralplace.
▪ I neffect iveuseofwai t:Iusedi mpl icitwai twi thaf i
xed
timeout .Butsomepageswer et imi ngoutduet ohi gher
l
oadt i
me.Ihadt oadoptt heFl uentwai t( withav ari
abl e
timeout )toov ercomet hispr obl em.
▪ I mpr operer rorhandl ing:Itwasget tinghar dt odebugt he
causeofaf ailedt est.Atsomepl aces, the{ try -
cat ch}
blockswer emi ssing, andhence, caseswer eski ppingw/ o
givi
ngapr operr eason.Ther efore, Ihadt or ef act orthe
codebyaddi ngasser t
sandexcept ionhandl ing.
▪ I nconsi st entXPat h: Mostoft hel ocat orswer eusi ngt he
XPat hmet hod.Andt hedev eloper skeptt hem changed
whilef ixingnewdef ects.Ical ledupadi scussi onwi th
them andagr eedt ohav eaf i
xedXPat horanI Df orthe
webel ement s.
▪ Per for mance&Local i
zat i
on:Wewer eusi ngt hef l
atfiles
(CSV)i ni ti
al l
yt of eeddat at ot estcases.Howev er,i
thad
usf ail
edi nt est inglocal izati
onaswel lasbeat enusont he
performance.Eemi gr atedal l ofourt estdat at oMy SQL
andf ixedbot hi ssues.
▪ Monol i
t hict est s:Ear li
ert estswer en’ tusingt hel abeli
ng.
Honest ly,ther ewasn’ tawayt odoi t.Hence, wei ntegrated
ourt estsui tewi thTest NGandgotawaywi tht his
l
imi t
at i
on.Now, wehav emanyt estgr oupsl ikef eatures-
based( F1, F2, F3…) ,pr i
or i
ty-
based( P1, P2, P3) .
WhatBenef
it
sDoesTest
NGHav
eOv
erThe
JUni
tFramewor
k?
Test
NGv s.JUnit–TheBenefit
s
1InJUni
t,westartbydecl
ari
ngthe@Bef
oreCl
assand

39
@Af t
erClass.Howev er,therei
sn’tsuchaconst r
aintin
TestNG.
2TestNGal l
owsaddi ngset Up/tear
Downr out i
nes,whichJUni t
doesn’t
.
3-@BeforeSuite&Af terSuite,@BeforeTest&Af t
erTest,
@Bef or
eGr oup&Af t
erGroup
4TestNGdoesn’ tenfor ceacl asstoext end.
5Methodnamesar en’tmandat oryinTest NG, whichar einJUnit
.
6Wecanmakeacasedependonanot heri nTest NG, whereas
i
nJUni t,
it’
snotpossi ble.
7TestNGal l
owsgr oupi ngoft ests,
wher easJUni t
doesn’t
.Execut i
ngagr oupwi l
l r
unal ltestsunderi t
.For
example,ifwehav eano.ofcasesdi stri
butedi ntwo
groups,namel ytheSani t
yandRegr essi on.Ift
he
requi
rementi stor unt he“Sanity”test s,thenwecan
confi
gureTest NGt oexecut ethetest sundert he“ Sanit
y”
group.Test NGwi llexecuteallcasesassoci atedwi ththe
“Sani
ty”group.
Theparall
eli
zationoft estcasesi sanot hercr ucialfeatur
eof
Test
NG.

40

You might also like