0 ratings0% found this document useful (0 votes) 287 views17 pagesSelenium TestNG Basics
interview questions for selenium test ng
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content,
claim it here.
Available Formats
Download as PDF or read online on Scribd
,LULLLLLLLCEE
a 7
VVVLULLLLUL
GULL
automation testing framework In which AIG
Generation.
Inspired by Junit wen uses annotations. Test NG
Overcome tne divadvantages of Junit and js designed to
make EXE Festno easy.
Generate the yeport In proper format Including tne no. of
test cases yun, pass, Falled and skipped -
Molhple test cases can be grouped easly «
lle can assign priority fo test cases.
Same test cases can be executed multiple time without
loops using keyword -“Invecatton count".
You can execure multlple tect cases on the multiple browser.
Annotations uced are very easy +O under NO
Testn4 stmpitFles tne way fests aye eoded- There is no need
For static maln method- Sequence 1s yeguiared by annotations
thar do no require method +o be statte.
> Uncaugnt exceptions axe handled baie
The annotated method willl yun before all tests fn this
suite have yun.
©: [@ Aprer tutte]
DP tneannotated method Will run After all fests In chis
tuft have yun,
ATLL KUMAR (LINKED IM).WUVUVULULULLLULUUUUUUUU CU ee ceeded
(D- [@Berore Test
The annorared mernod willl Yan before any test method
belonging 40 clacces Inside they 4ag fe run
@.- (@Arverfest
the annotated method pail) yun after all posk method
belonging 40 clasces fnside the fag fs run.
The annotated mernod willl ran before tne Flyst fost method
fn current class fs Invoked.
O- [Batter clazz]
9 The annotated method oil yun affer all +ne pest method jn
Current class Js JnuoKed-
(OD. (ae kero ryeme |
"PF The annototed metnod yofll yun before each test metnod-
© (eater ries]
=P The annotated method pill yun after each test method-
©. (Ore)
wy the annotared method Ps @ part oF fest Case.
(8 [DeehoeG roti] @ Pererroopt
Aerer op This method is gurantad ¢4o yun shorty after the last
test method belong 40 any oF «peciFied gyoup Is Invoked.
°
Before {his method 7s guranteed to yun Shoxty hepore the first
tect method beteng fo ANY oF cpecifted group is
[avoked.
1 KOMAR _CLINKEDIN):AOU UU eee eee er eeece
[fes¢NG Annotattons |]
Sign ON [Reaisrer | Supporr | contact
Flow s-
Go 0 Homepage and Varify HHe.
Click Register and Voslfy fre.
Go back yo Homepage and varlfy +rie-
click Suppor and varity He.
Ge batk po homepage and vasty HHe.
Import 07g. openga selenium. X ;
Import org. pestng. assert;
Import o1g. testny . annorations Ks
Peblic class Test {
Pubric SHIN baseurl =“ hetp ri) demo. test, com";
String driverpath = PATH | 9@cKodriver. exe ;
Public lebDyiver driver ,
PUdilC Stving expewed = null
Poblle Sing actual = null »
@ Cerrerest
Poblic Wold launch Browser¢ ) {
Boas ("Launching Firefox browser") »
System. seeProperty (" weddriver. gecko drives”,
dyiverpath))
driver = new Firefox Driver);
driver. get (baseurl);
o
@ BeroremMethod
Pobuc Noid Verify Yornenriel) £
String expeured Title = “Wreleome : Home”;
String aqua) Title = drluen. getrste ()!
Assert assert lyuals (quusiTite, expected He) >
ei
LTULKOMAR CHINKEDIN)UULULULUUU UU deed ddddedd
vo
vv
WOVE
@ rest ( priority =0)
Pobre Utd yegnrerd) L
arver. pinderemow (Ry.Jd( “yegister") J. cure 0!
expected = "\rjelwme: Register" '
actual = dyer. get Fitle() }
Assert. accert Equal (actuar, expected ds
ect CPriortty = 1)
pusi vold Sopport C) £
dower, Find Element (By 9d C“ceppoxt py) Click (95
expetted = “ilelcome 2 support uy
Actual = fylver. guTitie Goes,
Assert. assert equals (actual, expetted ) ;
AFeYM ethod
unite wild gore rome () £
chluer. Find Element (By.ttnkrextL"Home "))- click;
@ nerer fest
Pubtie ud close Byowses ¢) es
driver.cloce 073
ArtUL KemAR (ei NKEDIN).
2° fe we don't assign Priority 4o PestnG method phen they
wl execute $9 Alphaberical order. :
2)- fe p20 morhods are hawing came priority tree they ef)
execute in alphabetical order.
ATUL KOMAK (LINKEDIN)3y. (bahar fs Priovitization Yo Tectng ? |
y Friorttpation $n TstNG 18 a ey fo proulde a seqyuenu
&
4O methods fo phat dhey do not yun Dut OF Order.
Syntax = @ Tose C prtortey = 1)
Lower the Priority number, bigher is Pe priority of the
test case method.
Priority Value can be negative, Zero or PostHue «
Prortty cannot pass pmough xm. Files.
Te no priority js assigned ghen lefault priority Is zero.
Gp: [Ho 10 SP a fect Yn PectnG using Parameter? |
=P Using ‘enable’ parameter
ex- @ Test ( enable = False )
>)
VP kun resting - Falled.xmi.
Fipache POI in Selenium jn a Widery used API for selentum
data driven testing: Tt le @ Por |fbrary written In Javea
that gies users On API for manipulating microseFt
document ike .xls and «xlsx «
« Users can easily cyeare, modtfy and read/write cata
Jno excel.
+ for stands for poor Obfuscation Jmplementarton.
« Jo ead xLs Files, HEce nplementarton Used.
* To read xlsx FRIes, xSse Implementation Is used.
OWLLMULLUL LULL UT UU UU Tee eed ddd
|
ATUL KUMAR CHNKEDIADADU UUUUULUUUULUVUUUUUUUUUU UU tice
% (lass and Interfaces jn Por
XLS classes Torertace_ _ Xisx classes
HSSF Alovkbook ————>_ lk lorkbook <— XssFIAJOrKbook
HSSFSheet ————}_ Sheet €—— xosFsheet
YSSEROOW ————> Row <——— XssFRo
HssECell ————} Cony << x SF cell
fasameterfoatton ¥n celenlum ba Process fo Pararneresize
test serlpte $n Osder fo pace multiple data fo appuicatton
at yuntlme .
Ir fs a Strategy of executon Wrlcn Gutomatically runs
the test cases mustlple mes using glFterent Volues.
The conupt aciewed by paramererloing tne pest scripts
Called Data Driven Testing -
hore are two woys by whlch we can achieve parametestaatiy
tn TestnG
> plith the help of @ Paramerers.
2). plith the help of @ Datafouider
p.
Paramerers annotarton In Testrnlg Is a Way fo pass
VYolues fo fest methods as arguments using .xm) Files .
User may be required fo pass Valuec jo test methods
durhag yuntme @ Fayamerers annoratlon Can be used In
any method having @tes+ @ Rebore @AFier or
@ factory annotation.
pur jLoMAR CLINKEDINDWOVVUNWWUUULLL LULL uuu Ue ceeded
< Payamerey name = “qutnor”' value = “cnetan "
< Pavametey name = “ searchkey" Value =" 2 spores
< +est name = "+estauthor">
< Payamurer name = “ searthkey" value =“ 3 idiots Ve
< Classes >
< Clats name = " packagename, Test ">
XJ class >
<) classec>
Suite>
@ Opttonot Parameter
@ fest
@ Parameters (Cautnor " "Search eey"})
Pobiic ueid Test ( @ optional ( “defout") String author,
Sting earth key )
Package Packagename
Import O19. 0penga. Selenium. x ;
import O99. es ng. annotations, * %
import java. utile KS
public class Tost A
Lyving drivespath = "C:\\ geckodriver. exe
Webdylver drivey;
@ Test
@ Paramerers({"author", Searchkey" >) Parameter vatue
Cannot be Typeas ted
Cie string ts In the TSENG then
String i's also in method.)
ATULIKOMAR (LINKEDIN)UULUUULUU UU Cee eed dddid
LLL
SVU
pubite yuld Test Param (@ OpHonal Casc") , String
aymor , string searchkey ) shrows Exception }
Sugrem- setProperty (“webdaver. gecko. driver ,
driver = new Firefox Drver( 75
dafver. manage (). timeouts )-fmpictlyWwalt (10
yivexpath )
Jyivexpath )
me Unie. sewnds)}
Z -
Jsiver.get (“dtp 1! Jemo-google. com’) 5
inlebllement” Search ext = driver. Aindélement (By name
= +
Egos
Search Text. sendxeys (search rey);
£:0-P. ("ileliome "+ Ourhor + “Your Seart) Ker ts”
, Searchkey )}
x
:
Datapyovider helpr ut po Send musttple set OF data from
our excel Sheet est methods.
os es rut Kom pk CLIAKe DIM).
Feleq RAN NOTES GALLERY.
a) [Page ovjewr maser ?]
Fage ober model also Known as Pom, te a qectgn parrern
fn selenium thar creates an Objer yepository fer storing
a1] web elements» Gt Ps useful In Ode geusaptity and
fmprouing pesr Cate malntanane .
Bn Pom, tonsider, each webpage In appUcatton I<
consider as clats File. Each clase Fle wll Contetn
corresponding web page elements.
Ata womak Ching erin).Fage objet design pattern cays that operations g Flow
Jn UF Should be separared From vyerlPicathon - Tris makes
Our Code cloaney and easy +o understand
Object yepostiory Ps Independent OF festeqses So We can
use fame OR for slFFerent purposes }th dleferenh
400) £
Code become Jets and Optimized because of the
yeusable methods,
(PE Pacrora =) eae
Fage Facrosy 9s a class provided by the selenium webdehver
tO support page Bbjeu design parrern. In page fautory,
testers use @Findgy annotation. fhe fnttElements
method 3s usted fo jnitatize web elements .
* @FindBy (td =“elementid") webGlement element :
different jocators ike name, class name, tagname, xpath,
CESE Ink text, ParHallinktest can be use-
- Jntt@lement( ):-
fnitElementr Js a static method on Page Farory class.
Using nitélenents method one can Gnittatize all the elements
Jocared by @ FinaBy annofation .
* hazy foltialtzarton ;-
Ajax elomenthe catorFactory one fa2y 104d Concept }n
ge Fauory.
pout Kumag CrunKeon)
WNWVVWVUVLLLLLUL ULL UU UU ei edd dddddeWWVULULOULLLLLLUUUUUUUU Cede ddd’
When We develop a class In @ such a way that It can only
have one(1) Instance ar any Hme fe called singletne
dlesigh partern-
fr Js very useful vhen you Use need fo SAME Obfet oF
a class Brewer all classes or framework
Gnoreron class musk veturn same jnstane again fe Pr
fe $nspanHared agasn.
to Creare Singlefon class —
Declare eonstrurtor oF a Class 9s Private.
Declare starte yeferene variable oF clase. Lratic he needed
tO maltt ft auallable globally.
> Declare statle method wfth rerurn type at Ober oF
clase pihich should cheuc $F class ts already §nstanHared
Onw.
kinenever you Feel you chowd have Single fnstanee of a
Class , you can use Singleton parrern.
Class Singleton Test
Privare tparic fingtetonfest Instance = nulls
Private singteton TestC)
S-0-P. €"Dbfect creared") ;
fuitc trarte Singietonfest getincpanceok Classe) {
if Cinstane = = nui)
INStANY = NeW CIngletonTert (7;
Yeturn Instance 5
ei
yca
ULLLU Lee deeded ddddedd
17
uv
LULU
G00
Class TestDemo <
C string args 61) {
Singiepon Test Grer = Singie ronTest. ger Instone -
OF Class (17;
Singieronfert cecond = Pnaie pon Test. gerInctHina
oFClass C
}
=P iwhen you yun Above pyogram , you'll ge “Objet
creared” only one , when you Create second Jnsrane
% whl not create / ca construuor as it is already
Sn?pared One.
Aeructevm pk (LinebDIns) «
TEEY RAM NOTES GRILERY
Pmpoxt O29 -Openga. Selenium .x 5
Public class SingtetonClass {
Privare start StngietonClacs Instance = null;
Private webdytuey drivers
fvare Singieronclassc) £
Lysrem. set Property (“Werdyiver. Chrome. driver",
“Jexec ries | Chromedriver. exe” »
dalver = new chromeDylverc);
Public fratte Singleton Class getinstane oF Class () £
te Cinstanw = = nuit
Fnstanw = new Singietonclass€ 73
e
zeturn Instance;
Puriic Whebdrlver Setariver() {
yerurn drlvers
ao
ATur Koma Crim kepia)Load URL. faua
Pmpost 679 .cponqa.selentum
Pubite clare peaduat £
sesing arosr1)
Singteton Class SC) = LtnglejonClars.g et Inspanu OFclaccc) 5
wlebdriver di = SCI. getdyiver( ps
fingtetonClass Sc2= gngletonClasr. gerinstanwoFClass():
webdrtver da = $2, gotdyiver():
d2.9et (“https 11 g00910.com") 5
y:
Ei
=P ithen you yun hogdURl-faua you wil fee byowsor
launched and uy! wil be Opened jn same hyowser.
ble have instanHated pwo Jnstanu of Class but borh
ofue phe fame fnstane of driver.
): fr 9s an approach Por design 0: fr tt clace Provide by selentum
Pattexns. ? Webdrives. p 9 :
2). I+ hops in sepawating Page” 2). Tt ie a pechnique to Pmplement
Objects and Leripre pom.
3). ‘Ry? annotation 7s used to | 37. @AndBy annotation is used
doflne Page objects. 1° describe page objets.
u). There ?s Cache Storage fo uy). There hs ao need for cache
Perrorm Pasks fJOrage.
5). POM does not Provide razy Jey. page Factory does nor pwuide |
intHaltzarton. Jazy jnittatizarfon .
). Aleed 4o IntHallze every |e». an page objets are
page object Individually, polarized using ¢he
PnrtE€lements( ) method.
LUMAR CLINKED)AI)
WWVVUVURULULLUUUUUU Ue eed ddddddeNWSOVUVUUUVUL UL UL UU UU UU
xeert in selenium wdebdylver fs uted Por varlfying or
validating Scenario ender fest:
Based on phe yesulh of Assert, putcome oF test case js
decided -
Some widely used categortes tn stlenlum are t-
+ ascert€quals , assestNotéyuals
2D ascertTyue , assertFalse
3? assertNull , assertniotNutl.
4 assertsqme , assertnlotsame
°
[Haver ob Assert =]
0 As the name Indicate , pest execution fs
hated when conditon 4f @ part of assert are not met.
Hard ascert usually nvow an Accertlon error
C fava. tong. AssextionEvrorx) and test case marktd ar Fabled
as goon as hard assert CondiHton js Failed.
“fhe assorton error should be handled fn try... cater block.
2). Soet assest axe used When theo test
method executton need not to be halted when
assertion conditton fc not met:
fn case oF Loft assont, ervOTS are accuumulared
fn each @fest execution and assert An C) methods
throw asseyt encountered during exeuuton.
T? ge current Page URL
=) driver. 9e currentuRl () ;
ATUL KumAR CLINKEDIN).WNVVLVULULLULLULUUUUUUUU UU Ue ee eee eee
Ru defour asserts used jn selenium are hard assert.
You need 40 Import Org -testng. Mssert package for
phyowng appropriate asserts.
import Ov9. pes1Ng - ascorts. SolKASSerE}
=P peserton hacsert = new Assertion CV}
>
Lof+pscert cert = new LoftrAssert OC);
— x —-
dotver. ger (url)
drlver-navigare( )-T0 0),
driver. navigare( )- yerresh 7;
dxtver- gercurrentURL (1;
driver. Findglement (By-id (20). send keys C eys. F595
driver. navigate (). baue C);
driver. navigate (). forward (7;
driver close ¢)
vs driver. guit ¢ 7
> drluer. closec) method shai) close fre browser which Is
fn focus.
driver. yur) method closes all the hyowserc.
driver. close’) metnod closes aettve Wesdyfver instonn.
Arlver-quir() method closes at) he acHue
plebdylver Insane.
grucicumark_C LINKEDIN).WVVUVLULLULUU UU ddd dddddddddddddde’
Selenium LemoleebDrivey fs Used to execute browser
automarior te on yemote machine. RemoreliehDsrluer
Jars Impleme mrobdriver Interface 40 execute ccriptc
salebOrver server on vemote Machine
Frrefoxopt = new Fire rox OpHons ( 3
iver ytver = new Remote web Dyiver
ie
Crews ure Core), Fireroyopt);
Atul jumar (LINKEDIN)
TEEURAM - NOTES CACC f.
I> @test Csescription = "Validate 200 sratus code for
GET vequest ")
27. enabled = False 40 skip pest case execution:
@restC descripHon = “Validate 200 starus code Me
enabled = False )
32+ alweysRun = frue ? TF set 4o true, ers pest method
voill afiouys be run even fF depends on a method
phat Failed
@fest C deseriprion = “ Validate 200 status code es
alway sRun = true )
4? Groups
@test (deserptton = "Vajidate 200 status code”,
groups > {“ smoxesutte" , Regression - Sulte"} )
gruticomak CuAticeial).\SOUUUUUULULUUUUUU UU eed
c). [Hoyo vevan galled testares ih islam]
=P Levan using Hsing = Pulled xm)
I). PFrer lyst yun oF an Qutomared fest yun, Rigne
click on Pyojet— Click on Rerresh
. A Polder poh be geneyared name “test-ourput’ folder
side “test- Output’ folder, you cuuld Find ‘testng
-Falied . xm).
3)- Kun “testng - Fabled xm!’ Jo execute Palled pest cases
again -
° [Kerry Analyzer
Creare a class — RetryFalledTestlases +0 frplement
LRerry Analyzer -
impext O19 -testng . TRetry Analyzer;
Impoat Org. testNg -TTestResult ;
fublic class Retryfatiedfestlases Implements
Lretrypnatyzer {
Private Int: yetrycnt =O;
Private Int maxretryent =2;
Poaite boolean yerry (fTestResut yesut) {
ie Crerryent’ maxyetry ent ) 76
S008 ( "Retrying" + result. geeniame()) :
verryent +r;
yuuryn trues
veturn falce ,of
ve
Uiddddddddedddddd
vuuv
vYVLevEU
Impoat Org. Fesing » TRetry Analyzer 5
a [AnnotatronTyvans former 5
». annofarlons . [TestAnnotatton
Retyy Leiner Class Implements
TAnnotattonTvanstormer £
Ouveryide
Public veid pyansporm (ITestAnnotation festannotatton ,
Class postclass , Constructor Festlonstrucor,
Method testrethod ) {
SLrersyAnaiyzer retry = festannotarron.
gerRetry Analyzer l);
iF Cxerry = = na) {
test annotation. Set Retry Analyzer (Retry Falled
Festeases. class):
—_—x—
< eimers >
Ksistener class-name =" Packagenlame. Rey ~
Lictenerclass” J >
XK \lsreners >