Selenium Real Time Scenarios
Selenium Real Time Scenarios
Selenium Real Time Scenarios
ether a small example belo" that uses the ne" API to lo! into t"o "eb based e#mail clients and send an e#mail. WebDriverTestBase.java package tests; import import import import import import import org.openqa.selenium.WebDriver; org.openqa.selenium.firefox.FirefoxDriver; org.openqa.selenium.support.ui.Wait; org.openqa.selenium.support.ui.WebDriverWait; org.testng.Assert; org.testng.annotations.AfterClass; org.testng.annotations.BeforeClass;
public class WebDriverTestBase { public static FirefoxDriver driver; public static Wait wait; @BeforeClass(alwaysRun = true) protected void startWebDriver() { driver = new FirefoxDriver(); wait = new WebDriverWait(driver, 120); } @AfterClass(alwaysRun = true) protected void closeSession() { driver.close(); } public static void assert !uals(Object actual, Object ex"ected) { Assert.assertEquals(actual, ex"ected); }
} VisibilityOfElementLocated.java package tests; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.support.ui.ExpectedCondition; public class #isibility$f le%ent&ocated implements x"ectedCondition { By findCondition; #isibility$f le%ent&ocated(By by) { this.findCondition = by; } public Boolean a""ly(WebDriver driver) { driver.findElement(this.findCondition); return Boolean.valueOf(true); } } WebmailTest.java package tests; import org.openqa.selenium.By; import org.testng.annotations.Test; public class Web%ailTest extends WebDriverTestBase { //variables public static final String 'A($$) *A+& = "[email protected]"; public static final String ($T*A+&) *A+& = "[email protected]";
@Test(descri"tion = "Sends an e-mail from Yahoo account") public void sendFro%'a,oo() { //new message variables String to = ($T*A+&) *A+&; String sub-ect = "Test Sending Email Message From Yahoo"; String %essa.e = "This is a test e-mail from Yahoo"; //login to yahoo driver.get("http://mail.yahoo.com/"); driver.findElement(By.id("username")).sendKeys('A($$) *A+&); driver.findElement(By.id("passwd")).sendKeys("mytestpw"); driver.findElement(By.id(".save")).click(); //create new message driver.findElement(By.id("compose_button_label")).click(); wait.until(new #isibility$f le%ent&ocated(By.xpath("id('_testTo_label')/ancestor::tr[1]//textare a"))); //send test message
driver.findElement(By.xpath("id('_testTo_label')/ancestor::tr[1]//textarea")).sendKeys( to);
driver.findElement(By.xpath("id('_testSubject_label')/ancestor::tr[1]//input")).sendKeys (sub-ect); driver.switchTo().frame("compArea_test_"); driver.findElement(By.xpath("//div")).sendKeys(%essa.e); driver.switchTo().defaultContent(); driver.findElement(By.id("SendMessageButton_label")).click(); //WARNING! sometimes a captcha is displayed here wait.until(new #isibility$f le%ent&ocated(By.xpath("//nobr[contains(text(), 'Message Sent')]")));
} @Test(descri"tion = "Sends an e-mail from Hotmail account") public void sendFro%(ot%ail() { //new message variables String to = 'A($$) *A+&; String sub-ect = "Test Sending Email Message From Hotmail"; String %essa.e = "This is a test e-mail from Hotmail"; //login to hotmail driver.get("http://mail.live.com/"); driver.findElement(By.name("login")).sendKeys(($T*A+&) *A+&); driver.findElement(By.name("passwd")).sendKeys("mytestpw"); if (driver.findElement(By.name("remMe")).isSelected()) { driver.findElement(By.name("remMe")).click(); } driver.findElement(By.name("SI")).click(); //create new message driver.switchTo().frame("UIFrame"); driver.findElement(By.id("NewMessage")).click(); //send test message driver.findElement(By.id("AutoCompleteTo$InputBox")).sendKeys(to); driver.findElement(By.id("fSubject")).sendKeys(sub-ect); driver.switchTo().frame("UIFrame.1"); driver.findElement(By.xpath("//body")).sendKeys(%essa.e); driver.switchTo().frame("UIFrame"); driver.findElement(By.id("SendMessage")).click();
Example Two: Window Handle example wit seleni!m webdriver " !sin# $ava % T e &et 'nterface for seleni!m a!tomation testin# package testngtest; import java.util.Iterator; import java.util.Set; import import import import import import org.openqa.selenium.By; org.openqa.selenium.WebDriver; org.openqa.selenium.firefox.FirefoxDriver; org.testng.annotations.Test; org.testng.annotations.BeforeMet o!; org.testng.annotations."fterMet o!;
public class Test#$%Win!o&'an!le(xample%by%jasmine ) ** De+lare global test varialbles WebDriver jasmine!river , new FirefoxDriver-.; String /pen%a%popup%&in!o&; String 0ositione!%0opup; String 1avaS+ript%0opup%Win!o&s; 2Test public void f-. throws Interrupte!(x+eption ) ** " Set is a 3olle+tion t at +annot +ontain !upli+ate elements. It mo!els t e mat emati+al set abstra+tion. Set &in!o&i!s , jasmine!river.getWin!o&'an!les-.; **iterator- . **4eturns an Iterator obje+t for t e +olle+tion & i+ may be use! to retrieve an obje+t
Iterator iter, &in!o&i!s.iterator-.; 1avaS+ript%0opup%Win!o&s,iter.next-.; ** /pen first popup jasmine!river.fin!(lement-By.xpath-5**672i!,8+ontent89*!iv7:9*a5. ..+li+;-.; &in!o&i!s , jasmine!river.getWin!o&'an!les-.; iter, &in!o&i!s.iterator-.; iter.next-.; /pen%a%popup%&in!o&,iter.next-.; System.out.println-1avaS+ript%0opup%Win!o&s.; System.out.println-/pen%a%popup%&in!o&.; T rea!.sleep-:<<<=.; System.out.println-.; System.out.println-50ositione!%0opup5.; ** s&it+ to main &in!o& to +li+; on ot er popup lin; jasmine!river.s&it+ To-..&in!o&-1avaS+ript%0opup%Win! o&s.; ** /pen se+on! popup jasmine!river.fin!(lement-By.xpath-5**672i!,8+ontent89*! iv7>9*p*a5...+li+;-.; &in!o&i!s , jasmine!river.getWin!o&'an!les-.; iter, &in!o&i!s.iterator-.; iter.next-.; iter.next-.; 0ositione!%0opup , iter.next-.; System.out.println-1avaS+ript%0opup%Win!o&s.; System.out.println-/pen%a%popup%&in!o&.; System.out.println-0ositione!%0opup.; System.out.println-.;
T rea!.sleep-:<<<=.; System.out.println-53entere!%0opup5.; ? 2BeforeMet o! public void beforeMet o!-. ) jasmine!river.get-5 ttp@**&&&.qua+;it.+om*javas+ript*popup%&in !o&s.+fm5.; ? 2"fterMet o! public void afterMet o!-. ) jasmine!river.s&it+ To-..&in!o&-/pen%a%popup%&in!o&.; jasmine!river.+lose-.; jasmine!river.s&it+ To-..&in!o&-0ositione!%0opup.; jasmine!river.+lose-.;
jasmine!river.s&it+ To-..&in!o&-1avaS+ript%0opup%Win!o&s.; jasmine!river.quit-.; ? ? Example Three: In Selenium 2(WebDriver), testing popup windows involve switching the driver to the popup window and then running the corresponding actions. Twist recorder records actions in popup windows as commented code. For eg.
**Write your logi+ to lo+ate t e appropriate popup before using +ommente! a+tions. **=oo; at A 8'o& !o I an!le popup in WebDriver8 se+tion for more !etails. **a+tion in popup 5$oogle5. popup.fin!(lement-By.name-5q5...sen!Beys-5T oug t∨s5.; **a+tion in popup 5$oogle5. popup.fin!(lement-By.name-5btn$5...submit-.;5
The above code is the result o recording in the popup window having google search page, searching or !Thoughtwor"s!. To get the above code wor"ing# $) Identi % the popup, The ollowing code identi ies the popup window with title !&oogle!. 'ote that the actions tells the title o the popup window. (dd the code )ust be ore the irst popup action being commented. String parentWin!o&'an!le , bro&ser.getWin!o&'an!le-.; ** save t e +urrent &in!o& an!le. WebDriver popup , null; IteratorCStringD &in!o&Iterator , bro&ser.getWin!o&'an!les-.; & ile-&in!o&Iterator. as#ext-.. ) String &in!o&'an!le , &in!o&Iterator.next-.;
2) *ncomment code or the same popup, **a+tion in popup 5$oogle5. popup.fin!(lement-By.name-5q5...sen!Beys-5T oug t∨s5.; **a+tion in popup 5$oogle5. popup.fin!(lement-By.name-5btn$5...submit-.;5
+) ( ter the popup actions, switch the driver bac" to the parent window, bro&ser.+lose-.; ** +lose t e popup. bro&ser.s&it+ To-..&in!o&-parentWin!o&'an!le.; ** S&it+ ba+; to parent &in!o&.
Example Four:
Creating a test suite using Selenium 2 / Webdriver "fter &riting my post@ 'E0(4=I#B 5 ttp@**n+ona.+om*F<GF*<F*runningAseleniumAFA&eb!riverA tests*5 Ho 54unning Selenium F.< * Web!river tests5 4unning Selenium F.< * Web!river testsI I &as t in;ing o& +oul! I ma;e a test suite so I +oul! run all my fun+tional tests &it just one +omman!. In t is post I am going to explain o& I use! 1ava +lasses to !o t is. T is post is ig ly base! on 'E0(4=I#B 5 ttp@**n+ona.+om*F<GF*<F*runningAseleniumAFA&eb!riverA tests*5 Ho 54unning Selenium F.< * Web!river tests5 4unning Selenium F.< * Web!river testsI so if you feel you !onJt un!erstan! & at I am sayingI please rea! t at post first. Test Suite T e first t ing I figure! is t at &e nee! a main +lass t at &ill +all all t e ot er +lasses testsI so I +reate! a main test suite file +alle! #+onaTestSuite.java &it t is +ontent@ Gpa+;age +om.n+ona; F :import org.openqa.selenium. KWebDriver; >import org.openqa.selenium.fi Lrefox.FirefoxDriver; Mimport org.openqa.selenium.s Nupport.ui.Wait; Oimport org.openqa.selenium.s G<upport.ui.WebDriverWait; GG GFpubli+ +lass #+onaTestSuite G:) GK G> publi+ stati+ voi! main- 'E0( GL4=I#B GM5 ttp@**&&&.google.+om*sear+ GN P l,enQq,allinurl GOR:"stringSjava.sun.+omQbtnI
F<,IRFMmRF<Feeling FGRF<=u+;y5 String79 args. FF ) F: ** /bje+ts t at are going FKto be passe! to all test +lasses F> WebDriver FL!river , ne& FirefoxDriver-.; FM FNWaitCWebDriverD&ait , ne& FOWebDriverWait-!riverI :<.; :< :G boolean result; :F try :: ) :K ** 'ere &e a!! all t e :>test +lasses &e &ant to run :L Mis+Test3lass :Mmt+G , ne& Mis+Test3lass-.; :N Mis+Test3lassT&o :Omt+F , ne& Mis+Test3lassT& K<o-.; KG Mis+Test3lassT ree KFmt+: , ne& Mis+Test3lassT r K:ee-.; KK K> ** We +all t e run KLmet o! -t at met o! runs all KM ** t e tests of t e KN+lass. for ea+ of t e +lasses KO ** above. If any test fails result &ill be false. result , mt+G.run-!riverI &ait. QQ mt+F.run-!riverI &ait. QQ mt+:.run-!riverI &ait.
. ? +at+ - 'E0(4=I#B 5 ttp@**&&&.google.+om*sear+ P l,enQq,allinurl R:"ex+eptionSjava.sun.+om QbtnI,IRFMmRF<Feeling RF<=u+;y5 (x+eption e. ) e.printSta+;Tra+e-.; result , false; ? finally ) !river.+lose-.; ? 'E0(4=I#B 5 ttp@**&&&.google.+om*sear+ P l,enQq,allinurl R:"systemSjava.sun.+omQbt nI,IRFMmRF<Feeling RF<=u+;y5 System.out.println-5Test 5 S -result P 5passe!.5 @ 5faile! .5..; if -Tresult. ) 'E0(4=I#B 5 ttp@**&&&.google.+om*sear+ P l,enQq,allinurl R:"systemSjava.sun.+omQbt nI,IRFMmRF<Feeling RF<=u+;y5 System.exit-G.; ? ? ? Test Class
/ur test +lasses nee! to ave a run met o! t at &ill run all t e tests it +ontains. 'ere is an example of o& it +oul! loo;@ Gpa+;age +om.n+ona; F :import java.util.=ist; Kimport org.openqa.selenium.B >y; Limport org.openqa.selenium. MWebDriver; Nimport org.openqa.selenium. OWeb(lement; G<import org.openqa.selenium.fi GGrefox.FirefoxDriver; GFimport org.openqa.selenium.s G:upport.ui.(xpe+te!3on!ition; GKimport org.openqa.selenium.s G>upport.ui.Wait; GLimport org.openqa.selenium.s GMupport.ui.WebDriverWait; GN GOpubli+ +lass Mis+Test3lass F<) FG stati+ WebDriver !river; FF F: stati+ WaitCWebDriverD &ait FK; F> FL FM publi+ stati+ boolean run-We FNbDriver !river"rgI FOWaitCWebDriverD &ait"rg. :< ) :G !river , !river"rg; :F &ait , &ait"rg; :: :K setUp-.; :>
:L ** 4un all t e met o!s :Man! return false if any fails :N return :O mis+Met o!-. K< QQ mis+Met o!F-. KG .; KF ? K: KK private stati+ boolean mis+M et o!-. ) ** 0ut your tests +o!e ere return result ? private stati+ boolean mis+M et o!F-. ) ** 0ut your tests +o!e ere return result ? ? Build file T e buil!.xml file use! for t is test suite almost t e same as t e one in my previous post. We just nee! to + ange t e target to use t e name of our ne& test suite file@ GCproje+t base!ir,5.5 name,5 FTest "utomation5D : K Cproperty name,5sr+.!ir5 va >lue,5V)base!ir?*java*sr+5*D
L M Cproperty name,5+lasses.!i Nr5 value,5V O)base!ir?*java*+lasses*main5* G<D GG GF Cproperty name,5lib.!ir5 val G:ue,5V)base!ir?*lib5*D GK G> Cproperty name,5buil!.!ir5 GLvalue,5V)base!ir?*buil!5*D GM GN Cproperty name,5testautom GOation.jar5 value,5V F<)buil!.!ir?*testautomation.jar FG5*D FF F: FK Cpat i!,5testautomation.+l F>asspat 5D FL Cfile file,5V FM)testautomation.jar?5*D FN Cfileset !ir,5V)lib.!ir?5D FO :< Cin+lu!e name,56.jar5 *D :G C*filesetD :F C*pat D Ctarget name,5buil!5 !es+ri ption,5sets up t e environment for test exe+ution5D Cm;!ir !ir,5V )+lasses.!ir?5*D Cm;!ir !ir,5V )buil!.!ir?5*D Cjava+ !ebug,5true5
sr+!ir,5V)sr+.!ir?5 !est!ir,5V )+lasses.!ir?5 in+lu!e"nt4untime,5false5 +lasspat ref,5testautomatio n.+lasspat 5*D Cjar base!ir,5V )+lasses.!ir?5 jarfile,5V )testautomation.jar?5*D C*targetD Ctarget name,5runA example5 !es+ription,5run +omman!Aline example5D CTAAAA T is is t e line I mo!ifie!. 3lassname is no& +om.n+ona.V)example? AAAAD Cjava +lassname,5+om.n+on a.V)example?5 failonerror,5true5 +lasspat ref,5testautomatio n.+lasspat 5*D C*targetD C*proje+tD Run the suite First &e nee! to buil! t e proje+t@ Gant buil! Finally to run it &e &oul! use t is +omman!@ Gant runAexample ADexample,#+onaTestSuite Example Five:
Selenium WebDriver, Selenium Server and PageObjects by Example HYPERLINK "http://www.has o!e. om/"#$"/#%/sele&ium'we(!river'sele&ium' server'a&!'pa)eo(*e ts'(+'example/" http://www.has o!e. om/"#$"/#%/sele&ium' we(!river'sele&ium'server'a&!'pa)eo(*e ts'(+'example/
Example ,ix: ,-./01I'2 !http#33selenium orum. orumotion.net3t$4+$5need5 selenium5webdriver5e6cel5sheet5e6amples! Selenium Webdriver + Excel sheet examples /6ample or read3write operations rom e6cel sheet using selenium webdriver. import )6l.Sheet7 import )6l.Wor"boo"7 import org.open8a.selenium.9%7 import org.open8a.selenium.WebDriver7 import org.open8a.selenium.chrome.:hromeDriver7 import )ava.io.FileInputStream7 import )ava.io.I;/6ception7 import )6l.Sheet7 import )6l.Wor"boo"7 import )6l.read.bi .9i /6ception7 public class TestData< WebDriver driver = new :hromeDriver()7 public void 1ogin() throws Interrupted/6ception, 9i /6ception, I;/6ception <
FileInputStream i=new FileInputStream(!D#>>sreewor"space>>sree.6ls!)7 Wor"boo" wor"boo" = Wor"boo".getWor"boo"( i)7 Sheet sheet = wor"boo".getSheet(!1ogin!)7 String s=sheet.get:ell(2,2).get:ontents()7 S%stem.out.println(s)7 driver. ind/lement(9%.id(!gb8 8!)).send2e%s(s)7 driver. ind/lement(9%.name(!btn2!)).clic"()7 ? public static void main(String@A args) throws Interrupted/6ception, 9i /6ception, I;/6ception < S%stem.set.ropert%(!webdriver.chrome.driver!, !D#3sree"umar3Tutorial3Selenium3chromedriverBwinB$C.4.DDE.43 chromedriver.e6e!)7 33.ausing here seems to ma"e it wor" better, so... TestData login = new TestData()7 login.driver.get(!https#33www.google.com!)7 login.1ogin()7 ? ? /6ample Seven# Uploading iles in Remote Web!river $arch %th& '()' b* Santia!o Suare+ Ordo,e+ ,i& e it-s (ee& a while si& e m+ last ,ele&ium tips (lo) post. I thou)ht it was time to share some ,ele&ium love a)ai&. To!a+ we-re overi&) /e(0river-s &ative solutio& to a ver+ ommo& issue whe& !oi&) !istri(ute! ross (rowser testi&): uploading files in remote servers.
1s +ou ma+ 2&ow. the wa+ to a!!ress this i& ,ele&ium $ is to pla e +our 3iles i& a& a essi(le we( server a&! use the atta hFile omma&! that poi&ts to the orre t 4RL. /ith ,ele&ium ". the ,ele&ium 0ev team has lu 2il+ ma!e this a lot more straightforward. For those o3 +ou !oi&) this lo all+. all +ou &ee! to !o is use the sendKeys omma&! totype the local path o3 the 3ile i& a&+ 3ile 3iel!. This wor2s li2e a harm i& all !rivers. /he& movi&) this test to a remote server 5su h as. 3or example. our ,ele&ium " 6lou!7. all +ou &ee! to !o is use the setFileDetector method to let /e(0river 2&ow that +ou-re uploa!i&) 3iles 3rom +our lo al omputer to a remote server i&stea! o3 *ust t+pi&) a path. 1lmost ma)i all+. the 3ile will be base64 encoded and sent transparentlythrou)h the 8,9N/ireProto ol 3or +ou (e3ore writi&) the 3ixe! remote path. This is a& ex elle&t solutio&. as it lets +ou swit h +our tests 3rom a lo al to remote 0river without havi&) to worr+ a(out ha&)i&) +our tests- o!e. This 3eature is available in all the official Selenium 2 bindings. *ust make sure Selenium 2. .! or newer is used as this 3eature has (ee& release! the&. Here are some examples tests: 8ava import import import import import import *u&it.3ramewor2.1ssert" *u&it.3ramewor2.Test6ase" or).ope&:a.sele&ium.;" or).ope&:a.sele&ium.remote.;" *ava.&et.4RL" *ava.util. o& urre&t.Time4&it"
public class #esting$ploadSe2Sauce e%tends Test6ase & private Remote/e(0river !river" public void set$p'( throws Ex eptio& & 0esire!6apa(ilities apa(illities ) 0esire!6apa(ilities.3ire3ox'(" apa(illities.set6apa(ilit+'"versio&"* "<"(" apa(illities.set6apa(ilit+'"plat3orm"* Plat3orm.=P(" apa(illities.set6apa(ilit+'"sele&ium'versio&"* "".$>.#"(" apa(illities.set6apa(ilit+'"&ame"* "Remote File 4ploa! usi&) ,ele&ium "?s File0ete tors"("
!river ) new Remote/e(0river' new $+,'"http://@user&ameA:@api' 2e+ABo&!ema&!.sau ela(s. om:>#/w!/hu("(* apa(illities(" !river.setFile0ete tor'new Lo alFile0ete tor'((" !river.ma&a)e'(.timeouts'(.impli itl+/ait'%#* Time4&it.,E69N0,(" public void testSauce'( throws Ex eptio& & !river.)et'"http://sso.!ev.sau ela(s. om/test/)ui&ea'3ile'uploa!"(" /e(Eleme&t uploa! ) !river.3i&!Eleme&t'C+.i!'"m+3ile"((" uploa!.se&!Ke+s'"/4sers/sso/the/lo al/path/to/!ar2(ul(.*p)"(" !river.3i&!Eleme&t'C+.i!'"su(mit"((. li 2'(" !river.3i&!Eleme&t'C+.ta)Name'"im)"((" 1ssert.assertE:uals'"!ar2(ul(.*p) 5ima)e/*pe)7"* !river.3i&!Eleme&t'C+.ta)Name'"p"((.)etText'((" public void tearDown'( throws Ex eptio& & !river.:uit'(" DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD DDDDDDDDDDDDDDDD Example Ei)ht: Selenium Grid with WebDriver I had earlier covered in m% blog on how to e6ecute %our 0: cases in selenium grid. 9ut with the commencement o Selenium5 23Webdriver, grid setup has been changed. In the ollowing blog I will cover how to set5up %our grid and the changes that will be re8uired or eas% e6ecution o cases. Following things are re8uired#
$. Selenium 2.66 version server )ar and Fava librar%. The latest one can be downloaded rom the lin"# ,-./01I'2 !http#33code.google.com3p3selenium3downloads3list! Selenium52 2. Fava $.G and above +. Test'g )ar . -ou can download it rom the lin"# ,-./01I'2 !http#33testng.org3doc3download.html! Test'& H. /clipse with Test'& plugin installed(optional) E. :hromeDriver. :an be downloaded rom# ,-./01I'2 !http#33code.google.com3p3chromium3downloads3list! :hromeDriver The Test Code Following is an e6ample o test5class that have a test case to search google or !testing! and veri %ing a ter clic"ing it on a lin". HYPERLINK "http://bl !"v#runin"$ m/%&''/'&/(elenium)!rid)with) webdriver"html" * i%"ort $ -ava.net.*alfor%ed/R& xce " "tion0 % i%"ort -ava.net./R&0 E F i%"ort G or..o"en!a.seleniu%.WebDr < iver0 > i%"ort H or..o"en!a.seleniu%.WebDr $# iverBac1edSeleniu%0 $$ i%"ort $" or..o"en!a.seleniu%.re%ot $% e.DesiredCa"abilities0 $E i%"ort $F or..o"en!a.seleniu%.re%ot $G e.Re%oteWebDriver0 $< i%"ort $> or..testn..annotations.Af $H terClass0 "# i%"ort "$
"" "% "E "F "G "< "> "H %# %$ %" %% %E %F %G %< %> %H E# E$ E" E% EE EF EG E< E> EH F# F$ F" F% FE FF FG F< F> FH G# G$
or..testn..annotations.Be foreClass0 i%"ort or..testn..annotations.2a ra%eters0 i%"ort or..testn..annotations.Te st0 i%"ort co%.t,ou.,twor1s.seleniu% .Seleniu%0 i%"ort -unit.fra%ewor1.Assert0 "ublic class 3oo.le 4 "rivate Seleniu% seleniu%0 @2ara%eters546browser6,6 "ort678 @BeforeClass "ublic void beforeClass5Strin. browser,Strin. "ort84 DesiredCa"abilities ca"ability9 new DesiredCa"abilities580 ca"ability.setBrowser:a %e5browser80 try 4 WebDriver driver9 new Re%oteWebDriver5new /R&56 ('2 R&+:; 6,tt"<==local,ost=6 ,tt"<==local,ost<6.concat 5"ort8.concat56=wd=,ub688 , ca"ability80 seleniu% 9 new WebDriverBac1edSeleniu%5d
G" G% GE GF GG G< G> GH <# <$ <" <% <E <F <G
river, 6 ('2 R&+:; 6,tt"<==www..oo.le.co%=6 ,tt"<==www..oo.le.co%680 7 catc, 5*alfor%ed/R& xce"tion e8 4 7 7 @Test "ublic void searc,58 4 seleniu%.o"en56=680 seleniu%.ty"e56id9lst> ib6, 6testin.680 seleniu%.clic156==in"ut ?@[email protected] Searc,@A680 for 5int second 9 B00 secondCC8 4 if 5second D9 EB8 Assert.fail56ti%eout6 80 try 4 if 5seleniu% .is le%ent2resent56 lin19Software testin. > Wi1i"edia, t,e free encyclo"edia688 brea10 7 catc, 5 xce"tion e8 4 7 try 4 T,read.slee"5FBBB80 7 catc, 5+nterru"ted xce"tion e8 4 == T$D$ Auto> .enerated catc, bloc1 e."rintStac1Trace580
e."rintStac1Trace580
7 seleniu%.clic156lin19So ftware testin. > Wi1i"edia, t,e free encyclo"edia680 for 5int second 9 B00 secondCC8 4 if 5second D9 EB8 Assert.fail56ti%eout6 80 try 4 if 5seleniu%.isText2resent56 Software testin.688 brea10 7 catc, 5 xce"tion e8 4 7 try 4 T,read.slee"5FBBB80 7 catc, 5+nterru"ted xce"tion e8 4 7 7 e."rintStac1Trace580
7 @AfterClass "ublic void afterClass584 seleniu%.sto"580 7 7 In the above class I am using the Test'& !.arameter! propert% to provide di erent data set to the !9e ore:lass! method !be ore:lass!. The be ore:lass method accepts two properties !browser! and a !port!. These values are used or initialiIation o driver and in5turn or
initialiIation o selenium ob)ect. In the above code I am using the !WebDriver9ac"edSelenium! class or creation o the selenium ob)ect, so that its eas% or gu%s who had wor"ed on Selenium5$ to understand the code. I %ou want the code to be purel% WebDriver, %ou can directl% use the !driver! ob)ect or de ining %our test5cases. The main part in this test case is how the driver ob)ect is being created# DesiredCa"abilities ca"ability9 new DesiredCa"abilities580 ca"ability.setBrowser:a%e5browser80 WebDriver driver9 new Re%oteWebDriver5new /R&56,tt"<==local,ost<6.concat5"ort8.concat56=wd=,ub688 , ca"ability80 The above code creates an ob)ect o Desired:apabilit% and then set the browser value to it. 'ow using this !capabilit%! ob)ect I am creating the webdriver ob)ect using the !0emoteWebDriver! class. This tells the selenium on which browser the test5case needs to run and where the server is located. In this e6ample I am assuming the server to be running locall%. In case it is on di erent s%stem the !localhost! needs to be re5placed with the ip o the said s%stem. TestNG configuration For parallel e6ecution %ou need to use the Test'& con iguration. Following is an !testng.6ml! ile or the above said test class. The said con iguration e6ecutes the test5cases across di erent browser. Gsuite na%e96Seleniu% Test:3 Suite6 "arallel96tests6 t,read>count96H6D Gtest na%e96Seleniu% Test:3 > F6D G"ara%eter na%e96browser6 value96firefox6 =D G"ara%eter na%e96"ort6 value96IIII6 =D GclassesD Gclass na%e96co%.test.testn..3oo.le6 =D
G=classesD G=testD Gtest na%e96Seleniu% Test:3 > J6D G"ara%eter na%e96browser6 value96c,ro%e6 =D G"ara%eter na%e96"ort6 value96IIII6 =D GclassesD Gclass na%e96co%.test.testn..3oo.le6 =D G=classesD G=testD G=suiteD In the #b ve $ n+i!ur#ti n, I #m $ n+i!urin! -e(tNG t run "te(t(" in p#r#llel" .l( there #re tw di++erent te(t( in(ide # (uite" / r e#$h te(t # di++erent "br w(er" p#r#meter v#lue h#( been $ n+i!ured" Selenium-Grid server N w (t#rt 0 ur !rid u(in! the + ll win! $ mm#nd(" Run e#$h $ mm#nd in # (eper#te termin#l r $ mm#nd pr mpt b0 ! in! t the dire$t r0 $ nt#inin! 0 ur (elenium)(erver)(t#nd#l ne)%"1"1"2#r" In the + ll win! e1#mple I #m u(in! the %"3"& ver(i n + (elenium" / r Hub: -ava >-ar seleniu%>server>standalone>J.K.B.-ar >role ,ub / r # +ire+ 1 b#(ed n de: -ava >-ar seleniu%>server>standalone>J.K.B.-ar >role webdriver >,ub ,tt"<==local,ost<IIII=.rid=re.ister >"ort HHHE >browser browser:a%e9firefox / r! !le)$hr me b#(ed n de:
-ava >Dwebdriver.c,ro%e.driver9="at,=to=c,ro%edriver >-ar seleniu%>server>standalone>J.K.B.-ar >role webdriver >,ub ,tt"<==local,ost<IIII=.rid=re.ister >"ort HHHH >browser browser:a%e9c,ro%e 9e ore running the above command %ou need to provide the chrome5driver path to the propert% !5Dwebdriver.chrome.driver!. 'ow run %our testng.6ml rom eclipse b% selecting it 5J 0ight clic" 5J 0un as 5J Test'& suite(this will wor" onl% i %ou have Test'& plugin installed in %our eclipse.) ;r %ou can choose other wa%s to e6ecute !testng.6ml! li"e rom command prompt, using ant or maven. ;nce %ou run the above testng.6ml. Test'& will e6ecute the cases rom the &oogle class on grid across di erent browsers ire o6 and google5chrome as con igured. -ou can do con igurations or environment li"e ;S (1inu6,Windows), browser, browser5version and all and then %ou can run %ou cases on particular t%pe o environment b% con iguring them accordingl%. Kore details can be ound at the ollowing *01# ,-./01I'2 !http#33code.google.com3p3selenium3wi"i3&rid2! http#33code.google.com3p3selenium3wi"i3&rid2 Example Ni&e: D#t#)Driven te(tin! u(in! 4unit #nd -e(tNG Kost o the gu%s who are into automation ma% be "nowing the term Data5Driven testing. 9ut the word will still be new or some resh aces in the ield o automation. In this blog I will e6plain what is Data5Driven testing and will give an e6ample o Data5 driven testing using Funit and Test'& ramewor"s. Data5Driven testing as the name suggests is a test driven b% the Data. For e6. -ou have a user detail orm where %ou need to
enter details o multiple users and save them. ,ere i %ou have E di erent user data available and %ou have to write automation cases or these, %ou ma% end up writing E di erent automation test cases(one or each user data). I %ou appl% a Data5Driven approach %ou will end up with onl% one test5case, that is illing the orm with user data and then submitting it. The test case will get e6ecuted based on the data provided to it. In this case it will be E and hence the test case will get e6ecuted E times with di erent data5set. The advantage o using a Data5driven approach is that %ou reduce %our e ort in writing3maintaing test5cases or %our di erent t%pe o data. In case o additions or deletion o new3old entries , %ou )ust have to change the data and not %our actual test5case. Following I will mention a Data5Driven approach or searching on google with di erent data using Funit and Test'g ramewor"s# Using Junit HYPERLINK "http://bl !"v#runin"$ m/%&''/'&/d#t#)driven)te(tin!) u(in!)2unit)#nd"html" * i%"ort static $ or..-unit.Assert.fail0 " % i%"ort E co%.t,ou.,twor1s.seleniu% F .L0 G i%"ort or..-unit.After0 < i%"ort or..-unit.Before0 > i%"ort or..-unit.Test0 H $# i%"ort $$ or..-unit.runner.RunWit,0 $" i%"ort $% or..-unit.runners.2ara%et $E eriMed0 $F i%"ort $G
$< $> $H "# "$ "" "% "E "F "G "< "> "H %# %$ %" %% %E %F %G %< %> %H E# E$ E" E% EE EF EG E< E> EH F# F$ F" F% FE FF FG
or..-unit.runners.2ara%et eriMed.2ara%eters0 i%"ort or..o"en!a.seleniu%.WebDr iver0 i%"ort or..o"en!a.seleniu%.WebDr iverBac1edSeleniu%0 i%"ort or..o"en!a.seleniu%.firef ox.FirefoxDriver0 i%"ort -ava.util.Arrays0 i%"ort -ava.util.&ist0 @RunWit,52ara%eteriMed.cl ass8 "ublic class Nunit3oo.leBase 4 "ublic Seleniu% seleniu%0 WebDriver driver0 "rivate Strin. testData0 "ublic Nunit3oo.leBase5Strin. testData84 t,is.testData9testData 0 7 @2ara%eters "ublic static &istG $b-ect?AD data58 4 return Arrays.as&ist5new $b-ect?A ?A446testin.67,46Software testin.67780 7
@Before "ublic void set/"58 t,rows xce"tion 4 driver9 new FirefoxDriver580 seleniu% 9 new WebDriverBac1edSeleniu%5d river, 6 ('2 R&+:; 6,tt"<==www..oo.le.co%=6 ,tt"<==www..oo.le.co%680 seleniu%.o"en56 ('2 R&+:; 6,tt"<==www..oo.le.co%=6 ,tt"<==www..oo.le.co%680 7 @Test "ublic void testSearc,58 t,rows xce"tion 4 seleniu%.o"en56=680 seleniu%.ty"e56id9lst> ib6, testData80 seleniu%.clic156==in"u t?@[email protected] Searc,@A680 for 5int second 9 B00 secondCC8 4 if 5second D9 EB8 fail56ti%eout680 try 4 if 5seleniu%.is le%ent2resen t56lin19Software testin. > Wi1i"edia, t,e free encyclo"edia688 brea10 7 catc, 5 xce"tion e8 47 T,read.slee"5FBBB80 7 seleniu%.clic156lin19S oftware testin. > Wi1i"edia, t,e free
encyclo"edia680 for 5int second 9 B00 secondCC8 4 if 5second D9 EB8 fail56ti%eout680 try 4 if 5seleniu%.isText2resent56 Software testin.688 brea10 7 catc, 5 xce"tion e8 47 T,read.slee"5FBBB80 7 7 @After "ublic void tearDown58 t,rows xce"tion 4 seleniu%.sto"580 7 7 Using TestNg: HYPERLINK "http://bl !"v#runin"$ m/%&''/'&/d#t#)driven)te(tin!) u(in!)2unit)#nd"html" * i%"ort $ co%.t,ou.,twor1s.seleniu% " .L0 % E F i%"ort G or..o"en!a.seleniu%.WebDr < iver0 > i%"ort H or..o"en!a.seleniu%.WebDr $# iverBac1edSeleniu%0 $$ i%"ort $" or..o"en!a.seleniu%.firef $%
$E $F $G $< $> $H "# "$ "" "% "E "F "G "< "> "H %# %$ %" %% %E %F %G %< %> %H E# E$ E" E% EE EF EG E< E> EH F# F$ F" F%
ox.FirefoxDriver0 i%"ort or..testn..Assert0 i%"ort or..testn..annotations.Af ter*et,od0 i%"ort or..testn..annotations.Be fore*et,od0 i%"ort or..testn..annotations.Da ta2rovider0 i%"ort or..testn..annotations.Te st0
"ublic class Test:33oo.leBase 4 "ublic Seleniu% seleniu%0 WebDriver driver0 @Data2rovider5na%e96"ar a%eter68 "ublic static $b-ect?A ?A data58 4 return new $b-ect?A?A 446testin.67,46Software testin.6770 7 @Before*et,od "ublic void set/"58 t,rows xce"tion 4 driver9 new FirefoxDriver580 seleniu% 9 new WebDriverBac1edSeleniu%5d river, 6 ('2 R&+:;
FE FF FG
6,tt"<==www..oo.le.co%=6 ,tt"<==www..oo.le.co%680 seleniu%.o"en56 ('2 R&+:; 6,tt"<==www..oo.le.co%=6 ,tt"<==www..oo.le.co%680 7 @Test5data2rovider96"ar a%eter68 "ublic void testSearc,5Strin. testData8 t,rows xce"tion 4 seleniu%.o"en56=680 seleniu%.ty"e56id9lst> ib6, testData80 seleniu%.clic156==in"u t?@[email protected] Searc,@A680 for 5int second 9 B00 secondCC8 4 if 5second D9 EB8 Assert.fail56ti%eout680 try 4 if 5seleniu%.is le%ent2resen t56lin19Software testin. > Wi1i"edia, t,e free encyclo"edia688 brea10 7 catc, 5 xce"tion e8 47 T,read.slee"5FBBB80 7 seleniu%.clic156lin19S oftware testin. > Wi1i"edia, t,e free encyclo"edia680 for 5int second 9 B00 secondCC8 4 if 5second D9 EB8 Assert.fail56ti%eout680
try 4 if 5seleniu%.isText2resent56 Software testin.688 brea10 7 catc, 5 xce"tion e8 47 T,read.slee"5FBBB80 7 7 @After*et,od "ublic void tearDown58 t,rows xce"tion 4 seleniu%.sto"580 7 7Gs"an class96A""le> style>s"an6 style96font> fa%ily< #erdana, sans> serif06D G=s"anD The main di erence in the above two unctions is that %ou provide a .aramateriIed option to the class in Funit and suppl% data to the constructor o the said class. Where as in Test'& %ou do the same at the test5method level. Its simple to do data5driven testing in Test'& ramewor" as %ou can provide a di erent data providing unction or each test5 method, but the same is not possible in Funit. Example Te&: HYPERLINK "http://bl !"v#runin"$ m/%&'&/&5/!ener#tin!)(elenium) rep rt()u(in!"html" Gener#tin! (elenium rep rt( u(in! -e(tNG)1(lt thr u!h .nt Test'&56slt generates user riendl% reports using the Test'& results output (testng5results.6ml). Its uses the pure LS1 or report generation and Sa6on as an LS12.4 implementation.
Kost o the material is ta"en rom the original site. http#33code.google.com3p3testng56slt3 I will tell in this blog how to implement this report or %our pro)ect. This implementation will tell %ou how to generate the testng56slt report using ant. I %our current pro)ect does not use ant build then %ou can use ant onl% or the report generation purpose. I %ou dont "now ant please chec" the (pache ant website http#33ant.apache.org3. For generating testng56slt report or %our pro)ect do the ollowing# $. Download the testng56slt 2. *nIip and cop% the testng5results.6sl rom the testng56slt older(testng56slt5$.$>src>main>resources) to %our own pro)ect older. +. 'ow cop% the sa6on librar% rom (testng56slt5$.$>lib>sa6on5 C.M.)ar)to %our pro)ect lib older. H. Kodi % %our build.6ml o ant and add the ollowing target to it. HYPERLINK "http://bl !"v#runin"$ m/(e#r$h/l#bel/Selenium 6%&Rep rt(" * G"ro-ect na%e96test6 $ basedir96.6D " G"ro"erty na%e96&+B6 % value96O4basedir7=libs6 =D E G"ro"erty na%e96B+:6 F value96O4basedir7=bin6 =D G G"at, id96%aster> < class"at,6D > G"at,ele%ent H location96O4B+:76 =D $# Gfileset dir96O $$ 4&+B76D $" Ginclude $%
$E $F $G $< $> $H "# "$ "" "% "E "F "G "< "> "H
na%e96LL=L.-ar6 =D G=filesetD G="at,D Gtar.et na%e96testn.> xslt>re"ort6D Gdelete dir96O 4basedir7=testn.>xslt6D G=deleteD G%1dir dir96O 4basedir7=testn.>xslt6D G=%1dirD Gxslt in96O 4basedir7=test> out"ut=testn.> results.x%l6 style96O 4basedir7=testn.> results.xsl6 out96O 4basedir7=testn.> xslt=index.,t%l6D G"ara% ex"ression96O 4basedir7=testn.>xslt=6 na%e96test:.Pslt.out"utDi r6 =D G"ara% ex"ression96true6 na%e96test:.Pslt.sortTest Case&in1s6 =D G"ara% ex"ression96FA+&,S;+2,2AS S,C$:F,B')C&ASS6 na%e96test:.Pslt.testDeta ilsFilter6 =D G"ara% ex"ression96true6 na%e96test:.Pslt.s,owRunt
i%eTotals6 =D Gclass"at, refid96%aster>class"at,6D G=class"at,D G=xsltD G=tar.etD G="ro-ectD The LS1 trans ormation can be con igured using the parameters described below. testNg!slt"output#ir 5 Sets the target output director% or the ,TK1 content. This is mandator% and must be an absolute path. I %ou are using the Kaven plugin this is set automaticall% so %ou donNt have to provide it. testNg!slt"css$ile 5 Speci ies and alternative st%le sheet ile overriding the de ault settings. This parameter is not re8uired. testNg!slt"sho%&untimeTotals 5 9oolean lag indicating i the report should displa% the aggregated in ormation about the methods durations. The in ormation is displa%ed or each test case and aggregated or the whole suite. 'on5mandator% parameter, de aults to alse. testNg!slt"reportTitle 5 *se this setting to speci % a title or %our ,TK1 reports. This is not a mandator% parameter and de aults to !Test'& 0esults!. testNg!slt"sortTestCase'in(s 5 Indicates whether the test case lin"s (buttons) in the le t rame should be sorted alphabeticall%. 9% de ault the% are rendered in the order the% are generated b% Test'& so %ou should set this to true to change this behavior. testNg!slt"chartScale$actor 5 ( scale actor or the SO& pie chart in case %ou want it larger or smaller. De aults to $. testNg!slt"test#etails$ilter 5 Speci ied the de ault settings or the chec"bo6 ilters at the top o the test details page. :an be an% combination (comma5separated) o #
F(I1,.(SS,S2I.,:;'F,9-B:1(SS -ou need to provide the testng56slt st%lesheet the Test'& results 6ml(testng5results.6ml) , the path to the st%le sheet testng5 results.6sl and the output inde6.html path. (lso dont orget to add the sa6on librar% to %our target classpath else %ou will get an error. In m% case it is the master5classpath. 'oe run the ant target or report generation (in m% case !testng5 6slt5report!) and chec" the ouput older con igured b% %ou or testng56slt report. Example Eleve&: How to take a screenshot at the end of your Selenium WebDriver tests? I':1*D/.I:T*0/ !http#33www.muhu".com3wp5 content3uploads324$23423webdriverBscreenshot5+4462M4.png! >P K/0&/F;0K(TI'/T When %ou run ,-./01I'2 !http#33seleniumh8.org3! Selenium headless on the server, debugging ailures with )ust the standard outputs can be challenging. ( screenshot o the last state o the browser helps in this case. This little tutorial e6plains how to ta"e such a screenshot and save it as an arti act in Fen"ins. I will be using ,-./01I'2 !http#33www.)unit.org3! )unit as the test ramewor". Step 0: Getting the name of the current test -ou probabl% want to include the name o the test class and the name o the current test method in the ilename. ,ere is how %ou ind it out# i%"ort or..-unit.After0 i%"ort or..-unit.Rule0 i%"ort or..-unit.rules.Test:a%e0
"ublic abstract class Test 4 @Rule "ublic Test:a%e test:a%e 9 new Test:a%e580 @After "ublic void tearDown58 4 Strin. class:a%e 9 t,is..etClass58..etSi%"le:a%e580 Strin. %et,od:a%e 9 t,is.test:a%e..et*et,od:a%e580 Syste%.err."rintln56Finis,ed test 6 C class:a%e C 6.6 C %et,od:a%e C 658680 7 7 The code above is )ust a simple demonstration o how %ou use Test:a%e. ,owever it is a good idea to produce a simple output li"e above in the beginning and the end o each test. Step : !aking the screenshot ,-./01I'2 !http#33seleniumh8.org3docs34HBwebdriverBadvanced.html! >l !ta"ing5a5screenshot! Selenium documentation suggests the ollowing# i%"ort or..-unit.After0 i%"ort -ava.io.File0 i%"ort or..o"en!a.seleniu%.$ut"utTy"e0 i%"ort or..o"en!a.seleniu%.Ta1esScreens,ot0 "ublic abstract class Test 4 @After "ublic void tearDown58 4 == driver is your WebDriver File screens,ot 9 55Ta1esScreens,ot8 driver8 ..etScreens,otAs5$ut"utTy"e.F+& 80
/6ample code in the o icial documentation is a little more terse, I le t out ever%thing but the essentials. Step ": Saving the image .etScreens,otAs58 method saves the output in a temporar% location. I too" ,-./01I'2 !http#33stac"over low.com3a3+H2++HM3H2$CC! the advice here and used File/tils.co"yFile58 to cop% this temporar% ile bac" inside m% wor"space. i%"ort or..-unit.After0 i%"ort -ava.io.+$ xce"tion0 i%"ort or..a"ac,e.co%%ons.io.File/tils0 "ublic abstract class Test 4 @After "ublic void tearDown58 4 == screens,ot is t,e file we ,ave ac!uired == file:a%e is t,e na%e of t,e i%a.e file try 4 File/tils.co"yFile5screens,ot, new File5file:a%e880 7 catc, 5+$ xce"tion e8 4 e."rintStac1Trace580 7 7 7 To give a concrete e6ample, i %our file:a%e is 6screens,ot> TestClass>test:a%e."n.6, it will be copied to OW$R;S2AC =screens,ot>TestClass>test:a%e."n.. Step #: $rchiving the screenshot as an artifact In Post-build Actions section enable Archive the artifacts and enter the appropriate glob in the te6tbo6 below. -our screenshots will appear in the Build Artifacts in build details page