Technical Technical Challenges with Selenium WHAT WHAT ARE THE TECHNICAL CHALLENGES WITH SELENIUM?
As you know Selenium Selenium is a free free ware open source testing tool. There are many many challenges challenges with Seleniu Seleniu m. 1. Selenium supports only web based applications. 2. It doesn't support any non web based (ike !in "2# $a%a Applet# $a%a Swing# .&et lient Ser%er etc a pplications. pplications. ". !hen you compare selenium with )T*# Silk Test# Test *artner and +,T# there are many challenges in terms of maintainability of the test cases. -. Since Selenium is a freeware tool# there is no direct support if one is in trouble with the support of a pplications. pplications. . There is no ob/ect repository concept in Selenium# so maintainability of the ob/ects is %ery high 0. There are many challenges if one ha%e to interact with !in "2 windows e%en when you are working with !eb based applications. . itmap comparison is not supported by Selenium. 3. Any reporting related capabilities# you need to depend on third party tools. 4. 5ou need to learn any one of the nati%e language like (.&et# $a%a# *erl# *ython# *6*# +uby to work e 7ciently with the scripting side of selenium. JUnit 4 Vs TestNG TestNG BELOW ARE SOME OF THE DIFFERENCES LISTED BETWEEN JUNIT 4 AND TESTNG 1. ANNOTATION @TEST IS USED IN BOTH JUNIT4 AND TESTNG BUT FROM DIFFERENT CLASS:
import org.junit.Test; 88 $9nit or Test&: import org.testng.annotations.Test; 88 Test&: public class MyTestClass { Test public void aTestMetho!"# throws ... { ... $
$
2. ACCORDING TO ANNOTATION SUPPORT:
Feature
Test Test annotation
JUnit 4
TestNG
Test Test
Test Test
%un &e'ore all tests in this suite ha(e ) run
*e'oreSuite
%un a'ter all tests in this suite ha(e run
)
+'terSuite
%un &e'ore the test
)
*e'oreTest
%un a'ter the test
)
+'terTest
%un &e'ore the ,rst test metho! that &elongs to any o' these grou-s is ) in(oe!
*e'oreGrou-s
%un a'ter the last test metho! that &elongs to any o' these grou-s is in(oe!
)
+'terGrou-s
%un &e'ore the ,rst test metho! in the current class is in(oe!
*e'oreClass
*e'oreClass
%un a'ter all the test metho!s in the current class ha(e &een run
+'terClass
+'terClass
%un &e'ore each test metho!
*e'ore
*e'oreMetho!
%un a'ter each test metho!
+'ter
+'terMetho!
/gnore test
ignore
Test"en&ale0'alse#
12-ecte! e2ce-tion
Test"e2-ecte! 0 +rithmetic12ce-tion.class#
Test"e2-ecte!12ce-tions 0 +rithmetic12ce-tion.class#
Timeout
Test"timeout Test"timeout 0 3#
Test"timeout Test"timeout 0 3#
3. EXCEPTION TEST
/t e2-lains what e2ce-tion will throw 'rom the unit test. 55JUnit4 Test"e2-ecte! 0 ArithmeticException .class# public void !i(ision*y6ero12ce-tion"# { int i 0 35; $
55TestNG Test"e2-ecte!12ce-tions 0 ArithmeticException .class# public void !i(ision*y6ero12ce-tion"# { int i 0 35; $
4. Ig!"# T#$% T#$%
/t e2-lains how to ignore the unit test. 55JUnit
/gnore"7Not %ea!y to %un7# Test public void /gnoreTest"# { System.out.-rintln"7Metho! is not rea!y yet7#; $
55TestNG
%un a'ter the test
)
+'terTest
%un &e'ore the ,rst test metho! that &elongs to any o' these grou-s is ) in(oe!
*e'oreGrou-s
%un a'ter the last test metho! that &elongs to any o' these grou-s is in(oe!
)
+'terGrou-s
%un &e'ore the ,rst test metho! in the current class is in(oe!
*e'oreClass
*e'oreClass
%un a'ter all the test metho!s in the current class ha(e &een run
+'terClass
+'terClass
%un &e'ore each test metho!
*e'ore
*e'oreMetho!
%un a'ter each test metho!
+'ter
+'terMetho!
/gnore test
ignore
Test"en&ale0'alse#
12-ecte! e2ce-tion
Test"e2-ecte! 0 +rithmetic12ce-tion.class#
Test"e2-ecte!12ce-tions 0 +rithmetic12ce-tion.class#
Timeout
Test"timeout Test"timeout 0 3#
Test"timeout Test"timeout 0 3#
3. EXCEPTION TEST
/t e2-lains what e2ce-tion will throw 'rom the unit test. 55JUnit4 Test"e2-ecte! 0 ArithmeticException .class# public void !i(ision*y6ero12ce-tion"# { int i 0 35; $
55TestNG Test"e2-ecte!12ce-tions 0 ArithmeticException .class# public void !i(ision*y6ero12ce-tion"# { int i 0 35; $
4. Ig!"# T#$% T#$%
/t e2-lains how to ignore the unit test. 55JUnit
/gnore"7Not %ea!y to %un7# Test public void /gnoreTest"# { System.out.-rintln"7Metho! is not rea!y yet7#; $
55TestNG
Test"ena&le!0alse# public void /gnoreTest"# { System.out.-rintln"7Metho! is not rea!y yet7#; $
&. SUITE TEST
!" Suite Test
/t e2-lains how to &un!le a 'ew unit test an! run together. 55JUnit4 The 7%un8ith7 7%un8ith7 an! 7Suite7 are use to run the suite test. test. The &elow class means &oth unit test 7JunitTest37 7JunitTest37 an! 7JunitTest97 7JunitTest97 run together a'ter 7JunitTest:7 7JunitTest:7 e2ecute!. +ll the !eclaration is !e,ne insi!e the class.
%un8ith"Suite.class# Suite.SuiteClasses"{ JunitTest3.class JunitTest9.class $# public class JunitTest: { $
55TestNG
TestNGT >TestNGTest3? an! >TestNGT >TestNGTest9? est9? will run it i t together. toge ther.
@suite name07My test suite7A @test name07My test7A @classesA @class name07e2am-le.test.TestNGTest37 5A @class name07e2am-le.test.TestNGTest97 5A @5classesA @5testA @5suiteA
'. DEPENDENC( TEST
/t e2-lains which test will e2ecute a'ter what test. /' the !e-en!ent metho! 'ails then all su&seBuent tests will &e si--e! not mare! as 'aile!. 55JUnit4 JUnit 'ramewor is 'ocus on test isolation; it !i! not su--ort this 'eature 'eature at the moment. 55TestNG /t use 7!e-en!nMetho!s7 to im-lement the !e-en!ency testing as 'ollowing
Test public void testMetho!3"# { System.out.-rintln"7This is metho! 37#; $
Test"!e-en!snMetho!s0{7testMetho!37$# Test"!e-en!snMetho!s0{7testMetho!37$# public void testMetho!9"# { System.out.-rintln"7This is metho! 97#; $ ). PARAMETERI*ED TEST
/t says how to -ass -arameters to an uni t test !ynamically. !ynamically. 55JUnit4 The 7%un8ith7 7%un8ith7 an! 7Darameter7 7Darameter7 is use to -ro(i!e -arameter (alue 'or unit test Darameters Darameters ha(e to return =istEF an! the -arameter will -ass into class constructor as argument.
%un8ith"(alue %un8ith"(alue 0 Darameterie!.class# public class JunitTest { private int num&er; Ju nitTest" est" int num&er# { public JunitT this.num&er 0 num&er; $ Darameters public static #ollection @$b%ectEFA !ata"# { $ { 9 $ { : $ { 4 $ $; $b%ect EFEF !ata 0 new $b%ectEFEF { { 3 $ return Arrays.as=ist"!ata#; $ Test public void -ushTest"# { System .out.-rintln"7Darameterie! Num&er is H 7 I num&er#; $ $ /t has many limitations here; we ha(e to 'ollow the >JUnit? way to !eclare the -arameter an! the -arameter has to -ass into constructor in or!er to initialie the class mem&er as -arameter (alue ' or testing. The return ty-e o' -arameter class is >=ist EF? !ata has &een limite! to String or a -rimiti(e (alue 'or testing. 55TestNG ataDro(i!er? is use! to -ro(i!e (ary -arameter 'or testing. AD+ANT AD+ANTAGES AGES OF WEB DRI+ER DRI+ER
3# Su--or Su--ortt 'or iDhone iDhone an! an! +n!ro +n!roi! i! testi testing ng 9# /m-lementation o' listeners K a much awaite! 'eature :# *etter 'eatures 'or +ja2 testing. 4# Lou Lou can easily simulate clicing on 'ront an! &ac &utton o' &rowser. # Lou can e2tract o&jects in &ul lie TD. Oor e2 K e2tract all lins o' -age. 8ith %C this was a &ig hastle P# Unlie %C you !onQt ha(e to start a ser(er in we&!ri(er. we&!ri(er. R# Lou Lou can simulate mo(ement o' a mouse using selenium. # Ta&s Ta&s an! -o-s are more or less the same. %C can also han!l e an! 8e&!ri(er can also han!le. # Lou can ,n! coor!inates o' any o&ject using 8e&!ri(er. 3# Lou Lou ha(e classes in 8e&!ri(er 8e&!ri(er which hel- you to simulate ey -ress e(ents o' ey&oar!. 3# eywor! !ri(en 'ramewor is (ery easy to &uil! in we&!ri(er. we&!ri(er.
TestNG *asic Conce-ts an! +nnotations
&' TESTNG BASIC CONCEPTS AND ANNOTATIONS
:# 4# Test&: engine supports a series of annotations# with these annotations it e%en has stronger ;euick look at the life cycle of a typical Test&: case.
#
P# R# # Orom the gi(en illustration we now that the li'eKcycle o' a TestNG case starts with *e'oreClass an! en!s with +'terClass. *e'oreClass5+'terClass metho!s will &e run &e'ore5a'ter any metho! in a gi(en is run they are !esigne! 'or those e2-ensi(e resource initialiation5cleanu- an! reco(ery we !i!nQt -ut *e'oreSuite *e'oreGrou-s +'terGrou-s an! +'terSuite to this illustration &ut i' they were they w ill &e ran e(en &e'ore *e'oreClass or a'ter +'terClass. Con,guration is !e-recate! so we !onQt recommen! use it. # ()' TESTNG BASIC ANNOTATIONS FOR CONFIGURATION METHODS *r i
Annotation name
+ocumentation
3 9
:
*e'oreSuite
*e'oreGrou-s
*e'oreClass
+nnotates metho!s that will &e run &e'ore any metho! in a gi(en is run. +nnotates metho!s that will &e run &e'ore the ,rst metho! in any o' the s-eci,e! grou-s is run. +nnotates metho!s that will &e run &e'ore the ,rst metho! on the current test class is run.
4
*e'oreTest
+nnotates metho!s that will &e run &e'ore any metho! in a gi(en is run.
*e'oreMetho!
+nnotates metho!s that will &e run &e'ore each test metho!.
P
+'terMetho!
+nnotates metho!s that will &e run a'ter e(ery test metho!.
R
+'terTest
+'terClass
+nnotates metho!s that will &e run a'ter all the test metho!s in a gi(en ha(e &een run. +nnotates metho!s that will &e run a'ter the last test metho! on th e current class is run. +nnotates metho!s that will &e run a'ter the last test metho! &elonging to
+'terGrou-s
the grou-s s-eci,e! in its (alue attri&ute has &een run. The annotate! metho! is automatically -ut into these s-eci,e! grou-s.
3
+'terSuite
+nnotates metho!s that will &e run a'ter all the test metho!s in a gi(en ha(e &een run.
33# The annotations Test annotates a metho! as test case in TestNG -attern. 39# 3:# Simple ?
-acage com.MyDroject; im-ort org.testng.annotations.W; -u&lic class TestNGTest { *e'oreGrou-s -u&lic (oi! *e'oreGrou-s"# { System.out.-rintln"7*e'oreGrou-s7#; $ *e'oreClass -u&lic (oi! *e'oreClass"# { System.out.-rintln"7*e'oreClass7#; $ Test"grou-s 0 {7My grou-7$# -u&lic (oi! test3"# {
System.out.-rintln"7test37#; $ Test -u&lic (oi! test9"# { System.out.-rintln"7test97#; $ +'terClass -u&lic (oi! +'terClass"# { System.out.-rintln"7+'terClass7#; $ +'terMetho! -u&lic (oi! +'terMetho!"# { System.out.-rintln"7+'terMetho!7#; $ $
6ere is the output of this Abo%e code EDarserF %unningH CHXUsersX+!ministratorX./ntelliJ/!eaRXsystemXtem-KtestngKcustomsuite.2ml *e'oreClass test3 +'terMetho! test9 +'terMetho! +'terClass 00000000000000000000000000000000000000000000000 Custom suite Total tests runH 9 OailuresH Si-sH 00000000000000000000000000000000000000000000000 Selenium *asics WHAT IS SELENIUM ?
Selenium is a Testing framework for web applications# ha%ing " %ariants@ Selenium I?
•
B ,irefo< addBon B +ecord and playback user actions on a web site B &ot recommend for stable# long staying test suites
•
Selenium + (+emote ontrol# Selenium 1 B B B B
$a%a Ser%er that controls %arious browsers ?
•
Selenium !ebri%er (Selenium 2
B $a%a ibrary# which controls the browser B 6as a ob/ectBoriented programming A*I B Supports Internet ?
-acage com.test.we&!ri(er; im-ort static org.testng.+ssertJUnit.assert1Buals; im-ort org.o-enBa.selenium.*y; im-ort org.o-enBa.selenium.8e&ri(er; im-ort org.o-enBa.selenium.,re'o2.Oire'o2ri(er; im-ort org.testng.annotations.+'terClass; im-ort org.testng.annotations.*e'oreClass; im-ort org.testng.annotations.Test; -u&lic class ri(er { -ri(ate 8e&ri(er !ri(er; *e'oreClass -u&lic (oi! Startu-"#{ !ri(er 0 new Oire'o2ri(er"#; $ Test "!escri-tion07Google =ogin7# -u&lic (oi! Google=ogin"# throws 12ce-tion{ !ri(er.get"7htt-H55www.gmail.com7#; assert1Buals"7Sign in7 !ri(er.,n!1lement"*y.i!"7sign/n7##.get+ttri&ute"7(alue7##; !ri(er.,n!1lement"*y.i!"71mail7##.sen!eys"7WWWWWWWWW7#; !ri(er.,n!1lement"*y.i!"7Dassw!7##.sen!eys"7WWWWWWWWWW7#; !ri(er.,n!1lement"*y.i!"7sign/n7##.clic"#; Threa!.slee-"3#; !ri(er.switchTo"#.'rame"7can(as'rame7#; !ri(er.,n!1lement"*y.i!"7g&gs4!n7##.clic"#; !ri(er.,n!1lement"*y.i!"7g&R37##.clic"#; !ri(er.switchTo"#.!e'aultContent"#; assert1Buals"7Sign in to Gmail7 !ri(er.,n!1lement"*y.i!"7&utton7##.getTe2t"##; $ +'terClass -u&lic (oi! tear!own"#{ !ri(er.Buit"#; $ $ Selenium 8e& ri(er Comman! =ist #ommand +escription driver"0et23http55www"0oo0le"com3'6 To o-en an a--lication driver"7ndElement2,y"id23passwd8id3''6 Oin!ing 1lement using /! driver"7ndElement2,y"name23passwd3''6 Oin!ing 1lement using Name driver"7ndElement2,y"xpath2355input9:id;eys23some text3'6 To ty-e some !ata element"clear2'6 clear thecontents o' a te2t ,el! or te2tarea driver"7ndElement2,y"xpath2355select3''6 Selecting the (alue select"7ndElements2,y"ta0Name23option3''6 Selecting the (alue select"deselectAll2'6 This will !eselect all DT/Ns 'rom the ,rst S1=1CT on the -age select"select,y?isibleText23Edam3'6 select the DT/N withthe !is-laye! te2t o' >1!am? 7ndElement2,y"id23submit3''"clic@2'6 To clic on +ny &utton5=in driver"switchTo2'"window23windowName3'6 Mo(ing 'rom one win!ow to another win!ow driver"switchTo2'"rame23rameName3'6 swing 'rom 'rame to 'rame "or into i'rames# driver"switchTo2'"rame23rameName")"child3'6 to access su&'rames &y se-arating the -ath with a !ot an! you can s-eci'y the 'rame &y itsin!e2 too.
driver"switchTo2'"alert2'6 Yan!ling +lerts driver"navi0ate2'"to23http55www"example"com3'6 To Na(igate Daeticular U%= driver"navi0ate2'"orward2'6 To Na(igate Oorwar! driver"navi0ate2'"bac@2'6 To Na(igate *acwor! driver"close2' Closes the current win!ow driver"uit2' uits the !ri(er an! closes e(ery associate! win!ow. driver"switchBtoBalert2' Switches 'ocus to an alert on the -age. driver"reresh2' %e'reshes the current -age. driver"implicitlyBwait2C)' +mount o' time to wait driver"setBscriptBtimeout2C)' The amount o' time to wait driver"0etBscreenshotBasB7le2D5Screenshots5oo"pn0D' The 'ull -ath you wish to sa(e your screenshot to driver"0etBscreenshotBasBbase42' Gets the screenshot o' the current win!ow as a &aseP4 enco!e! string which is use'ul in em&e!!e! i mages in YTM=
using 'unctions in 2-ath in selenium ow to use unctions in xpath in selenium +utomation using selenium is a great e2-erience. /t -ro(i!es many way to i!enti'y an o&ject or element on the we& -age. *ut sometime we 'ace the -ro&lems o' i!enti'ying the o&jects on a -age whi ch ha(e same attri&utes. 8hen we get more than one element which are same in attri&ute an! name lie multi-le chec &o2es with same name an! same i!. More than one &utton ha(ing same name an! i!s. There are no way to !istinguishes those element. /n this case we ha(e -ro&lem to instruct selenium to i!enti'y a -articular o&ject on a we& -age.
/ am gi(ing you a sim-le e2am-le . /n the &elow html source there are P chec &o2es are there ha(ing same ty-e an! same name. /t is really tough to select thir! or ,'th. in-ut ty-e0Zchec&o2Z name0ZchZ ,rst in-ut ty-e0Zchec&o2Z name0ZchZ secon! in-ut ty-e0Zchec&o2Z name0ZchZ thir! in-ut ty-e0Zchec&o2Z name0ZchZ 'orth in-ut ty-e0Zchec&o2Z name0ZchZ ,'th in-ut ty-e0Zchec&o2Z name0ZchZ si2th There are some 'unctions we can use in <-ath to i!enti'y the o&ject in a&o(e cases. +n
/n the a&o(e html ,le there are si2 chec &o2es an! all are ha(ing same attri&utes "same ty-e an! name# 3. Yow we can select the last chec&o2 &ase! on the -osition. 8e can use last"# 'unction to i!enti'y the last o&ject among all similar o&jects. *elow co!e will chec or unchec the last chec&o2. selenium.clic"72-ath0"55in-utEty-e0Zchec&o2ZF#Elast"#F7#; 9. Yow we can select the secon! last chec &o2 an! thir! last chec &o2. 8e can use last"#K 'unction to i!enti'y the last o&ject among all similar o&jects. *elow co!e will chec or unchec the secon! last chec&o2 an! thri! last chec&o2 res-ecti(ely. selenium.clic"72-ath0"55in-utEty-e0Zsu&mitZF#Elast"#K3F7#; selenium.clic"72-ath0"55in-utEty-e0Zsu&mitZF#Elast"#K9F7#;
N!,# S#% : !$%!/0
/' you want to select any o&ject &ase! on their -osition using 2-ath then you can use -osition"# 'unction in 2-ath. Lou want to select secon! chec&o2 an! 'orth chec&o2 then use &elow comman! selenium.clic"72-ath0"55in-utEty-e0Zchec&o2ZF#E-osition"#09F7#; selenium.clic"72-ath0"55in-utEty-e0Zchec&o2ZF#E-osition"#04F7#; a&o(e co!e will select secon! an! 'orth chec&o2 res-ecti(ely. S%"g : $%"%$%5/0
Many we& sites create !ynamic element on their we& -ages where /!s o' the elements gets generate! !ynamically.
1ach time i! gets generate! !i\erently. So to han!le this situation we use some Ja(aScri-t 'unctions.
TestNG ) e-en!ency Test
T#$%NG6 D##,#78 T#$%
The Cependency TestD means methods are test base on dependency. If the dependent method fails# all the subse>uent test methods will be skipped# not marked as failed.
Test&: uses CdependFnGethodsC to implement the dependency testing as following
import org.testng.annotations.H 8HH H Test&: ependency Test H
H H8 public class Test&:Test J KTest public %oid method1( J
System.out.println(LThis is method 1L M KTest(dependsFnGethodsNJLmethod1LM public %oid method2( J System.out.println(LThis is method 2L M M
+esult
*ASS?@ method1 *ASS?@ method2
The Cmethod2(D will e
TestNG ) /gnore Test This >/gnore!? means the metho! is not rea!y to test the TestNG engine will just &y-ass this metho!. im-ort org.testng.annotations.W; 5WW W TestNG /gnore Test W W W5 -u&lic class TestNGTest: { Test"ena&le!0'alse# -u&lic (oi! !i(ision8ith12ce-tion"# { System.out.-rintln"7Metho! is not rea!y yet7#; $ $
/n a&o(e e2am-le TestNG will not test the division1ithException2' metho!. estNG ) Suite Test TESTNG 6 SUITE TEST
The >Suite Test? means &un!le a 'ew unit test cases an! run it together.
/n TestNG TestNGTest(? an! >TestNGTest& ? will e2ecute together.
@^CTLD1 suite SLST1M 7htt-H55&eust.com5testng5testngK3..!t!7 A @suite name07My test suite7A @test name07testing7A @classesA @class name07TestNGTest37 5A @class name07TestNGTest97 5A @5classesA @5testA @5suiteA *esi!e classes &un!le testing TestNG -ro(i!es a >Grou-ing? 'eature to &un!le 'ew metho!s as a single unit 'or testing where e(ery metho! is tie to a grou-. Oor e2am-le YereQs a class with 'our metho!s three grou-s "metho!3 metho!9 an! metho!:# im-ort org.testng.annotations.W; 5W W W TestNG Grou-ing W W W5 -u&lic class TestNGTest9 { Test"grou-s07metho!37# -u&lic (oi! testingMetho!3"# { System.out.-rintln"7Metho! K testingMetho!3"#7#; $ Test"grou-s07metho!97# -u&lic (oi! testingMetho!9"# { System.out.-rintln"7Metho! K testingMetho!9"#7#; $ Test"grou-s07metho!37# -u&lic (oi! testingMetho!33"# { System.out.-rintln"7Metho! K testingMetho!33"#7#; $ Test"grou-s07metho!47# -u&lic (oi! testingMetho!4"# { System.out.-rintln"7Metho! K testingMetho!4"#7#; $ $ Lou can e2ecute the unit test with grou- >metho!3? only. @^CTLD1 suite SLST1M 7htt-H55&eust.com5testng5testngK3..!t!7 A @suite name07My test suite7A @test name07testing7A @grou-sA
@runA
@inclu!e name07metho!375A
@5runA
@5grou-sA @classesA @class name07TestNGTest97 5A @5classesA @5testA @5suiteA R#$9-%:
Metho! K testingMetho!33"# Metho! K testingMetho!3"#
TestNG Grou-ing is highly [e2i&le an! use'ul es-ecially when you im-lement it in your -roject integration testing. /nter(iew uestions FEW INTER+IEW UESTIONS FOR SELENIUM WEBDRI+ER WITH JA+A
B!hat class should be e
BIs there Assert.assert&ot?>uals( in webdri%er P Ban we schedule the e
+'ter success'ully e2ecuting scri-ts e(ery one want to write results to e2cel sheet..here is the way to write results to e2cel sheet.... *elow is the sam-le scri-t to write results to e2cel sheet... -acage test; im-ort ja(a.io.Oile/n-utStream; im-ort ja(a.io.Oileut-utStream; im-ort j2l.Sheet; im-ort j2l.8or&oo; im-ort j2l.write.=a⪙ im-ort j2l.write.8rita&leSheet; im-ort j2l.write.8rita&le8or&oo; im-ort com.thoughtwors.selenium.W; im-ort org.o-enBa.selenium.ser(er.W; im-ort org.testng.annotations.W; -u&lic class /m-orte2-ort3 { -u&lic Selenium selenium; -u&lic SeleniumSer(er seleniumser(er; *e'oreClass -u&lic (oi! setU-"# throws 12ce-tion { %emoteControlCon,guration rc 0 new %emoteControlCon,guration"#; seleniumser(er 0 new SeleniumSer(er"rc#; selenium 0 new e'aultSelenium"7localhost7 4444 7W,re'o27 7htt-H557#; seleniumser(er.start"#; selenium.start"#;
$ Test -u&lic (oi! test/m-orte2-ort3"# throws 12ce-tion { 55 ead data rom excel sheet Oile/n-utStream , 0 new Oile/n-utStream" 7OHXXOrameworXXtest!ataXX=ogin3Cre!entials.2ls7#; 8or&oo w 0 8or&oo.get8or&oo",#; Sheet s 0 w.getSheet"#; String aEFEF 0 new StringEs.get%ows"#FEs.getColumns"#F; 55 1rite the input data into another excel 7le Oileut-utStream 'o 0 new Oileut-utStream" 7OHXXOrameworXX%esultsXX=ogin%esult3.2ls7#; 8rita&le8or&oo ww& 0 8or&oo.create8or&oo"'o#; 8rita&leSheet ws 0 ww&.createSheet"7loginresult37 #; selenium.o-en"7htt-H55www.gmail.com7#; selenium.win!owMa2imie"#; System.out.-rintln"7s.get%ows"# 0 7 I s.get%ows"##; 'or "int i 0 ; i @ s.get%ows"#; iII# { System.out.-rintln"7s.getColumns 0 7 I s.getColumns"##; 'or "int j 0 ; j @ s.getColumns"#; jII# { aEiFEjF 0 s.getCell"j i#.getContents"#; =a&el l 0 new =a&el"j i aEiFEjF#; =a&el l3 0 new =a&el"9 7%esult7#; ws.a!!Cell"l#; ws.a!!Cell"l3#; $ $ 'or "int i 0 3; i @ s.get%ows"#; iII# { selenium.ty-e"71mail7 s.getCell" i#.getContents"##; selenium.ty-e"7Dassw!7 s.getCell"3 i#.getContents"##; selenium.clic"7sign/n7#; selenium.waitOorDageTo=oa!"7:7#; &oolean aa 0 selenium.isTe2tDresent"7The username or -asswor! you entere! is incorrect. E_F7#; System.out.-rintln"7the (alue o' aa isHH7 I aa#; i' "aa# { =a&el l: 0 new =a&el"9 i 7'ail7#; ws.a!!Cell"l:#; System.out.-rintln"7=ogin Oailure7#; Threa!.slee-"3#; $ else { =a&el l9 0 new =a&el"9 i 7-ass7#; ws.a!!Cell"l9#; selenium.clic"7lin0Sign out7#; Threa!.slee-"3#; $ $ ww&.write"#; ww&.close"#; $ +'terClass -u&lic (oi! tearown"# throws 12ce-tion { selenium.sto-"#; seleniumser(er.sto-"#; $ $ Lour in-ut !ata shoul! &e lie this....
Lour out -ut e2cel shoul! &e lie this
8rite results to e2cel sheet 1rite results to excel sheet +'ter success'ully e2ecuting scri-ts e(ery one want to write results to e2cel sheet..here is the way to write results to e2cel sheet.... *elow is the sam-le scri-t to write results to e2cel sheet... -acage test; im-ort ja(a.io.Oile/n-utStream; im-ort ja(a.io.Oileut-utStream; im-ort j2l.Sheet; im-ort j2l.8or&oo; im-ort j2l.write.=a⪙ im-ort j2l.write.8rita&leSheet; im-ort j2l.write.8rita&le8or&oo; im-ort com.thoughtwors.selenium.W; im-ort org.o-enBa.selenium.ser(er.W; im-ort org.testng.annotations.W; -u&lic class /m-orte2-ort3 {
-u&lic Selenium selenium; -u&lic SeleniumSer(er seleniumser(er; *e'oreClass -u&lic (oi! setU-"# throws 12ce-tion { %emoteControlCon,guration rc 0 new %emoteControlCon,guration"#; seleniumser(er 0 new SeleniumSer(er"rc#; selenium 0 new e'aultSelenium"7localhost7 4444 7W,re'o27 7htt-H557#; seleniumser(er.start"#; selenium.start"#; $ Test -u&lic (oi! test/m-orte2-ort3"# throws 12ce-tion { 55 ead data rom excel sheet Oile/n-utStream , 0 new Oile/n-utStream" 7OHXXOrameworXXtest!ataXX=ogin3Cre!entials.2ls7#; 8or&oo w 0 8or&oo.get8or&oo",#; Sheet s 0 w.getSheet"#; String aEFEF 0 new StringEs.get%ows"#FEs.getColumns"#F; 55 1rite the input data into another excel 7le Oileut-utStream 'o 0 new Oileut-utStream" 7OHXXOrameworXX%esultsXX=ogin%esult3.2ls7#; 8rita&le8or&oo ww& 0 8or&oo.create8or&oo"'o#; 8rita&leSheet ws 0 ww&.createSheet"7loginresult37 #; selenium.o-en"7htt-H55www.gmail.com7#; selenium.win!owMa2imie"#; System.out.-rintln"7s.get%ows"# 0 7 I s.get%ows"##; 'or "int i 0 ; i @ s.get%ows"#; iII# { System.out.-rintln"7s.getColumns 0 7 I s.getColumns"##; 'or "int j 0 ; j @ s.getColumns"#; jII# { aEiFEjF 0 s.getCell"j i#.getContents"#; =a&el l 0 new =a&el"j i aEiFEjF#; =a&el l3 0 new =a&el"9 7%esult7#; ws.a!!Cell"l#; ws.a!!Cell"l3#; $ $ 'or "int i 0 3; i @ s.get%ows"#; iII# { selenium.ty-e"71mail7 s.getCell" i#.getContents"##; selenium.ty-e"7Dassw!7 s.getCell"3 i#.getContents"##; selenium.clic"7sign/n7#; selenium.waitOorDageTo=oa!"7:7#; &oolean aa 0 selenium.isTe2tDresent"7The username or -asswor! you entere! is incorrect. E_F7#; System.out.-rintln"7the (alue o' aa isHH7 I aa#; i' "aa# { =a&el l: 0 new =a&el"9 i 7'ail7#; ws.a!!Cell"l:#; System.out.-rintln"7=ogin Oailure7#; Threa!.slee-"3#; $ else { =a&el l9 0 new =a&el"9 i 7-ass7#; ws.a!!Cell"l9#; selenium.clic"7lin0Sign out7#; Threa!.slee-"3#; $ $ ww&.write"#; ww&.close"#; $ +'terClass -u&lic (oi! tearown"# throws 12ce-tion {
selenium.sto-"#; seleniumser(er.sto-"#; $ $ Lour in-ut !ata shoul! &e lie this....
Lour out -ut e2cel shoul! &e lie this
Collection Ja(a Drogramming /nter(iew uestions 3 #ollection A*. H Ja(a Collections 'ramewor +D/ is a uni,e! architecture 'or re-resenting an! mani-ulating collections. +ll collections 'ramewors contains inter'ace im-l ementations an! algorithms. Oollowing are the &ene,ts o' collection 'ramewor. ` %e!uces -rogramming e\orts. K /ncreases -rogram s-ee! an! Buality. ` +llows intero-era&ility among unrelate! +D/s. ` %e!uces e\ort to learn an! to use new +D/s. ` %e!uces e\ort to !esign new +D/s. ` 1ncourages Oosters so'tware reuse. Collection contains si2 inter'aces. Set =ist an! Sorte!SetH e2ten!s collection inter'ace Ma- an! Sorte!Ma- H !onQt e2ten! collection inter'ace.a
1hat is ash-ap and -apH Ma-s stores ey Value -air an! Yashma- is class that im-lements that using hashing techniBue. +iI ashTable ?s ash-ap ?s ashSet
Yashta&le Yashta&le is &asically a !atastructure to retain (alues o' eyK(alue -air. oesnot allow null 'or ey an! (alues /t is synchronie!. So it comes with its cost. nly one threa! can access in one time Synchronie! means only one threa! can mo!i'y a hash ta&le at one -oint o' time. +ny threa! &e'ore -er'orming an u-!ate on a hashta&le will ha(e to acBuire a loc on the o&ject while others will wait 'or loc to &e release!. Yashta&le@/ntegerStringA ran0 new Yashta&le@/ntegerStringA"#; ran.-ut"37+7#; ran.-ut"37*7#; ran.-ut"37C7#; ran.-ut"null717#; NullDointer12ce-tion at runtime System.out.-rintln"ran.get"3##; System.out.-rintln"ran.get"9##; YashMa=ie Yashta&le it also acce-ts ey (alue -air.+llows null (alues /t is unsynchronie!. So come u- with &etter -er'ormance *y using 'ollowing comman! Yashma- can &e synchronie!. Ma- m 0 Collections.synchronie!Ma-"hashMa-#; YashMa-@/ntegerStringA =ang0 new YashMa-@/ntegerStringA"#; =ang.-ut"3 7ja(a7#; =ang.-ut"9 null#; YashSet YashSet !oes not allow !u-licate (alues. /t can &e use! where you want to maintain a uniBue list. Lou also use its contain metho! to chec whether the o&ject is alrea!y a(aila&le in YashSet. /t -ro(i!es a!! metho! rather -ut metho!. YashSet@StringA str0 new YashSet@StringA"#; str.a!! "7+--le7#; str.a!! "7*oy7#; str.a!! "7Cat7#; i' "str.contains"7+--le7## .terator and implementation +n iterator is an o&ject that ena&les a -rogrammer to tra(erse a collection. /terator iter 0 list.iterator"#; while "iter.hasNe2t"## { System.out.-rint"iter.ne2t"##; i' "iter.hasNe2t"## System.out.-rint"7 7#; $ +iI .terator ?s /ist.terator
/terator H 1na&les you to tra(erse through a collection in the 'orwar! !irection only 'or o&taining or remo(ing elements =ist/terator H e2ten!s /terator an! allows &i!irectional tra(ersal o' list an! also allows the mo!i,cation o' elements. .nterace .mplementation
/m-lementations /nter'ace =ist
+rray
*alance! Tree
+rray=ist
=ine! =ist
Yash ta&le
=ine!=ist
Ma-
TreeMa-
YashMa-
Set
TreeSet
YashSet
eBue
+rrayeBue
=ine!=ist
Collection inter(iew uestions in Ja(a 9 Array/ist vs /in@ed/ist
+!!ing new elements is -retty 'ast 'or either ty-e o' list. Oor the +rray=ist !oing ran!om loou- using 7get7 is 'ast &ut 'or =ine!=ist itZs slow. /tZs slow &ecause thereZs no ebcient way to in!e2 into the mi!!le o' a line! list. 8hen remo(ing elements using +rray=ist is slow. This is &ecause all remaining elements in the un!erlying array o' &je ct instances must &e shi'te! !own 'or each remo(e o-eration. *ut here =ine!=ist is 'ast &ecause !eletion can &e !one sim-ly &y changing a cou-le o' lins. So an +rray=ist wors &est 'or cases where youZre !oing ran!om access on the list an! a =ine!=ist wors &etter i' youZre !oing a lot o' e!iting in the mi!!le o' the list. Array vs Array/ist vs /in@ed/ist vs ?ector in %ava
+rray (s +rray=istH +rray=ist is much &etter than +rray when the sie nee! to &e increase! !ynamically. 1bciency is -ossi&le with arrays. +rray=ist -ermits null elements. +rray=ist has grou- o' o&jects. +rray i t treate! as an o&ject. =ine!=ist (s VectorH + (ector is a growa&le array which can store many o&j ects o' !i\erent classes. + line! list is a linear list where each item has a li n to the ne2t item in the list. /t can &e use! to im-lement Bueue or stac o-erations. +rray=ist (s =ine!=ist +rray list is &etter than line! list 'or accessing elements.=ine! list is &etter than array list to -er'orm insertion an! !eletion o-erations at ar&itrary locations. Vector Vs +rray=ist Vector is synchronie! whereas +rray=ist is not. 1(en though Vector class is synchronie! still when you want -rograms to run in multithrea!ing en(ironment using +rray=ist with Collections.synchronie!=ist"# is recommen!e! o(er Vector. +rray=ist has no !e'ault sie while (ector has a !e'ault sie o' 3. 1hat is an enumerationH +n enumeration is an inter'ace containing metho!s 'or accessing the un!erlying !ata structure 'rom which the enumeration is o&taine!. /t is a construct which collection classes return when you reBuest a collection o' all the o&jects store! in the collection. /t allows seBuential access to all th e elements store! in the collection. euals vs toStrin0 vs hashcod are methods in $b%ect
Sort +iI b5w Arrays and #ollections
*oth use the same algorithm the only !i\erence is ty-e o' in-ut to them. Collections.sort"# has a in-ut as =ist so it !oes a translation o' =ist to array. So this shoul! &e use! when you are trying to sort a list. +rrays.sort is 'or arrays so the sorting is !one !irectly on the array. Drinting the Oi&onacci Series using Ja(a -u&lic class Oi&onaciN { -u&lic static (oi! main"String argsEF# { int -re( ne2t sum n; -re(0ne2t03; 'or"n03;n@0;nII# { System.out.-rintln"-re(#; sum0-re(Ine2t; -re(0ne2t; ne2t0sum; $ $ $ *asic String -erations in Ja(a -u&lic class String-erations { -u&lic static (oi! main"String argsEF#{ String str307Yello7; String str907Ja (a7; String str:07Yello7; 55 String -erations System.out.-rintln"7String3 00 String:7I str3.eBuals"str:##; System.out.-rintln"7String9 at /n!e2 9H7Istr9.char+t"9##; System.out.-rintln"7Com-are Str9 an! Str:7Istr9.com-areTo"str:##; System.out.-rintln"7Com-are str3 an! str:7Istr3.com-areTo"str:##; System.out.-rintln"7String9 contains JaH 7Istr9.contains"7Ja7##; System.out.-rintln"7String is em-ty _7Istr3.is1m-ty"##; System.out.-rintln"7Sting YashCo!e7I str3.hashCo!e"##; System.out.-rintln"7Su&string o' String37Istr3.su&string"9 :##; System.out.-rintln"7%emo(e whites-aces in String97Istr9.trim"##; System.out.-rintln"7Con(ert to =owerCase7Istr9.to=owerCase"##; System.out.-rintln"7%e-lace a with +7Istr:.re-lace"ZaZZ+Z##; $ $ utDutH 00000000 String3 00 String:true String9 at /n!e2 9H Com-are Str9 an! Str:9 Com-are str3 an! str: String9 contains JaH true String is em-ty _'alse Sting YashCo!ePPP Su&string o' String3l %emo(e whites-aces in String9Ja (a Con(ert to =owerCaseja (a %e-lace a with +Yello Dalin!rome in Ja(a 'or /ntegers an! Strings
-u&lic class Ja(aDalin!rome { -u&lic static (oi! main"String argEF#{ int num0393; String str07teet teet7; System.out.-rintln"7Gi(en Num&er7InumI7is Dalin!romeH7IintDalin!rome"num##; System.out.-rintln"7Gi(en String7IstrI7is Dalin!romeH7IstringDalin!rome"str##; System.out.-rintln"7String re(erse using toChar +rray7#; System.out.-rintln"7Gi(en String7IstrI7is Dalin!romeH7IstringChar+rrayDalin!rome"str##; $ -ri(ate static &oolean stringChar+rrayDalin!rome"String str# { String re(077; char arrEF0str.toChar+rray"#; 'or"int i0arr.lengthK3;iA0;iKK# re(0re(IarrEiF; i'"str.eBuals/gnoreCase"re(## return true; else return 'alse; $ -ri(ate static &oolean stringDalin!rome"String st# { String str3EF0st.s-lit"77#; String re(str077; 'or"int i0str3.lengthK3;iA0;iKK#{ re(strI0str3EiF; $ i'"st.eBuals/gnoreCase"re(str## return true; else return 'alse; $ 55 Checing Num&er Dalin!rome or not -ri(ate static &oolean intDalin!rome"int num# { int n 0 num; int re( 0 ; 'or "int i 0 ; i @0 num; iII# { int r 0 num 3; num 0 num 5 3; re( 0 re( W 3 I r; i 0 ; $ i' "n 00 re(# { return true; $ else { return 'alse; $ $5WW Num&er -alin!rome W5 $ Dolymor-hism in Ja(a Using (erloa!ing an! (erri!!en metho!s *olymorphism ne 'orm an! many im-lementations. /t can &e achei(e! &y using inheritenceo(erloa!ing an! (erri!ing.
#ompile time *olymorphism (er loa!ing untitme *olymorphism $(er ri!ing untime *olymorphism 5+ynamic method dispatch /ts a -rocess in which a call to an o(erri!!en metho!is resol(e! at runtime rather than com-ile itme. ynamic *in!ingH %e'ers to lining o' a -roce!ure call to the co!e to &e e2ecute! in res-onse to the call +lso nown as late &in!ing HCo!e associate! to -roce!ure call is not nown untile the ti me o' the call at runtime. $verloadin0" Two or more metho!s with same name in the same class with !i\erent arguments. •
(erloa!e! metho!s Must change the argument list
•
May change the return ty-e
•
May change the access mo!i,ers.
•
May change the chec!e! e2ce-tions. Example -acage com.oo-s;
-u&lic class (er=oa!ing12am-le { -u&lic int sum"int aint { System.out.-rintln"7/nt /nt7#; return aI&; $ -u&lic !ou&le sum"!ou&le a!ou&le { System.out.-rintln"7ou&le ou&le7#; return aI&; $ -u&lic int sum"int a!ou&le { System.out.-rintln"7/nt ou&le7#; return "int# "aI $ -u&lic static (oi! main"String argsEF#{ (er=oa!ing12am-le oe0new (er=oa!ing12am-le"#; System.out.-rintln"7(erloa!ing metho!7Ioe.sum": R##; System.out.-rintln"7(erloa!ing metho!7Ioe.sum"9. .R##; System.out.-rintln"7(erloa!ing metho!7Ioe.sum"9 .##; $ $ ut-utH 0000000 /nt /nt (erloa!ing metho!3 ou&le ou&le (erloa!ing metho!.9 /nt ou&le (erloa!ing metho!R $verridin0
ccurs in the su&class an! !eclares metho! that has same ty-e arguments as a metho! an! !eclare! &y one o' its su-er class.
•
/t can &e use! 'or !e,ning the &eha(iour o' chil! class.
•
+rgument list same as o(erri!en metho!.
•
Constructors canot &e o(erri!!en.
•
,nal metho!s canot &e o(erri!!en.
•
Static metho! cannot &e o(erri!!en &ut can &e reK!eclare!.
•
su-er"# can &e use! 'or in(oing -arent class"Su-er class# metho!s. Example -acage com.oo-s;
class (er12am-le{ -u&lic (oi! 'un3"#{ System.out.-rintln"7Su-er Ounction37#; $ -u&lic (oi! 'un9"#{ System.out.-rintln"7Su-er Using su-er"# Ounction97#; $ $ -u&lic class (er%i!!ing12am-le e2ten!s (er12am-le{ -u&lic (oi! 'un3"#{ System.out.-rintln"7Su&class Ounction37#; $ -u&lic (oi! 'un9"#{ su-er.'un9"#; System.out.-rintln"7Su&class Ounction97#; $ -u&lic static (oi! main"StringEF args# { (er12am-le or0new (er%i!!ing12am-le"#; (er12am-le oe0new (er12am-le"#; or.'un3"#; oe.'un3"#; or.'un9"#; $ $ ut-utH 00000000 Su&class Ounction3 Su-er Ounction3 Su-er Using su-er"# Ounction9 Su&class Ounction9 /nheritance in &ject rient Drogramming an! Ja(a .nheritance /ts a -rocess where one o&ject acBuire -ro-erites another. /nheritence re!uces the co!e reKusa&lity.
/nheritence can &e achie(e! &y using e2ten!s or im-lemnts eywor! Single /nheritanceH
Class + e2ten!s *{ statements $ 12am-leH 0000000000000 Dulsar is su&class o' *ie TVS is su&class o' *ie. -acage com.oo-s; class Two8heeler{ int count03; -u&lic (oi! setDro-"#{ System.out.-rintln"7ColorH %e! *ran!Hwn7#; $ $ -u&lic class Single/nheritence e2ten!s Two8heeler { -u&lic static (oi! main"String argsEF#{ Two8heeler two0new Two8heeler"#; Single/nheritence si0new Single/nheritence"#; System.out.-rintln"si instanceo' Two8heeler#; System.out.-rintln"7Calling metho! in Su-erClass7#; si.setDro-"#; $ $ ut-ut 0000000 true Calling metho! in Su-erClass ColorH %e! *ran!Hwn -ultiple .nheritance can be acheived by usin0 interace" .nterace in Java /an0ua0e 2#lic@ on lin@ to @now about interaces'
*elow e2am-le contains Single /nheritance an! Multi-le /nheritance Using /nter'aces. -acage com.oo-s; class Two8heeler{ int count03; -u&lic (oi! setDro-"#{ System.out.-rintln"7ColorH %e! *ran!Hwn7#; $ $ inter'ace Car { -u&lic (oi! set*ran!name"String name#; $
inter'ace Yea(eyVechile{ -u&lic (oi! setDro-erites"String -ro-#; $ -u&lic class 8heeler e2ten!s Two8heeler im-lements Car Yea(eyVechile{ -u&lic static (oi! main"String argsEF#{ Two8heeler two0new Two8heeler"#; 8heeler si0new 8heeler"#; System.out.-rintln"si instanceo' Two8heeler#; System.out.-rintln"7Calling metho! in Su-erClass7#; si.setDro-"#; si.set*ran!name"7Oirst7#; si.setDro-erites"7Yea(y=oa!Vechile7#; $ (erri!e -u&lic (oi! set*ran!name"String name# { System.out.-rintln"7*ran! name is7Iname#; $ (erri!e -u&lic (oi! setDro-erites"String -ro-# { System.out.-rintln"7Yea(y Vechile with 4 or 8heels 7I-ro-#; $ $ ut-ut 000000000 true Calling metho! in Su-erClass ColorH %e! *ran!Hwn *ran! name isOirst Yea(y Vechile with 4 or 8heels Yea(y=oa!Vechile inter'aces in &ject riente! Drogramming =anguage interace 0000000000 escri-ti(e set o' metho!s. /m-lements class nee!s to &e im-lemente! metho!s in inter'ace. *roperties o interace 0000000000000000000000000 Canot mar inter'ace as ,nal Cannot instiate inter'ace. e'aultH Metho!s in inter'ace are a&stract ,el!s in inter'ace are static an! ,nal. inter'ace can im-lement class. inter'ace can e2ten! multi-le inter'aces. #lass .mplementin0 .nterace 0000000000000000000000000000 -acage com.oo-s;
inter'ace *ie{ 55,nal static ,el!s as !e'ault int Ca-acity03; 55a&stract metho!s as !e'ault -u&lic (oi! s-ee!"#; -u&lic (oi! -rice"#; $ -u&lic class /nter'ace12am-le im-lements *ie { (erri!e -u&lic (oi! s-ee!"# { System.out.-rintln"7S-ee! o' *ie is 3 MDY7#; $ (erri!e -u&lic (oi! -rice"# { System.out.-rintln"7Drice o' *ie is R7#; $ -u&lic static (oi! main"String argsEF#{ /nter'ace12am-le it0new /nter'ace12am-le"#; it.s-ee!"#; it.-rice"#; $ $ .nterace extends -ultiple .nteraces
-u&lic inter'ace Com-uter { -u&lic (oi! set*ran!name"String name#; $ -u&lic inter'ace esto- e2ten!s Com-uter { -u&lic (oi! setDro-erty"String -ro-#; -u&lic (oi! (iewDro-erty"String i!#; $ -u&lic inter'ace =a-to- e2ten!s Com-uter { -u&lic (oi! setDrocess"!ou&le -rocess#; -u&lic (oi! setScreen"int sie#; $ -u&lic inter'ace =a-to- e2ten!s Com-utere(ice{ statements $ 1nca-sulation in Ja(a Drogramming EncapsulationH is lie in'ormation Yi!ing. Yi!ing the -ro-erites an! &eha(iors o' o&ject an! allowi ng outsi!e access (ia -u&lic metho!s. Example or Encapsulation
0000000000000000000000000000 1m-etails.ja(aH -acage com.oo-s; -u&lic class 1m-etails { -ri(ate int em-i!; -ri(ate String em-name; -u&lic (oi! set1m-i!"int i!#{ em-i!0i!; $ -u&lic int get1m-i!"#{ return em-i!; $ -u&lic (oi! set1m-Name"String name#{ em-name0name; $ -u&lic String get1m-Name"#{ return em-name; $ $ 1nca-sulation12am-le.ja(a -acage com.oo-s; -u&lic class 1nca-sulation12am-le { 5WW W -aram args W5 -u&lic static (oi! main"StringEF args# { 1m-etails em-30new 1m-etails"#; em-3.set1m-i!"3#; em-3.set1m-Name"7Oirst7#; System.out.-rintln"71m-loyee !etails i!H 7Iem-3.get1m-i!"#I7 an! nameH7Iem-3.get1m-Name"##; $ $ ut-ut 0000000000 1m-loyee !etails i!H 3 an! nameHOirst Ja(a 12ce-tion Yan!ling Drogramming uestions
# 8hat are the two ty-es o' 12ce-tions_ +#Chece! 12ce-tions an! Unchece! 12ce-tions. # 8hat is the &ase class o' all e2ce-tions_ +# ja(a.lang.Throwa&le
#/' the o(erri!!en metho! in su-er class + throws OileNotOoun!12ce-tion then the o(erri!ing metho! -resent in class * which is a su&class o' class + can throw /12ce-tion. /' the a&o(e statement true_ +# The o(erri!ing metho! can not throw any chece! e2ce-tion other than the e2ce-tion classes or su&Kclasses o' those classes which are thrown &y the o(erri!!en metho!. /n the scenario !escri&e! in Buestion the metho! in class * can not throw /12ce-tion &ut can throw OileNotOoun!12ce-tion e2ce-tion. #Can we ha(e a try &loc without a catch &loc_ -u&lic class J12am-le { -u&lic static (oi! main"String argsEF#{ int i0; int j04; try { int 0j5i; $ ,nally{ System.out.-rintln"7,nally7#; $ $ $ ut-utH 0000000 ,nally 12ce-tion in threa! 7main7 ja(a.lang.+rithmetic12ce-tionH 5 &y ero at com.test.J12am-le.main"J12am-le.ja(aH33# # 8hat is the !i\erence &etween chece! an! unchece! e2ce-tion han!ling in Ja(a_ 8hat are the !isa!(antages o' chece! e2ce-tion han!ling_ +# Chece! e2ce-tions are the one 'or which there is a chec &y the com-iler that these e2ce-tions ha(e to &e caught or s-eci,e! with throws eywor!. These in! o' e2ce-tions occur &ecause o' con!itions which are out o' control o' the a--lication li e Networ error Oile +ccess enie! etc. Unchece! e2ce-tions are the one which arise &ecause o' logic wri tten &y the !e(elo-er. e.g. Trying to access an array element which !oesnQt e2ist. #12-lain trycatch an! ,nally statements in Ja(a _ The try5catch statement encloses some co!e an! is use! to han!le errors an! e2ce-tions that might occur in that co!e. try { $ catch "12ce-tion e# { $,nally{ $ 12am-le 000000 -u&lic class J12am-le {
-u&lic static (oi! main"String argsEF#{ int i0; int j04; try { int 0j5i; $catch"12ce-tion e# { System.out.-rintln"712ce-tion caught7#; e.-rintStacTrace"#; $ ,nally{ System.out.-rintln"7,nally7#; $ $ $ ut-utH 000000 12ce-tion caught ja(a.lang.+rithmetic12ce-tionH 5 &y ero at com.test.J12am-le.main"J12am-le.ja(aH33# ,nally
# /' there is common co!e to &e e2ecute! in the catch &loc o' 3 e2ce-tions which are thrown 'rom a single try &loc then how that common co!e can &e wr itten with minimum e\ort_ +# /n -re J R a metho! can &e written an! all catch &locs can in(oe this metho! containing the common co!e. /n J R the d o-erator can &e use! in catch &loc in or!er to e2ecute common co!e 'or multi-le e2ce-tions. e.g. catch"S=12ce-tion sBle d /12ce-tion ioe#{$ 4# Ya(e you e(ery create! custom e2ce-tions_ 12-lain the scenario_ +nsH Custom e2ce-tions are use'ul when the J e2ce-tion classes !onQt ca-ture the essence o' erroneous situation which has come u- in the a--lication. + custom e2ce-tion can &e create! &y e2ten!ing any su&class o' 12ce-tion class or &y im-lementing Throwa&le inter'ace. # 8hat is the !i\erence &etween Vali!ation 12ce-tion an! 1rror_ +#Vali!ation is the -rocess o' maing user enter !ata in a 'ormat which the a--lication can han!le. 12ce-tion han!ling is the -rocess when the a--lication logic !i!nQt wor as e2-ecte! &y the Ja(a com-iler. 1rror occurs in a situation where the normal a--lication e2ecution can not continue. Oor e.g. out o' memory. # 8hat is the -ur-ose o' ,nally &l oc_ /n which scenario the co!e in ,nally &loc will not &e e2ecute!_ +# ,nally &loc is use! to e2ecute co!e which shoul! &e e2ecute! irres-ecti(e o' whether an e2ce-tion occurs or not. The in! o' co!e written in a ,nally &loc consists o' clean u- co!e such as closing o' !ata&ase5,le connection. *ut J R has come u- with try with resources &loc which automatically han!les the closing o' resources. # Can a ,nally &loc e2ist with a try &loc &ut without a catch_
+#Les. The 'ollowing are the com&inations try5catch or try5catch5,nally or try5,nally. # 8hat is the !i\erence &etween throw an! throws_ Throw is use! to e2-licitly raise a e2ce-tion within the -rogram the statement woul! &e throw new 12ce-tion"#; throws clause is use! to in!icate the e2ce-tions that are not han!le! &y the metho!. /t must s-eci'y this &eha(ior so the callers o' the metho! can guar! against the e2ce-tions. Throws is s-eci,e! in the metho! signature. /' multi-le e2ce-tions are not han!le! then they are se-arate! &y a comma. the statement woul! &e as 'ollowsH -u&lic (oi! !oSomething"# throws /12ce-tionMy12ce-tion{$ # Yow to create Custom 12ce-tion in Ja(a_ -acage com.test; 55Null12ce-tion is the user e2ce-tion !e,ne! class Null12ce-tion e2ten!s 12ce-tion{ int a; -u&lic Null12ce-tion"int i# { i0a; $ -u&lic String toString"#{ return 7Create! Null12ce-tionH7Ia; $ $ -u&lic class Custom12ce-tion { -u&lic static (oi! i(i!e"int aint throws Null12ce-tion{ int 0a5&; throw new Null12ce-tion"#; $ -u&lic static (oi! main"String argsEF#{ try{ Custom12ce-tion c0new Custom12ce-tion"#; c.i(i!e" 9#; $catch"12ce-tion e#{ System.out.-rintln"7Main Custom12ce-tionmH7 Ie#; $,nally{ System.out.-rintln"7Oinally 12ceuting7#; $ $ $ ut-ut 000000000 Main Custom12ce-tionmHCreate! Null12ce-tionH Oinally 12ceuting
# 8hat are the !i\erences &etween NoClasse'Ooun!1rror an! ClassNotOoun!12ce-tion_ +# NoClasse'Ooun!1rror occurs when a class was 'oun! !uring com-ilation &ut coul! not &e locate! in the class-ath while e2ecuting the -rogram. Oor e2am-leH class + in(oes metho! 'rom class * an! &oth com-ile ,ne &ut &e'ore e2ecuting the -rogram an +NT scri-t !elete! *.class &y mistae. Now on e2ecuting the -rogram NoClasse'Ooun!1rror is thrown. ClassNotOoun!12ce-tion occurs when a class is not 'oun! while !ynamically loa!ing a class using the class loa!ers. Oor e2am-leH The !ata&ase !ri(er is not 'oun! when trying to loa! the !ri(er using Class.'orName"# metho!.
# Can a catch &loc e2ist without a try &loc_ +#No. + catch &loc shoul! always go with a try &loc. # 8hat will ha--en to the 12ce-tion o&ject a'ter e2ce-tion han!ling_ +#12ce-tion o&ject will &e gar&age collecte!. #Yow !oes ,nally &loc !i\er 'rom ,nalie"# metho Oinally &loc will &e e2ecute! whether or not an e2ce-tion is thrown. So it is use! to 'ree resoources. ,nalie"# is a -rotecte! metho! in the &ject class which is calle! &y the JVM just &e'ore an o&ject is gar&age collecte!. # 8hat is the -ur-ose o' throw eywor!_ 8hat ha--ens i' we write >throw null;? statement in a Ja(a -rogram_ +# ?throw? eywor! is use! to reKthrow an e2ce-tion which has &een caught in a catch &loc. The synta2 is >throw e;? where e is the re'erence to the e2ce-tion &eing caught. The e2ce-tion is reKthrown to the client. This eywor! is use'ul when some -art o' the e2ce-tion is to &e han!le! &y the caller o' the metho! in which throw eywor! is use!. The use o' >throw null;? statement causes NullDointer12ce-tion to &e thrown.
# return statement in trycatch an! ,nally _ -u&lic class 12ce-tionemo { -u&lic int ch12ce-tion"int arrEF#{ int 0; int t03c09'0:; try { 'or"0;@;II# System.out.-rintln"7arr 1lement7IarrEF#; System.out.-rintln"7Try Catch7#; return t; $catch"12ce-tion e#{ System.out.-rintln"7Oaile! on e2ce-tion7Ie.getMessage"##; System.out.-rintln"7Catch %etrun7#; return c; $,nally{ System.out.-rintln"7Oinally %eturn7#; return '; $
$ -u&lic static (oi! main"String argsEF#{ int arrEF0{34$; 12ce-tionemo e0new 12ce-tionemo"#; e.ch12ce-tion"arr#; $ $ ut-ut 000000000000 arr 1lement3 arr 1lement4 arr 1lement Oaile! on e2ce-tion: Catch %etrun Oinally %eturnThrea! 12am-le in Ja(a
-u&lic class Threa!12am-le e2ten!s Threa!{ -u&lic synchronie! (oi! run"#{ 'or"int i0;i@33;iII# System.out.-rint"i#; System.out.-rintln"7 7#; $ -u&lic static (oi! main"String argsEF#{ Threa! t30new Threa!12am-le"#; Threa! t90new Threa!12am-le"#; Threa! t:0new Threa!12am-le"#; t3.start"#; t9.start"#; t:.start"#; t3.setDriority"M+<D%/%/TL#; System.out.-rintln"7Threa! 3 Driority7It3.getDriority"##; System.out.-rintln"7Threa! 3 Grou-7It3.getThrea!Grou-"##; System.out.-rintln"7State o' Threa!97It9.getState"##; $ $ +!(antages an! isa!(antages o' selenium automation tool Advanta0es o Selenium
3. 9. :. 4. .
-en Source Su--orts all &rowsers lie /1 Oire'o2 Moilla Sa'ari Su--orts all -erating Systems. Su--orts all -rogramming languages Ja(a%u&yC an! Dython. %un multi-le tests at a time.
+isadvanta0es
3. /!enti' /!enti'ying ying the locato locators rs that that su--or su--ortt comm common on attr attri&ut i&utes es li lie e i! i! names names etc as well as
ut-utH 0000000000 Yi This is ,rst ,le ,le 'or rea!in rea!ing g Than Thans s Oin!ing secon! secon! largest element in array array using ja(a
public class class Second6ighest?leme Second6ighest?lement nt J public static %oid main(String argsUJ int aUNJ1#2#-0#02#2-##0#-0#02M System.out.println(LSecond 6ighest ?lementLVsec6ighest?lement(a M pri%ate static int sec6ighest?lement(intU sec6ighest?lement(intU a J int =rstN#secondN =rstN#secondN
for(int iNiWa.lengthiVVJ iNiWa.lengthiVVJ if (=rst WaiUJ secondN=rst =rstNaiU M if(secondWaiU if(secondWaiU XX =rstENaiU secondNaiU M return second
M M,inding duplicate elements in gi%en array using Set
import /a%a.util.Arrayist /a%a.util.Arrayist import /a%a.util.6ashSet /a%a.util.6ashSet import /a%a.util.Set /a%a.util.Set public class class uplicate&umbersIn uplicate&umbersInArray Array J public static %oid main(String argsUJ int aUNJ1#2#"#-##0 aUNJ1#2#"#-##0#0#-#-#"#"M #0#-#-#"#"M System.out.println(Luplicate elements in ArrayLVdup?lements9singSet(a M pri%ate static ArrayistWIntegerY ArrayistWIntegerY dup?lements9singSet(intU dup?lements9singSet(intU a J ArrayistWIntegerY ArrayistWI ntegerY arrNnew ArrayistWInt egerY( SetWIntegerY sortsetNnew 6ashSetWInteg 6ashSetWIntegerY( erY( for(int iNiWa.lengthiVVJ iNiWa.lengthiVVJ if(sortset.contains(aiU arr.add(aiU else sortset.add(aiU M return arr M M Mselenium.start( B Takes you to the location where selenium ser%er is and runs the ser%er. Mselenium.open( B Takes you to the pro%ied 9+8!ebsite address. Mselenium.getTitle( B :et the title of the current browser window. Mselenium.window,ocus( B :et the focus on the current window. Mselenium.windowGa
Z Selenium operations operations are are highly ;e
Z Start from the the Giddle@ !e can can set the I? to begin begin running running from a speci=c speci=c command in the middle middle of the test case. This also is used for debugging. To set a start point# select a command# rightBclick# and from the conte
Z Z Z Z Z Z
Assertion Statements@ Statements@ Assert command will fail and abort current e
I ha%e been think to post Selenium webdri%er e
1.1 reate a new $a%a *ro/ect
1.2 Sa%e the new pro/ect and %iew the pro/ect in eclipse work space
1." reate a new ,older for library =les and download all the /a%a webdri%er /ar =les. opy the /ar =les from libs folder also ownload@ [email protected]=les8seleniumB/a%aB2.14..Oip
1.- on=gure the build *ath +ight click on the *ro/ect name BY uild *ath BY on=gure uild *ath Add $ars BY Select all the $ars from the ib folder and add it. .
1. reate new *ackage under the src folder
1.0 reate a new /a%a =le
2. opy and paste the below code P 1 2 " 0 3 4 1 11 12 1" 11 10 1 13 14 2 21 22 2" 22 20 2 23 24 " "1 "2 "" "-
package com.test.webdri%er import static org.testng.Assert$9nit.assert?>uals import org.open>a.selenium.y import org.open>a.selenium.!ebri%er import org.open>a.selenium.=refo<.,irefo<ri%er import org.testng.annotations.Afterlass import org.testng.annotations.eforelass import org.testng.annotations.Test public class ri%er J pri%ate !ebri%er dri%er Keforelass public %oid Startup(J dri%er N new ,irefo<ri%er( M KTest (descriptionNL:oogle oginL public %oid :oogleogin( throws ?uals(LSign inL# dri%er.=nd?lement(y.id(LsignInL.getAttribute(L%alueL dri%er.=nd?lement(y.id(L?mailL.send]eys(LHHHHHHHHHL dri%er.=nd?lement(y.id(L*asswdL.send]eys(LHHHHHHHHHHL dri%er.=nd?lement(y.id(LsignInL.click( Thread.sleep(1 dri%er.switchTo(.frame(Lcan%as^frameL dri%er.=nd?lement(y.id(Lgbgs-dnL.click( dri%er.=nd?lement(y.id(Lgb^1L.click( dri%er.switchTo(.defaultontent( assert?>uals(LSign in to :mailL# dri%er.=nd?lement(y.id(LbuttonL.getTe
M " "0 " "3 "4 -
KAfterlass public %oid teardown(J dri%er.>uit( M M
". +un the $a%a ode as Test&: test
-. Riew the ?mailable +eport in Test&: output folder
6ope this help in de%eloping the Selenium webdri%er for beginners. ,or any >uestions post your comments here. I will try to sol%e your problem.
Yow to create test suite using Junit an! ecli-se in selenium There are some scenarios where we nee! to run multi-le test cases. 1ither we can run those test cases in!e-en!ently or together. *ut there are some real time cases where w e nee! to run our test cases in a -articular or!er. /n this case we woul! -re'er Test Suite to com&ine the test cases together an! !eci!e their or!ers an! run those. *elow are the ste-s (" Create a Test Suite class where we create the Test Suites which will call all the test cases in a -articular or!er.
im-ort im-ort im-ort im-ort
junit.'ramewor.Test; junit.'ramewor.TestCase; junit.'ramewor.TestSuite; junit.te2tui.Test%unner;
-u&lic class TestSuite3 e2ten!s TestCase { -u&lic static Test suite"# { TestSuite suite 0 new TestSuite"#; suite.a!!TestSuite" TestCase3.class#; suite.a!!TestSuite" TestCase9.class#; suite.a!!TestSuite" TestCase:.class#; return suite; $ -u&lic static (oi! main"String argEF# { Test%unner.run"suite"##; $ $
Step &" #reate your 7rst test case
im-ort org.o-enBa.selenium.ser(er.%emoteControlCon,guration; im-ort org.o-enBa.selenium.ser(er.SeleniumSer(er; im-ort com.thoughtwors.selenium.W; -u&lic class TestCase3 e2ten!s SeleneseTestCase{ Selenium selenium; -u&lic static ,nal String M+<8+/TT/M1/NMS07P7; -ri(ate SeleniumSer(er seleniumSer(er; -u&lic (oi! setU-"# throws 12ce-tion { %emoteControlCon,guration rc 0 new %emoteControlCon,guration"#; rc.setSingle8in!ow"true#; seleniumSer(er 0 new SeleniumSer(er"rc#; selenium 0 new e'aultSelenium"7localhost7 4444 7Wie2-lore7 7htt-H55www.google.com57#; seleniumSer(er.start"#; selenium.start"#; $ -u&lic (oi! testgoogling"# { selenium.o-en"757#; selenium.ty-e"7B7 7Niraj7#; selenium.clic"7&tnG7#; selenium.waitOorDageTo=oa!"M+<8+/TT/M1/NMS#; assertTrue"selenium.isTe2tDresent"7Niraj7##; $ -u&lic (oi! tearown"# throws /nterru-te!12ce-tion{ selenium.sto-"#; seleniumSer(er.sto-"#; $ $ Step C" #reate your second test case
im-ort org.o-enBa.selenium.ser(er.%emoteControlCon,guration; im-ort org.o-enBa.selenium.ser(er.SeleniumSer(er; im-ort com.thoughtwors.selenium.W; -u&lic class TestCase9 e2ten!s SeleneseTestCase{ Selenium selenium; -u&lic static ,nal String M+<8+/TT/M1/NMS07P7; -ri(ate SeleniumSer(er seleniumSer(er; -u&lic (oi! setU-"# throws 12ce-tion { %emoteControlCon,guration rc 0 new %emoteControlCon,guration"#; rc.setSingle8in!ow"true#; seleniumSer(er 0 new SeleniumSer(er"rc#; selenium 0 new e'aultSelenium"7localhost7 4444 7Wie2-lore7 7htt-H55www.google.com57#; seleniumSer(er.start"#; selenium.start"#; $
-u&lic (oi! testgoogling"# { selenium.o-en"757#; selenium.ty-e"7B7 7Niraj umar7#; selenium.clic"7&tnG7#; selenium.waitOorDageTo=oa!"M+<8+/TT/M1/NMS#; assertTrue"selenium.isTe2tDresent"7Niraj umar7##; $ -u&lic (oi! tearown"# throws /nterru-te!12ce-tion{ selenium.sto-"#; seleniumSer(er.sto-"#; $ $
Step 4" #reate your third test case
im-ort org.o-enBa.selenium.ser(er.%emoteControlCon,guration; im-ort org.o-enBa.selenium.ser(er.SeleniumSer(er; im-ort com.thoughtwors.selenium.W; -u&lic class TestCase: e2ten!s SeleneseTestCase{ Selenium selenium; -u&lic static ,nal String M+<8+/TT/M1/NMS07P7; -ri(ate SeleniumSer(er seleniumSer(er; -u&lic (oi! setU-"# throws 12ce-tion { %emoteControlCon,guration rc 0 new %emoteControlCon,guration"#; rc.setSingle8in!ow"true#; seleniumSer(er 0 new SeleniumSer(er"rc#; selenium 0 new e'aultSelenium"7localhost7 4444 7Wie2-lore7 7htt-H55www.google.com57#; seleniumSer(er.start"#; selenium.start"#; $ -u&lic (oi! testgoogling"# { selenium.o-en"757#; selenium.ty-e"7B7 7htt-H55www.automationtrics.&logs-ot.com7#; selenium.clic"7&tnG7#; selenium.waitOorDageTo=oa!"M+<8+/TT/M1/NMS#; assertTrue"selenium.isTe2tDresent"7htt-H55www.automationtrics.&logs-ot.com7##; $ -u&lic (oi! tearown"# throws /nterru-te!12ce-tion{ selenium.sto-"#; seleniumSer(er.sto-"#; $ $ Step !" un your Test Suite Go to your Test Suite class an! right clic on that an! run as Junit Test.
This will run the TestCase3 then TestCase9 then TestCase: /' you want to e2ecute your test cases in some s-eci,c or!er then you call them in that or!er lie.
suite.a!!TestSuite" TestCase:.class#; suite.a!!TestSuite" TestCase9.class#; suite.a!!TestSuite" TestCase3.class#; +&o(e will run the TestCase: ,rst then TestCase9 then TestCase3. /ntro!uction to Selenium 8e&ri(er Selenium 8e&ri(er lets you write co!e to -er'orm automate! tests o' we& -ages. Unli eSelenium /1 "which recor!s clics that you -er'orm in the &rowser an! -lays them &ac# 8e&ri(er reBuires you to write co!e to connect to the +D/ which controls the &rowser. The co!e can &e written in Ja(a C or a 'ew other languages. The Selenium 8e&ri(er !ocumentation has some goo! instructions &ut while 'ollowing them / ran into a 'ew hitches &ut was a&le to ,n! the answers / nee!e! 'rom other -ages on the internet. Yo-e'ully / ha(e re'erence! those other -ages correctly. $btainin0 Selenium 1eb+river or Use with Java 3. /nstall +-ache Ma(en. This will &e use! 'or !ownloa!ing a -roject that can &e im-orte! into 1cli-se or Net*eans. 9. Create the -om.2ml ,le shown on the 8e&ri(er !ocumentation -age. Mae sure to u-!ate the
4. . P. R. o
.
/nstructions 'or a!!ing the M9%1D class-ath (aria&le in 1cli-se. Lour -roject shoul! ha(e no errors at this -oint. +!! a new class to your -roject with a static main metho!. %un your a--lication to see i' it will e(en run. /' you get the errorH 7Editor does not contain a main type7 thenH Lou nee! to tell 1cli-se where the Source is 'or your -roject. "Oor instructions re'er to a(e McueenZs res-onse on Co!e%anch on May 99 9.# Lour em-ty a--lication shoul! at least run at this -oint.
. /n the main"# metho! write your test co!e. %e'er to this e2am-le Selenium 8e&ri(er co!e. 3. /' you are using the Fireox !ri(er in your co!e then !o the 'ollowing &e'ore running or you will get an errorH Mae sure Oire'o2 is installe!. o +!! the -ath to Oire'o2 in your systemZs en(ironment path (aria&le. o %estart 1cli-se
o
33. /' you are using the .nternet Explorer !ri(er in your co!e then !o the 'ollowing &e'ore running or you will get an errorH Mae sure to !ownloa! an! uni- The /nternet 12-lorer ri(er Ser(er on your machine. o +!! the -ath to it in your systemZs en(ironment -ath (aria&le. %estart 1cli-se.
o o
39. /' you are using the Chrome !ri(er in your co!e then !o the 'ollowing &e'ore running or you will get an errorH ownloa! an! uni- the Chrome !ri(er. o +!! the -ath to it in your systemZs en(ironment -ath (aria&le. o o o
%estart 1cli-se. %un your a--lication.
+ssuming you ha(e an actual test scri-t set u- in your co!e Oire'o2 or /nternet 12-lorer "!e-en!ing on which &rowser !ri(er you use! in your co!e# shoul! launch at this -oint an! the test shoul! &e -er'orme! automatically. .ntroduction Selenium is a -o-ular 'ramewor 'or testing the user inter'ace "U/# o' a we& a--lication. /t is an e2tremely -ower'ul tool 'or running en!KtoKen! 'unctional tests. Lou can write tests in se(eral -rogramming languages an! Selenium e2ecutes them into one or multi-le &rowsers. Selenium herea'ter calle! Selenium 3 is not the only tool a&le to automate 'unctional tests in a &rowser. 8e&ri(er create! &y Simon Stewart "'rom Google# is a -roject with a similar goal. To control the &rowser 8e&ri(er relies on in!e-en!ent clients using nati(e su--ort. 8e&ri(er o\ers only Ja(a &in!ings an! !oes not su--ort the same num&er o' &rowsers as Selenium 3. Selenium ( 1eb+river ; Selenium & Selenium 3 an! 8e&ri(er merge! to -ro!uce a &etter -ro!uctfSelenium 9 or Selenium 8e&ri(er which was release! in 933. Selenium 9 has the clean an! o&jectKoriente! +D/s 'rom 8e&ri(er an! interacts with &rowsers in the &est way -ossi&le 'or that &rowser. Selenium 9 !oes not use a Ja(aScri-t san!&o2 an! it su--orts a wi!e range o' &rowsers an! multi-le language &in!ings. +t the time o' this writing Selenium 9 -ro(i!es !ri(ers ' orH Moilla Oire'o2 Google Chrome Microso't /nternet 12-lorer -era +--le iDhone +n!roi! &rowsers 8ith Selenium 9 you can write tests in Ja(a C %u&y an! Dython. Selenium 9 also o\ers a hea!less !ri(er &ase! on YtmlUnit which is a Ja(a 'ramewor 'or testing we& a--lications. YtmlUnit is really 'ast &ut it is not realistic as a !ri(er associate! with a real &rowser. +t the moment Selenium 9 is still un!er !e(elo-ment as minor issues are &eing resol(e!. The current (ersion is 9.. ri(ers 'or Sa'ari an! *lac&erry shoul! &e integrate! in the near ' uture. /n this article learn how to use Selenium 9 to test we& a--lications. 12am-les show how to remotely im-lement tests. =earn also how to mo(e your written tests 'rom Selenium 3 to Selenium 9. ownloa! the source co!e use! in this article. ,ac@ to top Gettin0 started with Selenium & /n this section learn how to use the Selenium 9 'ramewor 'or a relati(ely sim-le test o' a we& a--lication. Ja(a is the language 'or the !e(elo-ment en(ironment. Lou nee! the seleniumKja(aK @(ersionA.jar containing the Ja(a &in!ing "see %esources to !ownloa!#. /n a Ma(en -roject you just nee! to inclu!e the right !e-en!ency i n your -om.2ml as shown in =isting 3. o
• • • • • •
/istin0 (" Selenium8%ava dependency
@!e-en!encyA @grou-/!Aorg.seleniumhB.selenium@5grou-/!A @arti'act/!AseleniumKja(a@5arti'act/!A @(ersionA9..@5(ersionA @5!e-en!encyA
Now you can start writing tests. The main com-onent in the 8e&ri(er +D/ is the 8e&ri(er inter'ace. There is an im-lementation o' this common inter'ace 'or each &rowser a(aila&le. Oor instance the Oire'o2ri(er class will tae care o' controlling Moilla Oire'o2. =isting 9 shows how to instantiate a s-eci,c im-lementation insi!e your test. Lou can use the test 'ramewor that &est suits your nee!s such as JUnit or TestNG. /istin0 &" Fireox+river instantiated
-u&lic class Selenium912am-le3Test { Test -u&lic (oi! test"# { 55 /nstantiate a we&ri(er im-lementation 8e&ri(er we&!ri(er 0 new Oire'o2ri(er"#; $ $
To loa! the -age to test use the get"# metho!. /n =isting : the GitYu& home-age "htt-sH55githu&.com# is loa!e! into the Oire'o2 instance create! -re(iously. /istin0 C" /oad the pa0e under test
8e&ri(er we&!ri(er 0 new Oire'o2ri(er"#; we&!ri(er.get"htt-sH55githu&.com#;
Lou can now mae some assertions on the -age just loa!e!. Su--ose you want to test that the -age title is eBual to 7GitYu& K Social Co!ing7 as in =isting 4. 8e&ri(er o\ers the getTitle"# metho!; you can le(erage the chosen testing 'ramewor to mae an assertion. /istin0 4" Assertion on the pa0e title
+ssert.assert1Buals"7GitYu& K Social Co!ing7 we&!ri(er.getTitle"##;
+'ter you ,nish the test itZs a goo! -ractice to ill the 8e&ri(er instance using the Buit"# metho! as shown in =isting . /istin0 !" >illin0 the 1eb+river instance
we&!ri(er.Buit"#;
Oire'o2ri(er is just one o' the 8e&ri(er im-lementations a(aila&le. Lou coul! e2ecute the same test using the Chromeri(er to run the test insi!e Chrome. =isting P shows the 'ull e2am-le using the Chromeri(er. /istin0 " #hrome+river sample
-u&lic class Selenium912am-le9Test {
Test -u&lic (oi! test"# { System.setDro-erty"7we&!ri(er.chrome.!ri(er7 7src5main5resources5!ri(ers5chrome5chrome!ri(erKmac7#; 55 /nstantiate a we&ri(er im-lementation 8e&ri(er we&!ri(er 0 new Chromeri(er"#;
we&!ri(er.get"htt-sH55githu&.com#; +ssert.assert1Buals"7GitYu& K Social Co!ing7 we&!ri(er.getTitle"##; $
$
*e'ore instantiating the Chromeri(er you nee! to set the 7we&!ri(er.chrome.!ri(er7 system -ro-erty. This -ro-erty -oints to the location o' the Chromeri(er ,le 'or your S "see %esources to !ownloa!#. The e2am-le in =isting P uses the (ersion 'or the Mac; (ersions ' or 8in!ows an! =inu2 are also a(aila&le. To e2ecute the same test insi!e /nternet 12-lorer you nee! to use an instance o' the /nterent12-lorerri(er class as shown in =isting R. /istin0 K" .nternetExplorer+river instantiation
8e&ri(er we&!ri(er 0 new /nternet12-lorerri(er"#;
8hen using /nterenet12-lorerri(er you might encounter a security issue sayingH 7Drotecte! Mo!e must &e set to the same (alue "ena&le! or !isa&le!# 'or all ones.7 To o(ercome the -ro&lem you can set a s-eci,c ca-a&ility as shown in =isting . /istin0 L" Security capability set or .nternet Explorer
esire!Ca-a&ilities ca-a&ility0esire!Ca-a&ilities.internet12-lorer"#; ca-a&ility.setCa-a&ility" /nternet12-lorerri(er./NT%UC1O=+/N1SS*L /GN%/NGS1CU%/TLM+/NS true#; 8e&ri(er we&!ri(er 0 new /nternet12-lorerri(er"ca-a&ility#;
To e2ecute a test insi!e -era you nee! to instantiate the -erari(er class which was !e(elo-e! !irectly &y -era. %emem&er to inclu!e the J+% containing the !ri(er insi!e your -roject. /' youZre using Ma(en you just nee! to a!! the !e-en!ency in =isting . /istin0 M" $pera+river dependency
@!e-en!encyA @grou-/!Acom.o-era@5grou-/!A @arti'act/!Ao-era!ri(er@5arti'act/!A @(ersionA.R.:@5(ersionA @5!e-en!encyA
+!!itional con,gurations are reBuire! to run the tests insi!e an iDhone or +n!roi! &rowser emulator. ,ac@ to top Testin0 with Selenium & 8ith Selenium 9 you can &uil! tests that are more com-le2 than those in the -re(ious section. /n this section youZll test that the to- na(igation in the GitYu& home-age has ,(e list itemsH Signu- an! Dricing 12-lore GitYu& Oeatures *log an! =ogin. Oigure 3 shows the Githu& home-age.
Fi0ure (" Github homepa0e
%e(iew the YTM= co!e &ehin! the to- na(igationfshown in =isting 3. /istin0 ()" T-/ code behind the top navi0ation
@htmlA @hea!A ... @5hea!A @&o!y class07logge!out en(K-ro!uction7A @!i( i!07main7A @!i( i!07hea!er7 class07true7A ... @!i( class07to-search7A @ul class07na( logge!out7A @li class07-ricing7A @a hre'07htt-sH55githu&.com5-lans7ASignu- an! Dricing@5aA @5liA @li class07e2-lore7A @a hre'07htt-sH55githu&.com5e2-lore7A12-lore GitYu&@5aA @5liA @li class07'eatures7A @a hre'07htt-sH55githu&.com5'eatures7AOeatures@5aA @5liA @li class07&log7A
@a hre'07htt-sH55githu&.com5&log7A*log@5aA @5liA @li class07login7A @a hre'07htt-sH55githu&.com5login7A=ogin@5aA @5liA @5ulA @5!i(A ... @5!i(A ... @5!i(A ... @5&o!yA @5htmlA
Lou can le(erage the 8e&ri(er +D/ to retrie(e 'rom insi!e the YTM= co!e the elements you nee! to test. The ,n!1lement"#an! ,n!1lements"# metho!s return an instance or a list o' instances o' the common inter'ace 8e&1lement. The 8e&1lementinter'ace in a clean an! o&jectKoriente! manner is use! 'or all o' the elements in a -age. There are !i\erent strategies use! in the +D/ to locate a U/ element. The strategies are re-resente! &y the !i\erent ty-es o' -arameters -asse! i nto the,n!1lement"# an! ,n!1lements"# metho!s. =isting 33 shows the !i\erent strategies a!o-te! through the !i\erent metho!s a--lie! to the a&stract class *y. /istin0 ((" Usin0 the 7ndElement2' method
8e&1lement element3 8e&1lement element9 8e&1lement element: 8e&1lement element4 8e&1lement element 8e&1lement elementP 8e&1lement elementR 8e&1lement element
0 we&!ri(er.,n!1lement"*y.i!"7hea!er7##; 0 we&!ri(er.,n!1lement"*y.name"7name7##; 0 we&!ri(er.,n!1lement"*y.tagName"7a7##; 0 we&!ri(er.,n!1lement"*y.2-ath"755aEtitle0ZlogoZF7##; 0 we&!ri(er.,n!1lement"*y.cssSelector"7.'eautures7##; 0 we&!ri(er.,n!1lement"*y.linTe2t"7*log7##; 0 we&!ri(er.,n!1lement"*y.-artial=inTe2t"7%u&y7##; 0 we&!ri(er.,n!1lement"*y.className"7login7##;
Using one o' the strategies in =isting 33 you can start writing the test to retrie(e the ,rst elementsH the =/ tags insi!e the U= tag with the na( class. =isting 39 uses <-ath "*y.2-ath"##. /istin0 (&" path
=ist@8e&1lementA we&1lements 0 we&!ri(er.,n!1lements"*y .2-ath"755ulEclass0Zna( logge!outZF5li7##;
=isting 3: uses CSS selectors "*y.cssSelector"## to retrie(e the =/ tags. /istin0 (C" #SS selector
=ist@8e&1lementA we&1lements 0 we&!ri(er.,n!1lements"*y .cssSelector"7ul.na( li7##;
+t this -oint you can mae the ,rst assertion on the num&er o' items retrie(e! as shown in =isting 34. /istin0 (4" Assertion on the number o items
+ssert.assert1Buals" we&1lements.sie"##;
The -re(ious ste- (eri,e! that the num&er o' =/ tags is eBual to ,(e. The ne2t ste- is to retrie(e each anchor "+ tag# insi!e each =/ tag. =isting 3 shows how to get the anchor insi!e the ,rst =/. The tagName "*y.tagName"## strategy is use! 'or this case. /istin0 (!" etrievin0 A anchor inside the 7rst /. ta0
8e&1lement anchor3 0 we&1lements.get"#.,n!1lement"*y.tagName"7a7##;
/n a similar 'ashion you can collect all ,(e anchors as shown in =isting 3P. /istin0 (" etrievin0 all the anchors inside /. ta0
8e&1lement anchor3 8e&1lement anchor9 8e&1lement anchor: 8e&1lement anchor4 8e&1lement anchor
0 0 0 0 0
we&1lements.get"#.,n!1lement"*y.tagName"7a7##; we&1lements.get"3#.,n!1lement"*y.tagName"7a7##; we&1lements.get"9#.,n!1lement"*y.tagName"7a7##; we&1lements.get":#.,n!1lement"*y.tagName"7a7##; we&1lements.get"4#.,n!1lement"*y.tagName"7a7##;
+t this stage you can (eri'y i' the te2t insi!e the anchors corres-on!s to the e2-ecte! string. To retrie(e the te2t insi!e a tag 8e&ri(er -ro(i!es the getTe2t"# metho!. =isting 3R shows the 'ull test metho! with the assertions at the &ottom o' the test. /istin0 (K" #omplete test
Test -u&lic (oi! test"# { 8e&ri(er we&!ri(er 0 new Oire'o2ri(er"#; we&!ri(er.get"7htt-sH55githu&.com7#; =ist@8e&1lementA we&1lements 0 we&!ri(er.,n!1lements"*y .2-ath"755ulEclass0Zna( logge!outZF5li7##; +ssert.assert1Buals" we&1lements.sie"##; 55 %etrie(e the anchors 8e&1lement anchor3 0 we&1lements.get"#.,n!1lement"*y.tagName"7a7##; 8e&1lement anchor9 0 we&1lements.get"3#.,n!1lement"*y.tagName"7a7##; 8e&1lement anchor: 0 we&1lements.get"9#.,n!1lement"*y.tagName"7a7##; 8e&1lement anchor4 0 we&1lements.get":#.,n!1lement"*y.tagName"7a7##; 8e&1lement anchor 0 we&1lements.get"4#.,n!1lement"*y.tagName"7a7##; 55 +ssertions +ssert.assert1Buals"7Signu- an! Dricing7 anchor3.getTe2t"##; +ssert.assert1Buals"712-lore GitYu&7 anchor9.getTe2t"##; +ssert.assert1Buals"7Oeatures7 anchor:.getTe2t"##; +ssert.assert1Buals"7*log7 anchor4.getTe2t"##; +ssert.assert1Buals"7=ogin7 anchor.getTe2t"##; we&!ri(er.Buit"#; $
+'ter launching this test a new Oire'o2 win!ow will o-en an! stay o-en until all o' the assertions are e2ecute!. ,ac@ to top Testin0 remotely with Selenium Grid &
Lou can either locally or remotely run tests in Selenium 9. To run remotely the tests nee! to use a s-eci,c im-lementation o' the8e&ri(er inter'ace calle! %emote8e&ri(er. Lou can s-eci'y the &rowser to &e run using the esire!Ca-a&ilities class. =isting 3 shows an e2am-le. /istin0 (L" emote1eb+river and +esired#apabilities classes
esire!Ca-a&ilities ca-a&ilities 0 new esire!Ca-a&ilities"#; ca-a&ilities.set*rowserName"7,re'o27#; ca-a&ilities.setVersion"7R7#; ca-a&ilities.setDlat'orm"7M+C7#; 8e&ri(er we&!ri(er 0 new %emote8e&ri(er"ca-a&ilities#;
8ith the esire!Ca-a&ilities class you can s-eci'y the &rowser name the -lat'orm an! &rowser (ersion. Lou can also s-eci'y many other ca-a&ilities the &rowser can su--ort. /' you want to remotely e2ecute structure! tests an! run multi-le &rowsers "an! -ossi&ly (arious (irtual machines# Selenium Gri! o\ers a goo! solution. Selenium Gri! 9 -ro(i!es an in'rastructure where each no!e re-resenting a !i\erent &rowser registers itsel' against a hu&. Singular tests wi ll in(oe a hu& which is in charge o' !is-atching each reBuest to the right &rowser. Yu& an! no!es can run on !i\erent (irtual machines. To test remotely youZll nee! to !ownloa! seleniumKser(erKstan!aloneK@(ersionA.jar on each machine youZre going to use. To install a hu& on a machine go into the 'ol!er where you !ownloa!e! the reBuire! J+% an! launch the comman! in =isting 3. /istin0 (M" Startin0 the hub
ja(a Kjar seleniumKser(erKstan!aloneK9...jar _role hu&
Lou can access the Selenium Gri! 9 console at htt-H55localhostH44445gri!5console where all the no!es a(aila&le will &e liste!. To register a no!e sim-ly launch a comman! as shown in =isting 9. /istin0 &)" Node re0istered a0ainst the hub
ja(a Kjar seleniumKser(erKstan!aloneK9...jar Krole we&!ri(er _hu& htt-H55localhostH44445gri!5register K-ort P
The comman! in =isting 9 registers &y !e'ault se(en &rowsersH ,(e Oire'o2 instances one Chrome instance an! one /nternet 12-lorer instance. Lou can target a s-eci,c &rowser on a s-eci,c -ort as !emonstrate! in =isting 93. /istin0 &(" Fireox K instance re0istered on the hub
ja(a Kjar seleniumKser(erKstan!aloneK9...jar Krole we&!ri(er Khu& htt-H55localhostH44445gri!5register K-ort P K&rowser &rowserName0chrome(ersion034-lat'orm0M+C
+'ter registering a 'ew &rowsers the Selenium Gri! 9 console shoul! loo lie Oigure 9. Fi0ure &" Selenium Grid & console view
To use the gri! you nee! to s-eci'y insi!e your test cases the U%= o' the hu& an! the &rowser you want to control. =isting 99shows where the constructor o' the %emote8e&ri(er class acce-ts the U%= o' the hu& an! an instance o'esire!Ca-a&ilities !e,ning the s-eci,c &rowser. /istin0 &&" emote1eb+river instantiation
esire!Ca-a&ilities ca-a&ility 0 new esire!Ca-a&ilities"#; ca-a&ility.set*rowserName"7chrome7#; ca-a&ility.setVersion"7347#; ca-a&ility.setDlat'orm"Dlat'orm.M+C#; 8e&ri(er we&!ri(er 0 new %emote8e&ri(er"new U%="7htt-H55localhostH44445w!5hu&7# ca-a&ility#;
/n this case the hu& will launch the no!e associate! to Chrome Version 34 "-re(iously registere! in =isting 93#. Selenium Gri! 9 is also &acwar! com-ati&le with Selenium 3. Lou can register Selenium 3 %C no!es "-art o' the Selenium 3 in'r astructure# against the hu& as shown in =isting 9:. /istin0 &C" Selenium ( # node re0istration
ja(a _jar seleniumKser(erKstan!aloneK9...jar Krole rc _hu& htt-H55localhostH44445gri!5register K-ort R ,ac@ to top -i0ratin0 tests to Selenium & rom Selenium (
/' you nee! to migrate written tests 'rom Selenium 3 to Selenium 9 the transition is Buite smooth. The Selenium 3 +D/s are e-t un!erneath the new +D/s maing Selenium 9 com-letely &acwar! com-ati&le. /tZs easy to con(ert your test 'rom Selenium 3 into Selenium 9 thans to the 8e&ri(er*ace!Selenium class. /t taes an instance o' a 8e&ri(er an! the U%= un!er test as -arameters an! it returns a Selenium instance. =isting 94 shows the same e2am-le as in =isting 3P &ut using the Selenium 3 +D/ integrate! in Selenium 9. /istin0 &4" Selenium ( inte0rated in Selenium &
Test -u&lic (oi! test"# { String url 0 7htt-sH55githu&.com7; 8e&ri(er we&!ri(er 0 new Oire'o2ri(er"#; we&!ri(er.get"url#; Selenium selenium 0 new 8e&ri(er*ace!Selenium"we&!ri(er url#; selenium.o-en"url#; 55 Get the num&er o' =/s Num&er lis 0 selenium.get<-athCount"755ulEclass0Zna( logge!outZF5li7#; +ssert.assert1Buals" lis.intValue"##; 55 %etrie(e the te2t insi!e the anchors String anchor3Te2t 0 selenium.getTe2t"755ulEclass0Zna( logge!outZF5liE3F5a7#; String anchor9Te2t 0 selenium.getTe2t"755ulEclass0Zna( logge!outZF5liE9F5a7#; String anchor:Te2t 0 selenium.getTe2t"755ulEclass0Zna( logge!outZF5liE:F5a7#; String anchor4Te2t 0 selenium.getTe2t"755ulEclass0Zna( logge!outZF5liE4F5a7#; String anchorTe2t 0 selenium.getTe2t"755ulEclass0Zna( logge!outZF5liEF5a7#; +ssert.assert1Buals"7Signu- an! Dricing7 anchor3Te2t#; +ssert.assert1Buals"712-lore GitYu&7 anchor9Te2t#; +ssert.assert1Buals"7Oeatures7 anchor:Te2t#; +ssert.assert1Buals"7*log7 anchor4Te2t#; +ssert.assert1Buals"7=ogin7 anchorTe2t#; we&!ri(er.Buit"#; $
Selenium 9 has an increase! 'ocus on !e(elo-ers. /t has a cleaner +D/ than Selenium 3 as e(i!ence! &y the getTe2t"# an!get<-athCount"# metho! signatures. The Selenium 9 +D/ is also more o&jectK oriente!. Oor e2am-le you are not allowe! to !eal with U/ element o&jects only strings.
• • •
SE/EN.U- 1E,+.?E T.*S O T.#>S 8ritten &y Va!im Cha!yu d Ori!ay 9 +-ril 939 Drint 1mail +!! new comment %ate this item
•
•
3
•
9
•
:
•
4
•
": (otes#
veriyText*resent or Selenium 1eb+river
There is no metho! (eri'yTe2tDresent in Selenium 8e&ri(er so i' you nee! to chec te2t on the -age you can use the 'ollowing metho!sH -u&lic &oolean (eri'yTe2tDresent"String te2t#{ return !ri(er.getDageSource"#.contains"te2t#; $ or -u&lic &oolean (eri'yTe2tDresent"String te2t#{ return !ri(er.,n!1lement"*y.tagName"7&o!y7##.getTe2t"#.contains"te2t#; $ 1or@in0 with rames
To wor with 'rames you can use the 'ollowing metho!s. / recommen! the 'ollowing metho!H 8e&1lement myOrame 0 !ri(er.,n!1lement"*y.name"7i'ramecan(as7##; !ri(er.switchTo"#.'rame"myOrame#; Lou can switch to a 'rame &y nameH !ri(er.switchTo"#.'rame"7'rame7# +s well as &y in!e2H !ri(er.switchTo"#.'rame"#; 1or@in0 with windows
To wor with win!ows / recommen! using the 'ollowing metho!H -u&lic (oi! switchTo8in!ow"int num&er8in!ow# { String han!le 0 !ri(er.get8in!owYan!les"#.to+rray"#Enum&er8in!owF.toString"#; !ri(er.switchTo"#.win!ow"han!le#; $
Use the implicit waitin0
/ recommen! always inclu!e im-licit waiting where they are not nee!e! just turn them o\. -u&lic (oi! turnn/m-licitly8ait "int timeout# { !ri(er.manage"#.timeouts"#.im-licitly8ait"timeout TimeUnit.S1CNS#; $ -u&lic (oi! turn\/m-licitly8ait "# { !ri(er.manage"#.timeouts"#.im-licitly8ait" TimeUnit.S1CNS#; $ Usin0 +ra0 and +rop
rag an! ro- is -er'orme! in that wayH +ctions &uil!er 0 new +ctions"!ri(er#; +ction !rag+n!ro- 0 &uil!er.clic+n!Yol!"some1lement#
.mo(eTo1lement"other1lement#
.release"other1lement#
.&uil!"#;
!rag+n!ro-.-er'orm"#; Files uploadin0
/' you ha(e a ,le u-loa! ,el! "@in-ut ty-e0,leA# then im-lement a ,le !ownloa! in the 'ollowing wayH ,le/n-ut.sen!eys",le#; Y8 T /NT1G%+T1 S/U=/ SC%/DT 8/TY S1=1N/UM 81*%/V1% Doste! on +-r 3 93: &y %oman Siuli is a ro&ust an! -ower'ul tool to automate an! tests user inter'aces screenshots. The core o' Siuli Scri-t is written in Ja(a which means you can use Siuli Scri-t as a stan!ar! J+V+ li&rary in your -rogram. This article lets you now how to !o that. Siuli is a ro&ust an! -ower'ul tool to automate an! tests user inter'aces screenshots. The core o' Siuli Scri-t is written in Ja(a which means you can use Siuli Scri-t as a stan!ar! J+V+ li&rary in your -rogram. This article lets you now how to !o that. (" ownloa! an! install Siuli using the sel'Ke2tracting installer"htt-H55www.siuli.org5!ownloa!.html#. NoteH nly :9K&it (ersion is -ro(i!e! 'or using as a stan!ar! J+V+ li&rary. *ut S/U=/ /1 coul! run on &oth :9K&it an! P4K&it 8in!ows systems. &" Create new Ja(a -roject "use 1cli-se as an e2am-le#H
C" Oill -roject name an! clic OinishH
4" Create new classH
!" Oill class name an! clic OinishH