Testing Masters Technologies
www.testingmasters.com
Te Testin ting Mas Masters tersInc Inc.
Page 1
Testing Masters Technologies
1. Se Seleni lenium um Overv Overview iew Introduction Seleni Selenium um is an open-source open-source and and a portable automa automated software testi testing ng tool for testing web appli applica cati tions. ons. It has capab capabiiliti li ties es to oper operate acr across different different browsers and oper operating syste system ms. Selenium is not just just a single single tool but a set set of tools that helps helps tes testers ters to automate automate web-base web-based d appli applica cati tions ons more more efficiently. efficiently.
Advantages of Selenium UFT/ UFT/ QTP and Selenium are the most most used used tools in in the market rket for softwa software automa automati tion on testing. Henc Hence e it makes makes sense sense to compare compare the pros of Se Seleni lenium um over over UFT/ QTP. Feature
Lice icense Cost Brows rowse er Su Support OS Support Language Support Parallel Execution Remote Execution Hardware utilization
Selenium
Open source rce tool an and Zero Cost Fire Firefo fox x, Chrom rome, IE,Sa IE,Safari,Op ri,Opera, ra, etc., Windows, MAC, Unix Java, C# C#, Ru Ruby, Py Python, et etc., Supports Supports[Using Grid] Low
QTP/UFT
Commerci rcial to tool an and huge license cost Fire Fireffox, Chrom rome, IE Windows VB Sc Scripting Does not Support Does not su support High
2. Se Seleni lenium um Compo Compone nents: nts: The The follo followin wing g are the the components of selen lenium ium * Selenium IDE * Sel Selenium RC * Sel Selenium WebDri WebDriver ver * Selenium Grid
Seleni nium um IDE: IDE: ¸ ¸ ¸ ¸
Seleni Selenium umIIDE Stands Stands for Integrated ntegrated Deve Developme lopment nt Environm Envir onment. ent. Seleni Selenium um IDE is a Firefox Firefox plug in that lets testers testers to record their acti actions ons as as they they follow foll ow the Workfl Workflow ow that they they need need to test. test. Sel Selenium does not support support any program programming ming languag language. e. To overco rcome this this Selen lenium ium RC is intro introd duced.
Selenium RC: ¸ ¸
Selenium RC stands for Selenium Remote Control(Selenium 1.0 version) Sel Selenium RC supports supports program programm ming language languages s li like Java Java,, C#etc., etc.,
www.testingmasters.com
Te Testin ting Mas Masters tersInc Inc.
Page 2
Testing Masters Technologies
¸ ¸
But in Selenium Selenium RC the wri written Test Test Scri Script pt codefirst first interac interacts ts with with Serve Serverr and then then interacts interacts with with webpa webpag ge. To overco rcome the these arch rchitec itectura turall drawb rawba acks selen lenium ium Webdrive river is intr intro oduced.
Seleni nium um WedDri WedDrive verr: ¸ ¸ ¸
Seleni Selenium um WebDri WebDrive verr [Seleni [Selenium um2.0 Ver Version] is the succe success ssor or to Seleni Selenium um RC[Se RC [Selenium lenium 1.0 Version]. Seleni Selenium um WebDri WebDrive verr will wil l sends sends commands ands direc dir ectl tly y to the browser and retri retriev eves es result results. s. Sel Selenium WebDriver WebDriver has Robust and powerful methods methods to can be use used d easil easily. y.
Selenium Grid: ¸ ¸ ¸
Selenium Grid is a toll that can be used for Remote and parallel Execution. Seleni Selenium um Grid can can be confi config gured with wi th both RC,Web RC, Webdri drive verr versi versions. ons. Using Selenium Selenium Grid will wil l help help in redu reducing cing the exec executi ution on tim time drastical drastically.
3. Se Sele leni nium um ID IDE E ¸ ¸ ¸ ¸ ¸ ¸ ¸ ¸
Selenium IDE stands for selenium Integrated Development environment. Seleni Selenium um IDE is is launched launched in year year 2006 by thought works wor ks organi organization, in competiti competition on to the QTP tool of mercury. mercury. Sel Selenium IDE IDE doesnot does not have any any program programming ming languag language e support. support. Selenium IDE is is an add add-on -on for Firefox Firefoxbrowse browser. r. In Selenium IDE, we need to enter the commands and object properties to perform actions. Seleni Selenium um IDE does does not support good reporting reporti ng formats. formats. Because of this drawback, the other components of selenium are introduced. However, the recorded scripts can be converted into various programming languages supported by Selenium and the scripts can be executed on other browsers as well.
3.1 Ins Instal tallat lation ion of seleni selenium um IDE: ¸
Open Open a Firefox Fi refox browser Navigate to this URL https://addons.mozilla.org/en-US/firefox/addon/selenium-ide/ [Google: SeleniumIDE for Firefox] Click li ck on add add to Firefox Firefoxbutto button n
¸
After download downloadiing, ng, click click on install button at the top, to install selenium selenium IDE.
¸ ¸
www.testingmasters.com
Te Testin ting Mas Masters tersInc Inc.
Page 3
Testing Masters Technologies
¸
After Insta I nstalllla ation, Resta Restart rt the Firefo Firefox x browser. browser.
¸
After succes successful sful inst i nsta alla ll ation, selenium selenium IDE will will be visi visible ble in Tools T ools Selenium SeleniumIIDE.
¸ ¸
The The Ico Icon will will also lso be visib isible le at the the top top righ right corne rner. Click Click on this this Icon to open open Selen Selenium ium IDE.
www.testingmasters.com
Te Testin ting Mas Masters tersInc Inc.
Page 4
Testing Masters Technologies
3.2 Working with Selenium IDE: ¸ ¸ ¸ ¸
Open Open Selenium IDE[Tools DE[Tools Selenium SeleniumIIDE] Open Open the AUT{ AUT{Appli Applica cati tion on Under Under Test} Start perfor performing ming some some acti actions ons in the webpage. webpage. All All the Actions along with with data ar are recorded recorded in in the form form of of IDE I DE Table.
www.testingmasters.com
Te Testin ting Mas Masters tersInc Inc.
Page 5
Testing Masters Technologies
¸
SeleniumI lenium IDE Table Table Command Sel Selects the the command command based on action perform performed
Target
Value
Builds Buil ds the locator locator Descri Descripti ption on based based Stores the data based on the Webelem Web element entSe Selected lected on the values entered.
¸
Example:
¸ ¸
Fil Fi le Save SaveTest Test Caseas Caseas Givethe ve the test case case name name and and save save the test test case. case. File Fi le Export Export Tes Testt Cas Case e As Selec Selectt the Appropriate Appropriate version version click click on Sav Save. e.
4. Sel elen eniu ium m WebD bDrriv iver er:: 4.1 Environment Environment Setup Setup for Selenium Selenium WebDriver: WebDriver: I n order order to devel develop WebDri WebDrive verr scripts, scripts, users users have have to ensure ensure that that they have have the the initi initial al Confi Config guration uration done. done. Setting Setting up the envir environm onment ent involves thefol the follow lowing ing steps. steps. and Insta Installll Java ava v Download and Configure Eclipse Ecli pse v Download and Configure and Configure Configure Fir Firebug ebugand and Fir Firepath epath v Download and v Configure Selenium WebDriver First WebDri WebDrive verr Program Program v First
www.testingmasters.com
Te Testin ting Mas Masters tersInc Inc.
Page 6
Testing Masters Technologies
4.1.1: Download and Install Java ¸
Navigate to "http://www.oracle.com/technetwork/java/javase/downloads/index.html"
¸ ¸ ¸ ¸ ¸ ¸ ¸ ¸ ¸ ¸
[Google: Java JDK Download] Click on JDK Download. Click on accept license agreement radio button. Download the JDK JDK file file based based on the system type [Rig [Right click click on My com computer puter Properti Properties esSy System stemtype] 64 bit bit -- Windows Windows X64 X64 -- click on "jdk-8u101-windows-x64.exe" 32 bit -- Windows Windows X86 -- Clic li ck on on "jdk-8u101-windows-i586.exe" The The " jdkjdk-8 8u77-win -wind dows-x ws-x6 64.exe" JDK JDK will be downloa loaded on clickin licking g above link link Double Double click cli ck on this exe file file and proceed proceed install Java. ava. After successful successful insta installllation ation we can can vi view JDK,JRE JDK,JRE files files in the below below location "C:\Program Files\Java"
4.1.2: Download and Configure Eclipse ¸
Download Eclipse from the link. https://drive.google.com/file/d/0B5fakF7Z_ekCN2lJTml5U1JNdj 5fakF7Z_ekCN2lJTml5U1JNdjg/view?usp=sharing g/view?usp=sharing v https://drive.google.com/file/d/0B
¸ ¸ ¸ ¸ ¸ ¸ ¸
Zip file will be downloaded. Unzip this this file fi le to extr extrac actt actual actual file file contents. contents. Go to the extracte extracted d file[ file[eclipse-jee-neon-1-win32-x86_64Eclipseclick on eclipse.exe file] On cli clicking cking on this exe file, file, a window wil willl be opened opened to specif specify y the workspace location Workspa Workspace ce location specif specifies ies the har hard disk location where to store stor e code codes. s. Click Click on OK after spec speciifying the work space space location. location. Click Click on Workben Workbench ch icon [Display [Displ ayed ed at at the Right top corner]
4.1.3: Download and Configure Firebug and Firepath ¸ ¸
¸ ¸
Firebu Firebug g add-on add-on is supported supported only only for Firefox Firefoxbrowse browsers. rs. The The follo followin wing g are the the step teps to ins install tall fireb irebug add-on -on. pen Fir Firefo efox x browser browser v Open v Navigate to "https://addons.mozilla.org/en-US/firefox/addon/firebug/" URL. [Goog [Google: le: firebug fi rebug for Firefox] Fi refox] F irefo efox' x' Button v click on 'Add to Fir v Click on install button after downloading. after succe successful ssful insta i nstallllation, ation, fir firebug ebug can can be viewed in follow fol lowing ing path v after Tools Web Develop loper Fireb Firebug ß Too An icon icon will will be displayed displayed at the top rig ri ght corner. ß This complete letes s the the fireb firebug ins installa tallatio tion n. v This Firepa Firepath th is is an an sub add-on add-onfor for fireb fir ebug ug.. The The follo followin wing g are the the step teps to ins install tall Firep Firepath add-on -on. pen Fir Firefo efox x browser browser v Open v Navigate to "https://addons.mozilla.org/En-us/firefox/addon/firepath/" URL. [Goog [Google: le: Fir Fi repath epath for Fir Fi refox] efox] F irefo efox' x' Button v click on 'Add to Fir v Click on install button after downloading.
www.testingmasters.com
Te Testin ting Mas Masters tersInc Inc.
Page 7
Testing Masters Technologies
v v
After succes successful sful inst i nstallation, allation,Re Resta start rt the Fire Fir efoxbrowse fox browser. r. This This complete letes s the the fireb firebug ins installa tallatio tion n.
4.1.4: Configure Selenium WebDriver: ¸ ¸
¸ ¸
Download the selenium server standalone.jar file from the below URL http:/ http :/ / selenium-r selenium-release elease.stor .storag age.g e.googlea oogleapi pis.c s.com/ om/iindex ndex.html?path= .html?path=2.53/ Click on Selenium-server-standalone-2.53.1.jar
Download the suppor supportedbrow ted browse serr versi version on acc accordi ording ngly. ly. Assoc Associate iate this jar file fil e with curren currentt Project Project in eclipse Open eclipse eclipse ÿ Open project ect ÿ Create a proj Associate sel selenium enium jar file file to the current current projec project. t. ÿ Associ Right Click on java java Project Build Path Configure build path Libraries Add External Jars Browse for jar file. ÿ
Create eate the object for the res respec pecti tive ve browser browser drive dri verr class and and use the required requir ed methods.
4.1.5 First Webdriver Program: Pre Pr e Che hecks cks:: v v v
Jav Java is ins installe talled d and should be on or above 1.8 versio rsion n. Eclipse Ecli pse shoul should be on or above above Mar Mars ver version. Seleni Selenium um Webdri Webdrive verr ver version should be on or above above 2.53.1 2.53.1 versi version. on.
Steps for Fi First Selen Seleniium Web WebDri Drive verr Pr Prog ogrram: ¸ ¸ ¸ ¸ ¸
Open Open eclipse eclipse Create Create a projec proj ectt ->Pac ->Packag kage e ->Class Associ Associate selenium selenium jar fi file to the current pr project. oject. I denti dentify fy the Xpath Xpath or Locator of Eac Each h Webelem Web element ent Use this this xpath/ xpath/ locator for deve developi loping ng code in the webdri webdrive verr.
www.testingmasters.com
Te Testin ting Mas Masters tersInc Inc.
Page 8
Testing Masters Technologies
Example:
4.2 WebDriver Methods: Sel Selenium webdrive webdri verr methods are are used to perfor perform m operations operati ons on the browser browser and webelem web elements. ents. Using Web Web element element locator locators and Webdri Webdrive verr methods the test test scr scripts can can be written. wri tten. The The follo followin wing g are the the webdrive river metho thods: v v v v v v v v v v
get() navigate() findElement() findElements() getCurrentURL() getTitle() getWindowHandle() getWindowHandles() close() quit()
get(): ¸ ¸
This This metho thod is used to lau launch a URL in the the curren rrent drive river ins instan tance. This This metho thod will lau launch the the URL and waits waits until all the the elem lements of a web webpage are loa loaded. Syntax:
drive driver.g r.get(Full et(Fully y Qualifi Qualified ed URL) Example:
drive dri ver.ge r.get( t(“ “https:/ / www.g www.goog oogle.co le.co.in”) .in”) Note:
Fully Fully qua qualified li fied URL URL will will start start with wi th https or http. navigate(): ¸
This This metho thod is also lso used to lau launch a url in the the drive river ins instan tance and wait waits s for for all the the elem lements to be loade loaded. d.
www.testingmasters.com
Te Testin ting Mas Masters tersInc Inc.
Page 9
Testing Masters Technologies
¸
But this method also supports, the features such as v Backward v forward v refresh
Example:
WebDriver driver =new FirefoxDriver(); driver.navigate().to( driver .navigate().to("http "https:/ s:/// tale talentzing ntzing.c .com om// "); xpath("/ / spa driver.findElement(By. driver .findElement(By. xpath span[@id= n[@id='lnkRegistr istration']" ation']")).click(); )).click(); xpath("/ / spa driver.findElement(By. driver .findElement(By. xpath span[@id= n[@id='lbl 'lblJsRe JsReg gister']" ister']")).click(); )).click(); driver.navigate().refresh(); driver .navigate().refresh(); driver.navigate().back(); driver .navigate().back(); Note: ÿ
back() back(),, forward( forward()) methods will will navi navigate to the pag pages base based d on the history histor y of the page navigations in the driver instance.
FindElement(): ¸ ¸
This This metho thod is used to find find a web web elem lement in the the curren rrent document of drive river ins instan tance based on the node nodeproperties. properties. the followi foll owing ng ar are the sub sub method methods s that findElme fi ndElment nt supports sendKeys – to enter enter text text v sendKeys perform orm click opera operation tion v click – to perf clear – to clear clear the ex existing istingcon conten tents ts v clear isDisplaye yed d – to veri verify fy the existenc istence e – true/ true/ false false v isDispla isEnabled – to ve verify ri fy if the field is ena enable bled d – true/ false v isEnabled isSelected d – if the che checkb ckbox ox is selected selected – true/ false v isSelecte etAttribute – to get get the attribute attribute value/ value/ property value. value. v getAttri Example1: driver.findElement(By. driver .findElement(By. xpath("/ / input[@na input[@name me= ='use 'userName rName']" ']")).sendKeys( )).sendKeys("abcd123" "abcd123"); ); Example2: driver.findElement(By. driver .findElement(By. xpath("/ / input[@na input[@name me= ='L 'Log ogin' in']" ]")).click(); )).click(); Example3: driver.findElement(By. driver .findElement(By. xpath("/ / input[@na input[@name me= ='use 'userName rName']" ']")).clear(); )).clear(); driver.findElement(By. driver .findElement(By. xpath("/ / input[@na input[@name me= ='use 'userName rName']" ']")).sendKeys( )).sendKeys("abcd123" "abcd123"); ); Example4: boolean flagdisplayed; flagdisplayed =driver driver.findElement(By. .findElement(By. xpath("/ / input[@nam input[@name= e='use 'userName rName']" ']")).isDisplayed(); )).isDisplayed(); System.out System.out .println(flagdisplayed .println(flagdisplayed); ); Example5: boolean flagEnabled flagEnabled;; flagEnabled =driver driver.findElement(By. .findElement(By. xpath("/ / input[@nam input[@name= e='userNam 'userName']" e']")).isEnabled(); )).isEnabled(); System.out System.out .println(flagEnabled .println(flagEnabled); ); Example6: boolean flagSelected flagSelected;; flagSelected =driver driver.findElement(By. .findElement(By. xpath("/ / input[@nam input[@name= e='che 'checkbox ckbox']" ']")).isSelected(); )).isSelected(); System.out System.out .println(flagSelected .println(flagSelected); ); Example7: String value ="" "";; value= value =driver driver.findElement(By. .findElement(By. xpath("/ / input[@na input[@name me= ='l'log ogin' in']" ]")).getAttribute( )).getAttribute("width" "width"); ); System.out System.out .println(value .println(value); );
www.testingmasters.com
Te Testin ting Mas Masters tersInc Inc.
Page 10
Testing Masters Technologies
Note: ¸ ¸
I f the elem element ent desc descri ripti ption on is matc matching hing more more than one one node, node, by defa default ult this this method method will will points to the fir first occurr occurrenc ence. e. I n order to point out to specifi specific c occurr occurren ence ce,, we nee need to use index in xpath. xpath.
findElements(): ¸ ¸ ¸
This This metho thod is used to perform rform action ion on a grou roup of web web elem lements. ts. This This metho thod will retu return rn the the web web elem lements in the the form of a list list. From the list, we have to iterate using for each loop and then perform action on each webelement. Syntax:
¸
List< Li st
obj WebElement>objectna ectname me =dri =driver.findEl ver.findElem ements(by.Xpath("xpath ents(by.Xpath("xpath Expression") Expression"))); number of matching matching web elements elements, we can use objectname.size(); To get the the number
Program to get the names of all the radio buttons present on a webpage: WebDriver driver =new FirefoxDriver();
SECONDS); driver.man driver.m anag age e().time () .timeouts() outs().im .impli plicitl citlyWa yWait it(10, (10, Tim Ti meUnit. Unit. SECONDS ); driver.get( driver .get("http:/ "http:/ / ne newtours.de wtours.dem moau oaut.c t.com om// "); driver.findElement(By. driver .findElement(By.name("userName" "userName")).sendKeys( )).sendKeys("mercury" "mercury"); ); driver.findElement(By. driver .findElement(By.name("password" "password")).sendKeys( )).sendKeys("mercury" "mercury"); ); driver.findElement(By. driver .findElement(By.name("login" "login")).click(); )).click(); xpath("/ / input[@ty Listallitems Listallitems =driver driver.findElements(By. .findElements(By. xpath input[@type pe= ='r 'rad adio']" io']")); )); for(WebElement ele le::allitems allitems))
{ System.o System.out .println(e .println( ele le.getAttribute( .getAttribute("name" "name")); )); } Program to get the number of links displayed in a webpage:
WebDriver driver =new FirefoxDriver(); SECONDS); driver.m driver .man anag age e().time () .timeouts() outs().im .impli plicitl citlyWa yWait it(10,Ti (10,Tim meUnit. Unit. SECONDS ); driver.get( driver .get("http:/ "http:/ / ne newtours.de wtours.dem moau oaut.c t.com om// "); xpath("/ / a")); Listallitems Listallitems =driver driver.findElements(By. .findElements(By. xpath System.out System.out .println(allitems .println( allitems.size()); .size()); Program to get the names of all the radiobuttons: WebDriver driver =new FirefoxDriver();
SECONDS); driver.man driver.m anag age e().time () .timeouts() outs().im .impli plicitl citlyWa yWait it(10,Ti (10,Tim meUnit. Unit. SECONDS ); driver.get( driver .get("http:/ "http:/ / ne newtours.de wtours.dem moau oaut.c t.com om// "); driver.findElement(By. driver .findElement(By.name("userName" "userName")).sendKeys( )).sendKeys("mercury" "mercury"); ); driver.findElement(By.name("password" "password")).sendKeys( )).sendKeys("mercury" "mercury"); ); driver.findElement(By. driver .findElement(By.name("login" "login")).click(); )).click(); xpath("/ / input[@ty Listallitems Listallitems =driver driver.findElements(By. .findElements(By. xpath input[@type pe= ='r 'rad adio']" io']")); )); le::allitems allitems)) for(WebElement ele
{ System.o System.out .println(e .println( ele le.getAttribute( .getAttribute("name" "name")); )); }
www.testingmasters.com
Te Testin ting Mas Masters tersInc Inc.
Page 11
Testing Masters Technologies
getCurrentURL():
This This metho thod is used to get the the curren rrent URL of the the web webdrive river ins instan tance. Example:
System.out System.out .println(driver .println(driver.getCurrentUrl()); .getCurrentUrl()); getTitle():
This This metho thod is used to get the the title title of the the web webdrive river ins instan tance. Example:
System.out System.out .println(driver .println(driver.getTitle()); .getTitle()); getwindowhandle():
This This metho thod is used to get the the run runtim time generate rated d page id of the the drive river ins instan tance. Example1:
System.out System.out .println(driver .println(driver.getWindowHandle()); .getWindowHandle()); Example2:
WebDriver driver =new FirefoxDriver(); driver.m driver .mana anag ge().time e().timeouts() outs().implici .implicitl tlyWa yWaiit(10, t(10, Tim TimeUnit eUnit.. SECONDS ); SECONDS); driver.manage().window().maximize(); driver .manage().window().maximize(); driver.get( driver .get("http: "http:// / ne newtours. wtours.de dem moa oaut. ut.co com m/ "); System.out System.out .println(driver .println(driver.getCurrentUrl()); .getCurrentUrl()); System.out System.out .println(driver .println(driver.getTitle()); .getTitle()); System.out System.out .println(driver .println(driver.getWindowHandle()); .getWindowHandle()); Output:
http:/ / newtours.dem newtours.demoaut.co oaut.com m/ Welcome: Welcome: Mercury Tours Tour s {38ed9a6c-dedc-4d73-a86d-1242d22f0470} getwindowhandles(): ¸ ¸
This This metho thod is used to get all the the wind window handles les of the the dive iver ins instan tance. The The wind window handles les will be retu return rne ed in the the form form a String tring set.
Code to get the window handles:
Setallhandles Setallhandles =driver driver.getWindowHandles(); .getWindowHandles(); str1::allhandles allhandles)) for(String str1 { t .println(str1 System.ou System.out .println(str1); ); } close(): ¸
Close method is used used to closeonly close only the curr current ent window of the drive driverr insta i nstance nce..
quit(): ¸
quit method method will will close all the windows of the drive driverr insta i nstance nce..
4.3 Switch To Window: web pag page will will be having having URL, URL, Titl Title, e,Window Window Handle, Handle, Docum Document. ent. ¸ Every web Dri ver object object can can poi point out to to only one webpage webpage// document document at a tim time. ¸ Driver ¸ By default driver object will be pointing out to parent window. to make make the dr driver ver object to point point out to child child window window we need need to use use the handle handle of ¸ I n order to the window.
www.testingmasters.com
Te Testin ting Mas Masters tersInc Inc.
Page 12
Testing Masters Technologies
Syntax: ¸
driver.switchTo().window(WindowHandle); The The follo followin wing g are the the step teps to be follo followe wed d to switc witch the the control trol to child wind window and get back back to par parent window window parent window window handle handle & Store in in a variab variable le v get the par v get all the window handles v switch to each window by using the handles Titl e/URL URL of the window and and verify verify v get Title/ v Perform desired actions on child window. child window window v close the child witch back back the control control to parent window. window. v Switch
Example:
WebDriver driver =new FirefoxDriver(); driver.get( driver .get("https "https:/ :/ / tale talentzing ntzing.c .com om// "); xpath("/ / a[te driver.findElement(By. driver .findElement(By. xpath a[text()= xt()='Terms & Conditions']" Conditions']")).click(); )).click(); xpath("/ / a[te driver.findElement(By. driver .findElement(By. xpath a[text()= xt()='Fee 'FeedBa dBack']" ck']")).click(); )).click(); String parentHandle parentHandle;; parentHandle= parentHandle =driver driver.getWindowHandle(); .getWindowHandle(); Setallhandles Setallhandles =driver driver.getWindowHandles(); .getWindowHandles(); for(String h1:allhandles allhandles)) { driver.switchTo().window( driver .switchTo().window(h h1); String URL =driver driver.getCurrentUrl(); .getCurrentUrl(); if (URL.contains("TermsAndConditions" .contains("TermsAndConditions")) )) { xpath("/ / input[@id='btnO driver.findElement(By. driver .findElement(By. xpath 'btnOk']" k']")).click(); )).click(); driver.close(); driver .close(); break ; } } driver.switchTo().window( driver .switchTo().window(parentHandle parentHandle); );
4.4 Switch to Frame: ¸ ¸ ¸ ¸ ¸
A fram frame e is document that that is is defined defined inside inside aparent document. document. As the driver driver object object can point to only only one frame frame at at a tim ti me, by by default default it points points to the parent document. So, inorder to perform any operation on the elements in the frame, first we need to switch to the the respective fram fr ame. Firepath view can handle only one document at a time. I n Order view view the complete complete set set of documents documents associated associated with with current curr ent webpage webpage,, we need need to move to HTML View.
www.testingmasters.com
Te Testin ting Mas Masters tersInc Inc.
Page 13
Testing Masters Technologies
The following is the process to identify a frame. ¸
¸
¸ ¸
¸
While Whil e spying spying an an object object in in normal normal page using using firep fir epath, ath,iin the top left corner, it will will show as as Top Top Wind indow.
But, while whil e spying spying an an object object which which is inside inside a frame, frame, it would would look li l ike,
Now, Select elect the HTML View, Vi ew,iinstead nstead of of fir fi repath epath view and select select the object. Trav Traverse rse the the paren rent hiera ierarc rch hy of the the selec lected ted node to ide identify tify the the fram frame details tails..
Using Using this this fram frame e detai details, but but the webelem web element ent object. WebElement WebElement ele =dri =driver.findEl ver.findElem ement(By.Xpa ent(By.Xpath( th(“/ “/// fram frame[@na e[@name me=’’login_Pag ’’login_Page]”)) e]”))
The following are the steps to switch to the frame ¸ ¸ ¸ ¸
Create a webel webelement object object to the res respective pective fra fr ame. me. Use this webelement object to switch to the frame. Perform Perform the desir desired ed oper operation in i n the frame. frame. Switch back back to the the parent parent document. document.
Code to switch to frame:
WebElementframeobj WebElement frameobj =driver driver.findElement(By. .findElement(By. xpath fram ame[@na e[@name me= ='l'login_pag ogin_page']" e']")); )); xpath("/ / fr driver.switchTo().frame( driver .switchTo().frame(frameobj frameobj); ); Code to switchback to parent document:
driver.switchTo().defaultContent(); driver .switchTo().defaultContent();
www.testingmasters.com
Te Testin ting Mas Masters tersInc Inc.
Page 14
Testing Masters Technologies
Note:
If two frames are present adjacently, then 1. first fir st we nee need to switch switch to one one frame 2. switch switch to to defa default ult con conte tent nt 3. switch switch to the the se second cond fram frame e. Example1: WebDriver driver =new FirefoxDriver(); driver.m driver .mana anag ge().tim e().timeouts().i eouts().im mplicitl plicitlyWa yWait it(10, (10, Tim Ti meUnit. SECO Unit. SECONDS ); NDS); driver.navigate().to( driver .navigate().to("https:/ "https:/ / ne netban tbanking.h king.hdfcba dfcbank.c nk.com om// ne netban tbanking/ king/ "); WebElement ele le= =driver driver.findElement(By. .findElement(By. xpath("/ / fr fram ame[@na e[@name me='l'login_pag ogin_page']" e']")); )); driver.switchTo().frame( driver .switchTo().frame(e ele le); ); driver.findElement(By. driver .findElement(By. xpath("/ / img img[@a [@alt= lt='continue']" 'continue']")).click(); )).click(); driver.switchTo().defaultContent(); driver .switchTo().defaultContent(); Example 2: WebDriver driver =new FirefoxDriver(); driver.get( driver .get("https:/ "https:/// netba netbanking. nking.hdfcba hdfcbank.c nk.com om// ne netbanking tbanking// "); WebElement frameobj =driver driver.findElement(By. .findElement(By. xpath("/ / fr fram ame[@na e[@name me='l'login_pa ogin_page ge'] ']"")); driver.switchTo().frame( driver .switchTo().frame(frameobj frameobj); ); driver.findElement(By. driver .findElement(By. xpath("/ / input[@na input[@name me= ='fl 'fldLoginUse dLoginUserI rId']" d']")).sendKeys( )).sendKeys("40058155" "40058155"); ); driver.switchTo().defaultContent(); driver .switchTo().defaultContent(); WebElement frameobj2 =driver driver.findElement(By. .findElement(By. xpath("/ / fr fram ame[@ e[@nam name='footer'] 'footer']"")); driver.switchTo().frame( driver .switchTo().frame(frameobj2 frameobj2); ); driver.findElement(By. driver .findElement(By. xpath("/ / a[te a[text() xt()= ='T 'Terms erms and Co Conditi nditions']" ons']")).click(); )).click();
4.5 Switch to Alert: ¸ ¸ ¸ ¸
Alerts are the pop ups on the webpage, which cannot be identified by the firepath spy tool. To handle the these, we need to switc witch to the the alert lert and perform rform desired ired action tions on it. At a time time a webpa webpag ge supports supports only one aler alert. t. The The follo followin wing g are the the step teps to handle alert lerts s on a web webpage. witch to the aler alertt v Switch the al alert v Get the text of the v Based on text accept or dismiss the alert. alert is closed, closed, thedrive driverr control control will wil l automatically switch back to the v After the alert parent parent page. page.
www.testingmasters.com
Te Testin ting Mas Masters tersInc Inc.
Page 15
Testing Masters Technologies
Example:
Alert a1 =driver driver.switchTo().alert(); .switchTo().alert(); String text =a1.getText(); t .println(text System.ou System.out .println(text); ); if (text text.contains( .contains("Custom "Customer er ID ID ca cannot nnot be left blank" blank")) )) { System.ou System.out .println("About to ac acce cept pt Alert" Al ert"); ); t .println("About a1.accept(); } else
{ System.ou System.out .println("About to dismiss Alert"); Alert"); t .println("About a1.dismiss(); }
5. Cr Cros osss Brow Browse ser: r: Firefox Browser:
WebDriver driver =new FirefoxDriver(); driver.get( driver .get("http: "http:// / tes testingm tingmaste sters.c rs.com om// hrm hrm""); Chrome Browser: Steps to download chrome driver: ¸ Navigate to http://www.seleniumhq.org/download/ ¸
Google: selenium selenium downloads downloads In Third Party Browser Drivers Secti Section, on, Cl Click on the ver version sion name of Google Google chrome driver.
¸ ¸
Click li ck onchromedriver_win32.zip on chromedriver_win32.zip to download the chrome driver Unzip the downloaded downloaded file file to extr extrac actt .exe .exe file. file.
Use below code in the PSVM Method: public pub lic sta static tic voi void d main(String[] args args))
{ System.setProperty ("webdriver.chrome.driver" "webdriver.chrome.driver",, "C "C:: \ \ ch chrome romedri drive ver.ex r.exe" e"); ); WebDriver driver =new ChromeDriver(); driver.get( driver .get("http:/ "http:/// www.te www.testing stingm maste sters.c rs.com om// hrm hrm""); }
www.testingmasters.com
Te Testin ting Mas Masters tersInc Inc.
Page 16
Testing Masters Technologies
IE Driver: Steps to download IE driver: ¸ Navigate to http://www.seleniumhq.org/download/ ¸ ¸ ¸
Google: selenium selenium downloads downloads Download the respe respective ctive IE IE Drive Driverr ser server ver base based d on the sys system tem type [Rig [Right Cli Click ck on my computer computer Prope Pr operrties System ystem Type] Click li ck on on this link 64 bit bit Windows Windows IE to download driver server. Unzip the the zip file file to extr extrac actt .exe .exe file. fil e. Use the below code in PSVM to work with IE Browser: System.setProperty ("webdriver.ie.driver" "webdriver.ie.driver",, "IEDriverServer.exe" "IEDriverServer.exe"); ); WebDriver driver =new InternetExplorerDriver();
driver.get( driver .get("http:/ "http:/// tes testing tingm mas asters. ters.co com m/ hrm hrm""); The following are restrictions while working with IE Browser: ¸
¸
Zoomlevel evel should be set to 100%.
www.testingmasters.com
Te Testin ting Mas Masters tersInc Inc.
Page 17
Testing Masters Technologies
Desired Capabilities: ¸ ¸
Desir Desired ed capa capabil biliities tiesare are create created d to introduc intr oduce e some some setti setting ngs, s, into the browser before launching. The The follo followin wing g is the code to ign ignore the the security rity settin tting gs and zoom lev level settin tting gs before fore launching IE Browser.
DesiredCapabilities capabilities =DesiredCapabilities. internetExplorer (); (); capabilities.setCapability(InternetExplorerDriver. capabilities .setCapability(InternetExplorerDriver.II GNORE GNORE_ _ZOO OOM_ M_SETT SETT I NG NG,, true); ODUCE_ E_FLAK FLAK I NESS_ NESS_BY_ BY_II GNORI NG_SECURI TY_ TY_DOMAI DOMAI NS , true); capabilities.setCapability(InternetExplorerDriver. I NTR ODUC capabilities.setCapability(InternetExplorerDriver. System.setProperty ("webdriver.ie.driver" "webdriver.ie.driver",, "C "C:: \ \ IEDriverS EDriverSe erver.e rver.exe xe"); WebDriver driver =new InternetExplorerDriver( InternetExplorerDriver(capabilities capabilities); );
driver.get( driver .get("http:/ "http:/ / www www.te .testingm stingmas asters.c ters.com om// hr hrm m");
6. Syn Synchr chroni onizat zation ion:: ¸ ¸
Synchronizati Synchronization oniis the Tim Ti me Interfac Interface e between between the scri script pt and web page page.. The The follo followin wing g are the the synchron roniza ization tion state tatements used in selen lenium ium Wait v Static Wait v I mplicit wait v Explicit wait Static wait: ¸ ¸ ¸
In this wait, the sc scri ript pt will will halt halt the exe execution cution for the specifi specifie ed tim time duration, duration, independent ndependent of the web web page page beha behavi vior or.. The The script ript will wait wait for the the same tim time, even if you run run it for for any number of times. Thre Threa ad.slee leep is the the metho thod used for the the static tatic wait. wait. Example:
¸
Thre Threa ad.slee leep(20 (2000) ----- For For making king the the script ript wait wait for 3seconds Gener enerally ally stati static c wait wait is not prefe pr eferrred in the the real real tim time if the the wait wait is more than than 12seconds. Note:
Static wait wait is not prefe preferr rred ed for longer longer wait durations durations beca because use,, the exe execution will will continue to halt halt even even if the elem element ent is existing existing,, befor before e the spec specif ifiied tim ti me. Example:
¸
If static static wait is specif specifiied for 10Sec 10Sec and and even even if the desir desired ed eleme element nt is is loaded loaded in 2sec, 2sec, then then also the scr script will will wait for 10sec 10seconds, onds, thus wasting remaini remaining ng 8seconds 8seconds of tim time. Static wait wait is appli applica cable ble only only for the cur current statemen statementt in i n selenium code code..
Implicit Wait: ¸ ¸ ¸ ¸ ¸
In im implicit pli cit wait, wait, the existence existenceof of the webelem webelement ent is verifi veri fied ed for ever every 0.5 sec seconds onds At any point, if if the webelem webelement ent exi exists, exec executi ution on will will continue with with the normal normal flow. flow. If the wait time has reached the max specified time and still element is not existing, then it will throw an exception. Implicit wait will be applicable throughout the driver instance. In real tim time, Most of the cas cases es we will wil l use implicit implicit wait. wait.
www.testingmasters.com
Te Testin ting Mas Masters tersInc Inc.
Page 18
Testing Masters Technologies
Example:
WebDriver driver driver= =new FirefoxDriver(); driver.m driver .mana anag ge().time e().timeouts() outs().implici .implicitl tlyWa yWait it(10, (10, Ti TimeUni eUnit. SECONDS ); SECONDS); Note:
¸
If Once Once impli implicit cit wait is defined, defined, the algori algorithm thm of implicit wait will wi ll be appli applica cable ble for all drive dri verr.findElem .findElement statem statements. ents. if we declar declare e implicit implicit wait wait once that is enough enough for the whole scri script. pt.
Explicit Wait: ¸ ¸ ¸
Explicit wait is same as implicit wait, but only difference is that explicit wait is applicable for the specified webelement. I n Gener eneral expli explicit cit wait is is not much much preferred preferr ed.. Explicit Explicit wait is suggest est able able only only for those webe webelem lements, ents, which can can take some some abnormall abnormally y long times to load load the el element ement v which v check for the conditions of a webelement.[Wait until the element is enabled] Example:
WebDriverWait w1 w1= =new WebDriverWait(driver WebDriverWait( driver,, 40); WebElement ele le= = w1.until(ExpectedConditions. w1 .until(ExpectedConditions. presenceOfElementLocated (By. (By.id ("oway" "oway"))); )));
ele le.click(); .click();
7. Adv Advance anced d User User Act Actions ions:: * Mouse Mouse hover * Right Click * Drag N Drop * Scr Scroll down page page * Scroll down to webelement Mouse Hover: ¸ ¸ ¸
Create object for action class. Use movetoelement method method.. Use .buil .build() d() and .per .perform() Example:
Actions a1 =new Actions(driver Actions(driver); ); xpath("/ / spa WebElementmainMenu WebElement mainMenu =driver driver.findElement(By. .findElement(By. xpath span[tex n[text() t()= ='Men']" 'Men']")); )); a1.moveToElement(mainMenu .moveToElement( mainMenu).build().perform(); ).build().perform(); Right Click: ¸ ¸ ¸
Create object for Actions Object Use contect contect cli click method. method. use .bui .build() ld( ) and .perfor .perform m() Example:
WebDriver driver driver= =new FirefoxDriver(); driver.get( driver .get("https "https:/ :/ / tale talentzing ntzing.c .com om// "); driver.manage().window().maximize(); driver .manage().window().maximize(); driver.m driver .mana anag ge().time e().timeouts() outs().implici .implicitl tlyWa yWaiit(5, t(5, TimeUnit TimeUnit.. SECONDS ); SECONDS);
www.testingmasters.com
Te Testin ting Mas Masters tersInc Inc.
Page 19
Testing Masters Technologies
Drag n Drop: ¸ ¸ ¸
Create acti actions ons obje object use movetoelement and dragAndDrop Methods use .bui .build() ld( ) and .perfor .perform m() Example: xpath("/ / div[@id=' drag WebElementdrag WebElement drag= =driver driver.findElement(By. .findElement(By. xpath dragg gab able']" le']")); )); xpath("/ / div[@id=' droppable']" WebElementdrop WebElement drop =driver driver.findElement(By. .findElement(By. xpath droppable']")); )); Actions action =new Actions(driver Actions(driver); ); action.moveToElement( action .moveToElement(drag drag).dragAndDrop( ).dragAndDrop(drag drag,, drop drop).build().perform(); ).build().perform();
Scroll Page: ¸ ¸ ¸ ¸ ¸ ¸
Create Create Object Object for JavaS avaScri criptExe ptExecutor cutor by typecas typecasti ting ng dr driver ver instance nstance.. use scollby scollby method method Scrol Scrolll Rig Ri ght x + Scrol Scrolll down y + Scroll UpyScroll left xExample:
Jav JavascriptE riptEx xecutor tor js =(JavascriptExecutor) =(JavascriptExecutor)driver driver;; js.executeScript( js .executeScript("window.scrollBy(0,500)" "window.scrollBy(0,500)"); ); Scroll to WebElement: ¸ ¸
Create Object for JavaScript Executor Use scrollintoView Method Example:
Jav JavascriptE riptEx xecutor tor js =(JavascriptExecutor) =(JavascriptExecutor)driver driver;; xpath("/ / abbr[tex WebElementelement WebElement element= =driver driver.findElement(By. .findElement(By. xpath bbr[text() t()= ='01:4 '01:44']" 4']")); )); js.executeScript( js .executeScript("arguments[0].scrollIntoView();" "arguments[0].scrollIntoView();",, element element); );
8. Ex Exce cel: l: ¸ ¸
Download apac apache he POI POI jar files. files. Confi Config gure the jar fil fi les to the ecli eclipse pse projec projectt [Right Click li ck on Project Build Build Path Configure onfigure Build Path Libraries Li brariesAdd Add External External Jars Add the jar files]
¸ ¸ ¸ ¸
Create the objects Based Based on the Object Object Hierarchy Hierarchy Defi Defined. ned. To Crea reate an objec ject for the the fileins instan tance, use below low code File f1 f1= =new File("E:\ File("E:\\\ Tm Tma aste sters\ rs\ \ Selen leniu\ iu\ \ Me MercuryD rcuryDa ata ta.x .xlsx lsx""); Creati Creating ng File File Input I nput Stream Stream FileInputStream fis =new FileInputStream(f1); Work Work book/ WorkShe WorkSheet et objects has has to be created base based d on the fil file extention extention type. type.
Example:
XSSFWorkbook wb wb1 1 =new XSSFWorkbook(fis XSSFWorkbook(fis); ); XSSFSheet ws ws1 1 =wb wb1 1.getSheet("Sheet1" .getSheet("Sheet1"); );
www.testingmasters.com
Te Testin ting Mas Masters tersInc Inc.
Page 20
Testing Masters Technologies
¸
Celll Obj Ce Object can can be cr created eated by usi using the row and column numbers. numbers. Syntax:
Celll ObjectName =SheetObject.g Ce =SheetObject.getRow( etRow(RowNumbe RowNumberr).getCe .getCelll(ColumnNum (ColumnNumber) ber);; Example: ¸
Cell c1 =ws ws1 1.getRow(2).getCell(0); Read the data from the Cell System.ou System.out .println(c1.getStringCellValue()); t .println(c Note: v v
Index ndex of a row wil willl start from from 0. Index ndex of a ce cell will will start start from from 0.
Code to read Data Fom Excel: File f1 f1= =new File("C File("C:\ :\ \ Us Use ers\ \ ba balu\ lu\ \ Do Downloa wnloads ds\\ \ Me MercuryD rcuryDa ata ta..xls xlsx x"); FileInputStream fis fis= =new FileInputStream(f1 FileInputStream(f1); ); XSSFWorkbook wb wb1 1 =new XSSFWorkbook(fis XSSFWorkbook(fis); );
XSSFSheet ws ws1 1 =wb wb1 1.getSheet("TestData" .getSheet("TestData"); ); Cell c1 =ws ws1 1.getRow(2).getCell(1); System.out System.out .println(c .println(c1.getStringCellValue()); wb1.close(); wb1 fis.close(); fis .close();
RowCount: ¸
To get the the number of rows rows in the the excel we can use System.ou System.out .println(ws1 1.getLastRowNum()); t .println(ws
CellCount: ¸
To get cell count in the excel, wecan use System.ou System.out .println(ws1 1.getRow(4).getLastCellNum()); t .println(ws Here, 4 is the row number.
NOTE: ¸ ¸
getLastRowNum getLastRowNum will will return the last index of a row Whereas Whereas getLastC getLastCellNum ellNum will will return last index of a cell + 1.
Code to Print the Value of all the cells in Row 1: int columncount =ws ws1 1.getRow(1).getLastCellNum(); columncount;;cn++) for(int cn =0;cn
{ Cell c1 =ws ws1 1.getRow(1).getCell(c .getRow(1).getCell(cn); System.ou System.out .println(c1.getStringCellValue()); t .println(c }
www.testingmasters.com
Te Testin ting Mas Masters tersInc Inc.
Page 21
Testing Masters Technologies
Code to Print all the values of a Sheet of excel: File f1 f1= =new File("E:\ File("E:\\\ Tm Tma aste sters\ rs\ \ Selen lenium ium\\ \ Me MercuryD rcuryDa ata ta.x .xlsx lsx""); FileInputStream fis fis= =new FileInputStream(f1 FileInputStream(f1); ); XSSFWorkbook wb wb1 1 =new XSSFWorkbook(fis XSSFWorkbook(fis); );
XSSFSheet ws ws1 1 =wb wb1 1.getSheet("Sheet1" .getSheet("Sheet1"); ); int rowcount =ws ws1 1.getLastRowNum(); for(int i =0;i<=rowcount rowcount;;i++) { int colcount =ws ws1 1.getRow(i .getRow(i).getLastCellNum(); colcount;;k++) for(int k =0;k
wb1.close(); wb1 fis.close(); fis .close(); Code to Write Data to a cell of Excel: File f1 f1= =new File("E:\ File("E:\ \ Me MercuryDa rcuryData. ta.xlsx xlsx""); FileInputStream fis fis= =new FileInputStream(f1 FileInputStream(f1); ); XSSFWorkbook wb wb1 1 =new XSSFWorkbook(fis XSSFWorkbook(fis); );
XSSFSheet ws ws1 1 =wb wb1 1.getSheet("Sheet1" .getSheet("Sheet1"); ); Cell c1 =ws ws1 1.getRow(1).getCell(1); if (c1==null) { c1 =ws ws1 1.getRow(1).createCell(1); } c1.setCellValue("NewPassword" .setCellValue("NewPassword"); ); fis.close(); fis .close(); FileOutputStream fo fos s =new FileOutputStream(f1 FileOutputStream( f1); ); wb1 wb 1.write(fo .write(fos s); fos fo s.close(); wb1 wb 1.close();
10.. Se 10 Sele leni nium um RC: RC: ¸ ¸ ¸
¸
Selenium RC stands for selenium Remote control. The The follo followin wingis gis the the arch rchitec itecture ture of selen lenium ium RC. The The follo followin wing g are the the limita limitatio tion ns of selen lenium ium RC: * It I t uses selense com comma mands nds which which are are java script scri pt commands commands *To decrypt these commands, selenium uses RC Server. *And to launch l aunch the server, some some of the ports ports have have to be opened. opened. Becau Because se of these limitations limitations selenium webdri webdrive verr is intr introduced oduced..
www.testingmasters.com
Te Testin ting Mas Masters tersInc Inc.
Page 22
Testing Masters Technologies
11. Sel Seleni enium um Gri Grid: d: ¸ ¸
¸
Sel Selenium Gr Grid can can be used for remote emote exec executi ution/ on/ Parall Parallel el Executi Execution on of the testcases. testcases. The The follo followin wing g are the the major jor components in the the selen lenium ium grid. rid. * Hub * Node The The follo followin wing g are the the key thin thing gs tha that are inv involve lved in Selen lenium ium Grid setup tup and execution ion * Creati Creation on of Hub * Creation of Node and register to the Hub * Ver Verify ify the registr egistration ation to the Hub Hub * Trigger execution in a node from the hub. Creation Creation of of Hub: ÿ ÿ
Open command command pr prompt ompt Typ Type the the follo followin wing g command by specifyin ifying g the the selen lenium ium serve rver jar jar file file path. java -jar "C:\selenium-server-standalone-2.53.0.jar" -role hub
ÿ
ÿ ÿ
After clicking clicking on enter enter the the following following mes messa sag ge will wil l be display displayed ed
By default default hub will wi ll be launched launched in 4444 Port. Por t. The The same can be viewe iewed d from from "http ttp:/ / loc localho lhost:4 t:4444/ grid/ rid/ console" le" URL
www.testingmasters.com
Te Testin ting Mas Masters tersInc Inc.
Page 23
Testing Masters Technologies
Creation of Node and register to the Hub: 1) Register Register Local Machi Machine ne Firefox Firefox Node: Node: ¸ ¸
Open command command pr prompt Typ Type the the follo followin wing g command by specifyin ifying g the the selen lenium ium serve rver jar jar file file path. java -jar "C:\selenium-server-standalone-2.53.0.jar" -role webdriver -hub http://192.168.0.121:4444/grid/register -port 8585
¸
¸
After Clicking Clicking on enter enter the followi foll owing ng messa essag ge will wil l be displaye displayed d
The The same can be viewe iewed d in the the
2) Register Register Remote Firefox Firefox Node: ¸ ¸
Open command command pr prompt Typ Type the the follo followin wing g command by specifyin ifying g the the selen lenium ium serve rver jar jar file file path. th. java -jar "C:\selenium-server-standalone-2.53.0.jar" -role webdriver -hub http://192.168.0.105:4444/grid/register http://192.168.0.105:4444/grid/r egister -port 8585
¸
The The same can be viewe iewed d in the the
www.testingmasters.com
Te Testin ting Mas Masters tersInc Inc.
Page 24
Testing Masters Technologies
3) Register Register Local Local Chrome Chrome Node: Node: ¸ ¸
Open command command pr prompt Typ Type the the follo followin wing g command by specifyin ifying g the the selen lenium ium serve rver jar jar file file path. java -Dwebdriver.chrome.driver= -Dwebdriver.chrome.driver="C:\chromedriver.exe" "C:\chromedriver.exe" -jar "C:\selenium-server-standalone-2.53.0.jar" -role webdriver -hub http://192.168.0.105:4444/grid/register -port 6565
¸
The The same can be viewe iewed d in the the
4) Register Register Local IE Node: ¸ ¸
Open command command pr prompt Typ Type the the follo followin wing g command by specifyin ifying g the the selen lenium ium serve rver jar jar file file path. java -Dwebdriver.ie.driver="C:\IEDriv -Dwebdriver.ie.driver="C:\IEDriverServer.exe" erServer.exe" -jar "C:\selenium-server-standalone-2.53.0.jar" -role webdriver -hub http://192.168.0.105:4444/grid/register -port 4545
www.testingmasters.com
Te Testin ting Mas Masters tersInc Inc.
Page 25
Testing Masters Technologies
Configure hub with selenium code:
The The follo followin wing g is code for for crea reating ting a werb werbd drive river objec ject in a node firefox (); DesiredCapabilities capability =DesiredCapabilities. firefox (); capability.setBrowserName( capability .setBrowserName("firefox" "firefox"); ); capability.setPlatform(Platform. capability .setPlatform(Platform.WINDOWS ); WINDOWS); WebDriver driver =new RemoteWebDriver(new URL("h URL("http ttp:/ :/ / 192.168.0.105:56 :5656 56// wd/ hu hub" b"), ),capability capability); ); Note:
Desir Desired ed capab capabiiliti li ties es are are used to config configure the the setti setting ngs s of the browser instance nstance..
12.. Au 12 Auto toIT IT:: Auto It V3 is afreewa a freeware re tool which is used used for autom automa ating ting anything anything in Windows environment. Auto It script is written in BASIC language. It can simulate any combination of keystr keystrokes okes,, mouse mouse move movem ment and window/ window/ contr control ol manipulation. Whiledoing While doing automation through Seleniumor Selenium or through any other tool for that matter, we all encounter a common problem, windows pop-ups. As Selenium is confined to automating browsers, desktop window is out of scope. Web applications sometimes need to interact with the desktops to perform perform things like like file file download downloads s and uploads. uploads. There are tools tools avai available for automating these these sorts of workflow such as AutoIt . We can upload or download the files or images by transferring our control our control from Selenium WebDriver to AutoIt. AutoI t. We need need to expli explicitl citly y call call the the AutoIt AutoI t script script from from our prog progrram. Steps to use AutoIT:
Find Find theprope the properti rties es using using the AutoIT finder tool desiired windows wi ndows object. object. ÿ Drag the Finder tool and drop it on the des The Prop Properties rties of the the elem lement such as Title, Class and and instance will be displayed. ÿ The ontrolID D =Class =Class +Instance ÿ ControlI
www.testingmasters.com
Te Testin ting Mas Masters tersInc Inc.
Page 26
Testing Masters Technologies
Example:
ÿ ÿ
Class Class =Edit =Edit Instance =1 The Then, ControlID trolID =Edit1. it1. Use the title and Control ID in the scripti scripting ng.. The The follo followin wing g are the the commands used for for Auto AutoIT IT Scriptin ripting g *ControlFocus -- focus on the object object *ControlClick -- click on the the object object *ControlSetText -- enter enter tex text *Sleep -- wait wait in i n mil milli li seco seconds nds Example:
ÿ ÿ ÿ ÿ
Sleep(3000); ControlFocus("File Upload","","Edit1"); ControlClick("Fi ontrolClick("File le Upload", Upload","", "","Edit1"); "Edit1"); Contr ControlSe olSetT tTex ext( t("Fi "File le Upload Upload","", ","","Edit1","C:\ "Edit1","C:\ abcd. abcd.xlsx"); xlsx"); Sleep(3000); ControlClick("File Upload","","Button1"); Save Save the code with with .au3 extenti extention. on. RightCli RightClick ck on the .au3 .au3 extention extention fil fileC eCompil ompile e the scri script pt .Exe fil file wil will be gene generraed aed in in the same same path. path. Trigg Trigger this this exe file file to run run the the Auto AutoIT IT Script. ript.
Code to trigger .exe file from Java: getRuntime().exec("C Runtime. getRuntime ().exec("C:\ :\ \ Us Use ers\ \ Tm Tma aste sters\ rs\ \ De Deskto sktop\ p\ \ Brows Browse e.e .ex xe"); Selenium Code Example: WebElement element =driver driver.findElement(By. .findElement(By. xpath("/ / input[contains(@na input[contains(@name me,'flUpdRes ,'flUpdResum ume')]" e')]")); ));
element.click(); element.click(); Thre Threa ad.sleep(2000); getRuntime().exec("C Runtime. getRuntime ().exec("C:\ :\ \ Us Use ers\ \ Tm Tma aste sters\ rs\ \ De Deskto sktop\ p\ \ Brows Browse e.e .ex xe");
13.. Ro 13 Robo bott Keys Keys:: ¸ ¸ ¸ ¸
Robot Keys Keys ar are used used to gener generate keyboard keyboard actions actions from from java. java. For this, this, first first we nee need to create an object object for Robot class. The Then, use KeyPress or KeyRelease methods based on the need. The The follo followin wing g is the code to copy a specific tex text to clipb lipboard String filepath filepath= ="E:\ \ Tm Tmas asters\ ters\ \ Sele elenium nium\\ \ TmBa TmBatch1 tch19_ 9_S Sep ept_ t_7. 7.30AM\ 30AM\\\ Coll ollec ections. tions.doc docx" x";; StringSelectionselection StringSelection selection =new StringSelection(filepath StringSelection(filepath); ); getDefaultToolkit ().getSystemClipboard(); Clipboard clipboard =Toolkit. getDefaultToolkit ().getSystemClipboard(); clipboard.setContents( clipboard .setContents(selection selection,,selection selection); );
Code to browse file file using ROBOT Keys Keys in Java: xpath("/ / input[@c driver.findElement(By. driver .findElement(By. xpath input[@clas lass= s='browse 'browsefil file']" e']")).click(); )).click(); Thre Threa ad.sleep(2000);
String filepath filepath= ="E\ \ Coll olle ections. ctions.doc docx" x";; StringSelectionselection StringSelection selection =new StringSelection(filepath StringSelection(filepath); ); getDefaultToolkit ().getSystemClipboard(); Clipboard clipboard =Toolkit. getDefaultToolkit ().getSystemClipboard(); clipboard.setContents( clipboard .setContents(selection selection,,selection selection); );
www.testingmasters.com
Te Testin ting Mas Masters tersInc Inc.
Page 27
Testing Masters Technologies
Robot robo =new Robot(); robo.keyPress(KeyEvent. robo .keyPress(KeyEvent.VK_CONTROL ); VK_CONTROL); robo.keyPress(KeyEvent. robo .keyPress(KeyEvent.VK_V ); VK_V ); VK_V ); robo.keyRelease(KeyEvent. robo .keyRelease(KeyEvent.VK_V ); robo.keyRelease(KeyEvent. robo .keyRelease(KeyEvent.VK_CONTROL); VK_CONTROL); Thre Threa ad.sleep(3000); robo.keyPress(KeyEvent. robo .keyPress(KeyEvent.VK_ENTER ); VK_ENTER); robo.keyRelease(KeyEvent. robo .keyRelease(KeyEvent.VK_ENTER); VK_ENTER );
14. TestNG Tes TestNG tNG Stan tands for for Tes Test Next Generatio ration n Fram Framework,it work,it is softwa ftware re whic which h prov rovide ides some facilities through annotations which make the testing job easier as it is making some(testing) job more easy people generally call it as TestNG Framework. Steps to Install TestNG: ¸ ¸ ¸
¸ ¸
Open Eclipse Go to Help>>I nstall New Softw Software are Click Click on add, add, provide below below details detail s Name: Name: TestNG TestNG Location: http:/ http:/// www.be www.beust. ust.co com m/ eclipse Sel Select theT the TestNG Checkbox Checkbox and and click cli ck on Next Accept license agreement and click on finish.
Annotation in TestNG: ¸ ¸
Annotations in tes testNG tNG are use used d to control the flow of exec executi ution on of program at run tim time. The The follo followin wing g are the the annotatio tation ns tha that can be used in Tes TestNG tNG @Test @Beforetest @AfterTest @BeforeSuite @AfterSuite @BeforeClass @AfterClass @BeforeMethod @AfterMethod @DataProvider
Steps to create a First TestNG class: ¸ ¸ ¸ ¸ ¸
Right Ri ght Cli Click on package>>New> New>>Others> Others>>Testng estng class class Provide the name, Select the required annotations and click on finish. By Default Default a methods methods will wil l be cr created eated with with @Test Annotation. Wriite a code in the body Wr body of default default annotati annotation on and click click on run. we can can also exec execute ute by right rightcli clicki cking ng on .java fil file>run as as >>TestNG >TestNG Suite/ Test
Multiple Methods: ¸ ¸
I f we have multipl multi ple e methods methods under the same annotati annotation, on, by defualt they they wil wi ll be exec executed uted in the al alphabeti phabetical cal order order of the method method name names. The The Orde rder of execution tion of the the metho thods is ind independent of the the Orde rder of writin writing g the the metho thods on the code.
www.testingmasters.com
Te Testin ting Mas Masters tersInc Inc.
Page 28
Testing Masters Technologies
Output:
Executing Method1 Executing Method2 Executing Method3 Setting Priorities for TestNG: ¸ ¸
By default TestNG Methods will be executed in the alpahabetical order of the method names. If we want to redefine the order of execution of the methods, then we have to set the priori pri oriti tie es for eac each method. ethod. Example:
@Test(pri @Test (priority ority =1) =1) public pub lic voi void d Login() { System.out System.out .println("Method .println("Method to Login into i nto appli applica cati tion" on"); ); } Note: v v v
Prior Pr ioriities ties can can also take nag nagative values. values. Priorities can be any integer no necessarily consecutive integers. If more than one test is having same priority, then alphabetical oder of the methods are considered. Example: public publ ic clas classs Tes Test1
{ @Test(priority @Test (priority =-100) public pub lic voi void d Login() { System.out System.out .println("Method .println("Method to Login Login into i nto appli applica cation" tion"); ); } @Test(priori @Test (priority ty =2) =2) public pub lic voi void d AddSkillSetDetails() { System.out System.out .println("Method .println("Method to AddSkillSetDetails"); AddSkillSetDetails"); } @Test(pr @Test (priori iority ty =1000 =10000) 0)
www.testingmasters.com
Te Testin ting Mas Masters tersInc Inc.
Page 29
Testing Masters Technologies
public pub lic voi void d Logout()
{ System.out System.out .println("Method .println("Method to Logout"); Logout"); } @Test(priority @Test(priori ty =3) =3) public pub lic voi void d AddEducationDetails() { System.out System.out .println("Method .println("Method to AddAddEducationDetails"); AddAddEducationDetails"); } } Output:
Method to Login into application Method to AddSkil AddSkilllSetDeta etDetailils s Method to Logout Method to AddAddEduca AddAddEducati tionDe onDetail tails s @BEFORETEST,@AFTERTEST: ¸ ¸
The The metho thod under @Before foreTe Tes st annotatio tation n, will be executing ting before fore first first metho thod under @Test annotation. The The Meth Metho od under @Afte fterTes rTest annotatio tation n will be executed ted afte fter the the las last method under @Test annotation. Example: public pub lic cla class ss Tes Test1
{ @Test(priority @Test (priority =-100 =-100)) public pub lic voi void d Login() { System.ou System.out .println("Method to Logi Login into applica appli cati tion" on"); ); t .println("Method } @Test(pri @Test (priority ority =2) =2) public pub lic voi void d AddSkillSetDetails() { System.out System.out .println("Method .println("Method to AddSkillSetD AddSkil lSetDeta etaiils" ls"); ); } @Test(priority @Test (priority =10000) public pub lic voi void d Logout() { System.ou System.out .println("Method to Log L ogout" out"); ); t .println("Method } @Test(pri @Test (priority ority =3) =3) public pub lic voi void d AddEducationDetails() { System.out System.out .println("Method .println("Method to AddAddEduc AddAddEducationDe ationDetail tails" s"); ); } @BeforeTest public pub lic voi void d LaunchBrowser() { System.out System.out .println("Method .println("Method to Lau LaunchBrowse nchBrowserr"); } @AfterTest public pub lic voi void d CloseBrowser() www.testingmasters.com
Te Testin ting Mas Masters tersInc Inc.
Page 30
Testing Masters Technologies
{ System.ou System.out .println("Method to CloseBrowser"); CloseBrowser"); t .println("Method } } Output:
Method to LaunchBrowser Method to Login into application Method to AddSkil AddSkillSetD lSetDeta etailils s Method to AddAddEduca AddAddEducati tionDe onDetail tails s Method to Logout Method to CloseBrowser Steps to Create A XML File for for Executing TestNg Clasess: ¸ ¸ ¸ ¸ ¸
¸
Right Ri ght Cli Click on the the package>>Go to TestN TestNG> G>>Convert Convert to to TestN TestNG G>>Specify Specify Detail Details>>Cli Click on Finish. A XML File Fi le will will be created created at at the project location. double click on XML file to edit the details in XML file. Right Right Click Click on XMl Fil Fi le>>Run as>>TestNG Suite Suite to run r un the the test cases cases insi inside de a package package.. The The follo followin wing g is an example XML File of executing ting the multip ltiple le tes test cases ins inside ide a packag kage > classes classes> > test test> > suite suite> > The The follo followin wing g is an example XML File of executing ting all the tes test cases ins inside ide a packag kage > packages packages> > test test> > suite suite> >
Grouping The Test Cases in TestNG: ¸
¸
¸
To add a specific ific tes testNg tNg Meth Metho od to a grou roup , weuse mention tion the them as below low @Test(priority @Test (priority =3,groups="group1" "group1")) public pub lic voi void d Logout() { System.ou System.out .println("Logout"); ); t .println("Logout" } For adding the sam same method method under multi multipl ple e gr groups, we can can menti mention on as bel below @Test(pr @Test (priiority ori ty =2,groups= =2,groups={"group1" "group1",,"group2" "group2"} }) public pub lic voi void d CreateAdmin() { System.ou System.out .println("CreateAdmin"); ); t .println("CreateAdmin" } The The follo followin wing g is the XML File of executing ting the the tes testca tcases based on the the grou roup names.
www.testingmasters.com
Te Testin ting Mas Masters tersInc Inc.
Page 31
Testing Masters Technologies
> ru run n> groups groups> > > packages packages> > test test> > suite suite> > Note:
With the the abov above e XML XML File, File, >>all the methods methods which whi ch bel belong to gr group2 are excluded excluded for execution. execution. >>and all the methods methods which which bel belongs to gr group1 are included included for execution execution First Fi rst the Methods Methods will will be excluded, excluded, Ne Next xt the remaini remaining ngm methods ethods will wil l be filtered filtered for inclusive inclusive criteria. Parameterization In TestNG from XML: ¸
The The below low is the the forma rmat for for writin riting a Tes TestNG tNG Met Method whic which h can accept param rameters ters from from XML @Test @Parameters(("UserID" @Parameters "UserID")) public pub lic voi void d parameterTest(String parameterTest(Stringstr1 str1)) { t .println("Parameterized System.ou System.out .println("Parameterized value is : " +str1 str1); ); }
¸
The The follo followin wing g is the XMl Form Forma at for for passing ing the the value lue. > classes classes> > test test> > suite suite> >
Using Data Providers in TestNG: ¸ ¸
DataPr DataProvi oviders ders in in TestNg can can be used to execute execute a test case case with with mul multi tiple ple set of test test data. The The follo followin wing g is an example for for executing ting a metho thod with with data prov rovide ider. public pub lic cla class ss DataProviderExample
{ / / Thi This s test test method method declares declares that that its its data should be suppli supplied ed by by the Data Data Pr Provider ovider / / "g "getda etdata" ta" is the the function function name name which is i s passing passing the data / / Num Numbe berr of columns should should match match the numbe berr of input input paramete parameters rs @Test(dataProvider= @Test (dataProvider="getData" "getData")) public pub lic voi void d setData(String username username,, Str Striingpassword ng password))
www.testingmasters.com
Te Testin ting Mas Masters tersInc Inc.
Page 32
Testing Masters Technologies
{ System.ou System.out .println("you have provided provided usernam username e as::" as::"+ +username username); ); t .println("you System.ou System.out .println("you have provided password as::"+ as::"+password password); ); t .println("you } @DataProvider public Object[][] getData() { / / Rows - Num Numbe berr of time times s your your test has has to be repea repeated. ted. / / Co Columns lumns - Num Numbe berr of paramete parameterrs in test test data. data. Object[][] data data= =new Object[3][2]; / / 1st row row data[0][0] data [0][0] ="sampleuser1" "sampleuser1";; data[0][1] data [0][1] ="abcdef" ="abcdef";; / / 2nd row data[1][0] data [1][0] ="testuser2" "testuser2";; data[1][1] data [1][1] ="zxcvb" ="zxcvb";; / / 3rd ro row w data[2][0] data [2][0] ="guestuser3" "guestuser3";; data[2][1] data [2][1] ="pass123" ="pass123";; return data data;;
} }
Parallel Execution In testNg: ¸
¸
TO Execute tes testca tcases Para Parala lally lly in Tes TestNG tNG, we can use below low XML Form Forma at > packages packages> > test test> > suite suite> > Thre Threa ad Count Specifie ifies the the number of tes tests tha that can be executed ted at a time.
www.testingmasters.com
Te Testin ting Mas Masters tersInc Inc.
Page 33
Testing Masters Technologies
15.. Ma 15 Mave ven: n: Maven is a project management and comprehension tool. Maven provides developers a complete build lifecycle framework. Development team can automate the project's build infrastructure in almost no time as Maven uses a standard directory layout and a default build lifecycle. In case of multiple development teams environment, Maven can set-up the way to work as per standards in a very short time. As most of the project setups are simple and reusable, Maven makes life of developer easy while creating reports, checks, build and testing automation setups. Maven primary goal is to provide ∑
A comprehensive model for projects which is reusable, maintainable, and easier to comprehend.
∑
Plug Plug-i -in n or tools tools that that inte i nterac ractt with wi th this declarative declarative mode model. l.
Maven project structure and contents are declared in an xml file, pom.xml referred as Project Object Model (POM), (POM), which which is is the fundam fundamental ental unit of the entire entir e Maven Maven syste system m Steps to create Maven Project: ¸ Open eclipse[preferably version above helper] Go to file>>New> New>>Other> Other >>Maven Maven Project oject> >>Next> Next>>Next> Next>>Next ¸ Goto ¸ Specify GrouID,ArtifactID. enerally ally GroupId: oupI d: Com Company pany Name Name ¸ Gener ArtifactID: ProjectName Packagename will will be auto auto populated as as GroupI GroupID. D.Ar Arti tifac factI tID D ¸ Package
www.testingmasters.com
Te Testin ting Mas Masters tersInc Inc.
Page 34
Testing Masters Technologies
¸ ¸ ¸ ¸ ¸
On cli clicking cking finish, finish, Maven Maven Projec Projectt will wi ll be cr created eated along along with with pom.X pom.XML ML file. fil e. I N this this XML file, fi le, we need need to add add the depe dependen ndencies[Unique cies[Unique ID] of the respective respective jar files. files. By default default junit junit dependen dependency cy will will be adde added. d. Remove Remove juni junitt dependenc dependency y and rem r emove ove the unnecessary unnecessary fil fi les. Now, get get the requ requir ired ed Unique ID [depende [dependency] ncy] of the required requir ed jar file fi le from fr om https://mvnrepository.com
¸ ¸ ¸
Paste this dependency in POM.xml file and click on save. Now, the respective respective jar files files will will be downl download oaded ed from maven aven reposit repository ory and assoc associiated ated with with the current maven project. I n This Thi s way the jar files fil es will will be asso associated ciated with the the projec proj ectt automatica automaticalllly y base based d on the speci specified fied dependency. dependency.
www.testingmasters.com
Te Testin ting Mas Masters tersInc Inc.
Page 35
Testing Masters Technologies
16.. Fr 16 Fram amew ewor ork: k: ¸
A fram fr amework ework is a set of rules rules or guidelines uidelinesthat that are to be followed followed for easy easy deve developme lopment nt and maintenance aintenance of of the the test test scripts. scripts. Types of Frameworks:
* Linear Framework * Data Driven Framework * Keyword Drive Dri ven n Fram Framework * Modular Framework * Hybri Hybrid d Driven Fram Framework. Linear Framework: ¸
The The follo followin wing g are the the disa isadvantag tages of using ing the the line linear coding ing *No Logfile/ fil e/Re Reports ports *Multi *Multiple test test case case exec executi ution on is not possibl possible e *Error handling is not easy *Maintenance *Maintenance of test test data is difficu diffi cult lt *Maintena *Maintenanc nce e of the test test scri scripts pts is difficu diffi cult. lt. *Reusa *Reusabil biliity of the codeis not achieve achieved. d. *To overcome these limitations the other framework types are introduced.
Data Driven framework: ¸ ¸ ¸
In data driven framework the testdata is placed in some external sources such as Excel Files/ Fi les/ Databa Database ses s As the execution is driven from the data taken from external sources this is named as data driven framework. The The follo followin wing g are the the key fea feature tures s of the the data drive riven fram framework work * TestData should be placed in external sources * Provision for easy maintenance of the testdata. * Provisi Pr ovision on for a testcas testcase e with with multiple sets of testdata .
Keyword Driven Framework: Framework: ¸ ¸ ¸
¸ ¸
I n this this fram framewor ework, k, some some gene generric methods/ methods/ classes classes wil will be cr created eated which which can can be acces accessed sed across across all them the modules/ odules/projec projects. ts. The These key keyword words s are design igned conside idering ring the the overall rall usage of the the metho thods of a web webdrive river. The The key keyword words s can be of two two typ types * Web General Keywords * Applica Appli cati tion on Gene General ral Keywords The These key keyword words s are writte written n alon long with with error rror handling ling and ackno knowled wledgements. ts. Using Using these keywords, keywords, wil wi ll ease the process of the development development of testscri test scripts. pts.
Modular Driven Framework: ¸ ¸
I n Modular drive dri ven n fra framework, the com common test steps steps acr acrossall oss all the test test case cases s in a module module are identified. And methods methods are created for these comm common steps which which can can resue resued d acr across all the testcripts testcripts of that res respec pecti tive vem module.
www.testingmasters.com
Te Testin ting Mas Masters tersInc Inc.
Page 36
Testing Masters Technologies
¸
By using these reu reusa sable ble methods, ethods, the ma maintenance ntenance of the test test scripts scripts will wi ll be abette abetted d easy easy when the properti properties es of the objects got got changed. changed.
Hybrid Driven Framework: ¸ ¸ ¸
Hybrid driven framework can be combination of two or more types aof the above three types of frameworks. Tma Tmasters ters fram framework work is the the combina ination tion of data drive riven, hybrid drive riven and keyword word drive riven frameworks. This This fram framework work has follo followin wing g components. ts. Components Components of framewor framework: k:
* Trigg Tr igger.b er.ba at file fi le * RunManager * TestData * Driver Scri Script pt * Generi Generic c Resources *T Tes estCa tCase se Defi Definiti nitions ons * Jar File Fil es * Result Results s Trigger.Bat: ¸ ¸ ¸ ¸
This This file file is used to trigger the the executio tions of the the tes testca tcases. Trigg Trigger.b r.bat file file will inte intern rn inv invokes kes the the drive river script/ ript/Te Tes st Runner script. ript. Tes Test Runner Script ript will Takec Takeca are of the the furth furthe er execution tions. This This is framework specific file
Run Manager: ¸
This This is an excel file file in whic which h all the the tes testca tcase info inform rma ation tion is store tored d alon long with with execution tion fla flag The The follo followin wing g is the the tem template late of the the Run Man Manager file file
¸
Here the test engi engineer neer can can select the testcases testcases that are to to be exe executed cuted in the current current Run. So, So, for the test test script script deve development, lopment, the first first ta task will will be to menti mention on the testcas testcase e in the runmanager.xls file. This This is a project specific file
¸ ¸
TestData:
¸
I n this this folder folder we have have to specify specify the testdata testdata that is req requir uired ed for the the exe execution cution of the testcase The The Tes TestDa tData is store tored d agains inst the the tes testcase names in the these file files The The follo followin wing g is the tem template late of specifyin ifying g the the tes testda tdata
¸
The The Tes Testda tdata is store tored d in the the form forma at of Field FieldNa Nam me:=Tes TestDa tData For For Tha That Field Field
¸ ¸
Example:
UserName:=user02 Name:=Srinivas
www.testingmasters.com
Te Testin ting Mas Masters tersInc Inc.
Page 37
Testing Masters Technologies
Driver Script/TestRunner Script: ¸ ¸ ¸ ¸ ¸
This This is the the core script ript of the the framework work whic which h drive rives the the complete lete execution tion. Tes Test Runner Contain tains s the public stat tatic void main metho thod. Tes Test Runner script ript opens the the Runmanager fileand checks, ks, wha what are the the testca tcases tha that are set for execution. All All the testcases testcases that are are sel selected ected are are execute executed d one by one sequenti sequentiall ally. y. This This is framework specific script.
JarFiles: ¸ ¸ ¸ ¸
In This Folder all the required jar files for the framework are placed. The These jar jar file files inc includ ludes POI, POI, Selen lenium ium, Exte Exten nt Report file files. So, So, for setting a projec project, t, fir first we need need to Add thes these e jar files files to the projec projectt in in the ecli eclipse pse.. This This is framework specific component.
TestCase Definitions: ¸ ¸ ¸ ¸ ¸
I n this, we will will define define the actua actuall test test scri scripts pts code code.. We wil will create create a method method for every every testcas testcase, e,iinside test.testcases package. The The tes testca tcase name should be same in RunMan Manager,Te r, Tes stDa tData Sheet,me t,metho thod Na Nam me in tes test. testcases package. package. While Whil e wri writing ting the testca testcase ses, s, we will will use the the nece necessa ssary ry methods ethods which which ar are alr alrea eady dy defined in weblibrary and userlibrary classes . This This is a project specific folder
Results: ¸ ¸ ¸ ¸
In this folder, results will be generated for every run. For every every run, run,a a folder is crea created ted with with a date and time time stam stamp. Inside the folder the respective screenshots and results summary.html is stored. This This will be a project specific folder
Generic Resources: ¸ ¸ ¸ ¸ ¸
This This contain tains s the the reu reusableme lemetho thods for for work workin ing g with with excel sheets, ts, Report generatio ration n, Working Working with with WebPag Web Pages es etc.. etc.. This This is generally rally a framework specific folder . The The metho thods or clas lasses in this this folde lder can be used by the the drive river script ript or tes testca tcase definitio finition ns. The These are specifie ified in test.resources.generic package. The These metho thods are define fined in the the WebLibrary of Generic resources.
WebLibrary: ¸ ¸ ¸
I n this li library all the methods ethods that that are required requir edfor for the interacti nteractions ons with the webp webpag age e are are specified. The These metho thods can be used while develop loping ing a tes testca tcase for for perform rformin ing g operatio ration ns on the webelements. The The follo followin wing g are the the sample metho thods in WebLibra Library ry *SetText *ClickElement *SetTextAndEscape *Exist *SelectOPtionByText *SelectOPtionByValue *OpenUrl
www.testingmasters.com
Te Testin ting Mas Masters tersInc Inc.
Page 38
Testing Masters Technologies
¸
The The metho thods in this this libra library ry are generic, framework specific and can can be useful useful in i n wri writing ting the testcase.
FrameWork Library: ¸ ¸ ¸ ¸
I n this this library, li brary, the method methods s that ar are requir required ed for the functioni functioning ng of of the frame framework work are placed. Most of the meth methods ods present present in this this librar li brary y ar are use used d internall internally y by the framework. framework. very rarel rarely y these methods wil will be used used in in the devel development opment of the testcases. testcases. The The metho thods in this this libra library ry are generic, framework specific and and will will be use useful ful for framework functioning.
UserLibrary: ¸ ¸ ¸ ¸ ¸ ¸
I n this this li library, the Test Engineer Engineer can can add method methods s for the reusable reusable steps steps across across the testcases. Before/ After writi wr iting ngthe the testcas testcases es,, Test Engi Engineer neer will will check check for the reusabil reusabiliity com compone ponents nts in the testca testcase. se. Will Wil l chec check k if i f the me method alr alrea eady dy ex exists for this functionali functionality. ty. If existing, TE can use that method in the testcase. Else Else,, TE can can add amethod to the user user librar li brary. y. generic, project project specific specific and can The The metho thods in this this libra library ry are generic, can beuseful useful in wri writing ting the testcase.
FrameWork Flow:
www.testingmasters.com
Te Testin ting Mas Masters tersInc Inc.
Page 39
Testing Masters Technologies
Java Basics: Variable: ¸
a variable variable is is a named named mem memor ory y spacecreated at the runti runtime me.. int x; x =5; System.ou System.out .println(x); t .println(x
¸
x is a variab variable le here, for which which the mem memory is i s created created at at runti r untim me.D e. D
DataType: ¸
DataType DataType spec speciifie fies the type of data th that at a var variable can can store. store.
Ope perrator ators s in in ja java va:: ¸ ¸ ¸ ¸ ¸ ¸
Assignment operators: = Concatenation operator: + Arithm Ari thmetic etic operato operators: rs: +, - , * , / ,% Compar Compariison son oper operat ator or:: <,>,<=,>=,==,!= Logical operator: &&,||,! Tern Terna ary operato rator: r: ?:
Conditional Statements: ¸
Conditional Conditi onal statements statements are used used to make make a decision decision
¸
In java we have two types of conditional statements. Ë
If …else
Ë
Switch… Switch… case case
If--- Els Else e: ¸
Whenever Whenever we we want to execute execute one block of statements statements among amongtwo blocks blocks then we can can use If-Else If-El se.. Syntax:
if(condition) { block of stmts1 stmts1 } else { block of stmts2 stmts2
www.testingmasters.com
Te Testin ting Mas Masters tersInc Inc.
Page 40
Testing Masters Technologies
} ¸
If the condition condition is true tr ue then then block of stmts1 will wil l be execute xecuted d
¸
If the condition conditi on is false, false, then the block of stmts2 stmts2 will will be ex executed. ecuted.
Switch…case: ¸
Whenever Whenever we we want to exec execute ute a particular parti cular block block of statem statements among among many many blocks then then we will choose switch case statement.
Syntax:
switch(choice) { case “c1”: block1 break; case “c2”: block 2 break; ----------Defa Default: ult: ------ / / not manda ndatory }
Looping State tatem ments: ¸
Looping Loopi ng statements statements ar are used used for exec executi uting ng a certain certain block of statem statements ents repeatedl repeatedly y and and continuously for some number of times.
¸
In java java we have 3 types of loopi looping ng statem statements ents Ë
for loo loop p
Ë
while loo loop p
Ë
do…while loop
www.testingmasters.com
Te Testin ting Mas Masters tersInc Inc.
Page 41
Testing Masters Technologies
for loop: ¸
Whenever Whenever we clearly clearly know how many many no of time times s the block should be repeated repeated then use for loop. syntax:
for(ini for(initiation tiation ;condition ;condition ;improve ;improvem ment) ent) { ------------------------------ block block of of stm stmts ts } While loop: ¸
It is used for executing a block of statements repeatedly as long as the condition is bei being sati satisfi sfied ed.. Syntax:
while( condition) { ------------- block block of stmts stmts } do- while loop: ¸
It is used for executing a block of statements repeatedly as long as the condition is bei being satisfi satisfied ed,, but first fir st tim time exe execution cution wil willl be done done without without checking checking the conditi condition. on. Syntax:
do { -------------block of stmts } while(condition) ;
www.testingmasters.com
Te Testin ting Mas Masters tersInc Inc.
Page 42
Testing Masters Technologies
Arrays: array is a coll colle ection of sim si milar data types. types. ¸ An array ¸ Array is also known as static data structure because size of an array must be specifi specified ed at at the the time of of its i ts declar declaration. ation. ndex of ar array starts from from zero ¸ I ndex ndex of arr array aywi willll end at at le length-1. ngth-1. ¸ Index Example: package coreJava; public class P06_Arrays { public static void main(String[] args args))
{ int [] [] arr =new int [10]; [10]; for(int i=0;i<10;i <10;i++)
{ System.ou System.out .println("Currren entt Value in Array Ar ray at index : "+ "+arr rr[[i]); t .println("Cu arr rr[[i]=i; } t .println("--------------------------------------------------" System.ou System.out .println("--------------------------------------------------" ); for(int i=0;i<10;i <10;i++) { System.ou System.out .println("Currren entt Value in Array Ar ray at index : "+ "+arr rr[[i]); t .println("Cu } } }
String Methods Length: ¸
This This metho thod will retu return rn the the number of charac racters ters in a string tring. Example:
String str1 ="abcdef" "abcdef";; System.ou System.out .println(str1.le .leng ngth() th()); ); --6 --6 t .println(str1 CharAt: ¸
This This metho thod is used to get the the charac racter ter at the the specified ified ind index of a string tring. Example:
String str1 ="abcdef" "abcdef";; System.ou System.out .println(str1.c .cha harAt( rAt(0)); 0)); --a --a t .println(str1 System.ou System.out .println(str1.c .cha harAt( rAt(3)); 3)); --d --d t .println(str1 Input: Index Output: Character at specified index Note: v
For a string string,, the indexwill will start from fr om 0 and and end at at n-1[where n-1[where n is the leng length th of a string]
www.testingmasters.com
Te Testin ting Mas Masters tersInc Inc.
Page 43
Testing Masters Technologies
Program to Print each Character of a String:
String str1 ="abcdef" "abcdef";; for(int i =0;i
This This metho thod verifie rifies s if a main string tring is start tartin ing g with with the the specified ified set of charac racters ters.. If Yes returns true else returns false. false. Example:
String str1 ="abcdefg" "abcdefg";; System.ou System.out .println(str1.startsWith( .startsWith("abc" "abc")); )); -- returns returns true t .println(str1 System.ou System.out .println(str1.startsWith( .startsWith("bcd" "bcd")) ));; -- returns returns false false t .println(str1 Ends-With: ¸
This This metho thod verifie rifies s if a main string tring is ending ing with with the specifie ified set of charac racters ters.. If Yes returns true else returns false. false. Example:
String str1 ="abcdefg" "abcdefg";; System.ou System.out .println(str1.endsWith( .endsWith("efg" "efg")); )); -- returns returns true t .println(str1 System.ou System.out .println(str1.endsWith( .endsWith("xyzefg" "xyzefg")) ));; -- returns returns false false t .println(str1 Contains: ¸
This This metho thod verifie rifies s if a main string tring contain tains s the the specified ified set of charac racters ters ind independant of the position. If Yes returns true else returns false. false. Example:
String str1 ="abcdefg" "abcdefg";; System ystem.out. .out.pri println(str ntln(str1. 1.co conta ntains("cde ins("cde")) "));-;-- returns true System.ou System.out .println(str1.contains( .contains("xyzefg" "xyzefg")) ));; -- returns returns false false t .println(str1 indexOf: ¸
This This metho thod will verify rify the the existe isten nce of the the substrin tring g in the the main string tring, if exists, exists, returns returns the first first matc matching hing charac character ter position. positi on. else, else, returns returns -1. Input: Set Set of char character acters s Output: Index ndex Positi Position on Example:
String str1 ="abcdefg"; System ystem.out.pri .out.printl ntln(str n(str1.index 1.indexOf("cde Of("cde")) "));; -- 2 System.out.println(str1.indexOf("x")); -- -1 Note: v v
IndexO ndexOff Method will wil l consider only the first fir st occuranc occurance e of the sub str striing in the main string. LastInde LastIndexO xOff Method will will consi consider only only the last occuranc occurance e of the sub str string ing in in the main stri string. ng.
www.testingmasters.com
Te Testin ting Mas Masters tersInc Inc.
Page 44
Testing Masters Technologies
sub String: ¸
This This metho thod is used to extrac tract a sub string tring from from the main string tring, based on the the ind index positions specified. Inputs: Begi Begin Index Position, Positi on,End End Index Position{ Positi on{Optional} ptional} Output: sub str striing from from the main main string stri ng Syntax:
MainString MainStri ng.S .Substri ubstring ng(BeginI (BeginIndex ndex,, EndInde EndIndex) x) Begin Index Character is Inclusive. End Inde I ndex x Charac Character ter is i s Exclusive. Note: v
If End Inde I ndex x is not specifi specified ed,, it will will condier condier till ti ll the end end cha character racter positi position. on.
Split: ¸ ¸
This This metho thod is used to extrac tract sub string trings from from main string tring , based on the specified ified character{Delimiter} This This metho thod splits lits the the main string tring and retu return rns s in the the form form of string tring array rray. Syntax:
MainString.Split(Delimiter) Example1:
String str1 ="AP;TG;TN;KA;DEL" "AP;TG;TN;KA;DEL";; String []arrstr []arrstr =str1 str1.split( .split("";"); for(int i=0;i
String str1 ="AP;TG;TN;KA;DEL" "AP;TG;TN;KA;DEL";; String []arrstr []arrstr =str1 str1.split( .split("";"); for(String ele le::arrstr arrstr)) { System.ou System.out .println(ele le); ); t .println(e } Join: ¸ ¸
This This metho thod is used to join join the the conten tents of an array rray using ing the the delimite limiter. r. This This metho thod join joins s the the array rray value lues and ret returns rns res result in the the form of string tring. Example:
String str2 str2;; String []arrstr []arrstr ={"AP","TG","DEL"}; join(",", arrstr str2 =String. join arrstr); ); System.ou System.out .println(str2); ); t .println(str2 Replace: ¸
This This metho thod is used to rep replac lace a set of old charac racters ters with with a set of new charac racters ters syntax:
String. Stri ng.Repa Repallce(Old Set of Characters,New Set Set of Characters) Example:
String str1 str1= ="wel "welcom come e to hyderaba hyderabad" d";; System.ou System.out .println(str1.replace( .replace("hyderabad" "hyderabad",, "chennai" "chennai")); )); t .println(str1
www.testingmasters.com
Te Testin ting Mas Masters tersInc Inc.
Page 45
Testing Masters Technologies
to UpperCase,toLowerCase: ¸
The These metho thods are used to cover all the the alph lphabetica tical charac racters ters in a strin tring to eithe ither lowe lowerr case or upper case. Example:
String str1 ="ABcd12#$%E" "ABcd12#$%E";; System.ou System.out .println(str1.toLowerCa .toLowerCase se() ()); ); / / abcd abcd12# 12#$%e t .println(str1 System.ou System.out .println(str1.toUpp .toUpperC erCas ase() e()); ); / / ABCD12# ABCD12#$%E t .println(str1 equals: ¸
This This metho thod is used to compare both the the strin trings, If both are equa equal, l, retu returns rns true tr ue else, returns false. Syntax:
String1.equals(String2) Example:
String str1 ="firefox" "firefox";; String str2 ="Firefox" "Firefox";; if (str1 str1.equals( .equals(str2 str2)) )) System.ou System.out .println("Both are equal"); equal"); t .println("Both else
System.ou System.out .println("Both are not equal"); equal"); t .println("Both NOTE: v v
While Whil e worki working with with string string for compari comparision sion alway always s use equa equals ls or equalsingno equalsingnoreca recase se methods but not ==Operator. Beacuse, ==operator will compare the address, where as equals method compares the actual actual values.
Trim: ¸
This This metho thod is used to rem remove the the lea leading ing and trailin trailing g spaces in a string tring. starting
¸
ending
This This metho thod does not rem remove the the spaces tha that are pres resent in betwe tween. Example:
String str1 =" ha haii hello hello how? how? "; "; t .println(str1 System.ou System.out .println(str1.length()); .length()); str1 =str1 str1.trim(); .trim(); System.ou System.out .println(str1.length()); .length()); t .println(str1 Output:
17 14
www.testingmasters.com
Te Testin ting Mas Masters tersInc Inc.
Page 46
Testing Masters Technologies
Class and Object Class:
A class is a blue-print blue-print// template of an an object. object. A class can contain variables vari ables and and methods. methods. For a class, class,g gener enerally ally mem memory is not alloca allocated. ted.
¸ ¸ ¸
Object: ¸ ¸ ¸
An Object is is an instance of a class. The The memory is alloc llocated ted, whe when an objec ject is crea reated ted for for a clas lass. By using using the object reference reference,, the values can can be assigned assigned to the the var variables.
Syntax for creating a class:
class ClassName { datatype variable1; datatype variable2; datatype variable3; | | | } Example: class Student
{ String name name;; String fathername fathername;; int standard standard;; int id id;; char gender gender;; String schoolname schoolname;; } Syntax for creating an object for a class:
classname objectname =new classname(); example:
Students Student s1 =new Student(); ¸ ¸
Here,when an object is created, the memory is aloocated for the variables in the below format. To access the the assign igned variab riable momeory loc location tions, we need to use objectname.variablename
Example for assigning values for an object variables:
s1.name name= ="kiran" "kiran";; s1.fathername fathername= ="sai" "sai";; s1.standard =10; s1.id =415; s1.gender ='M 'M''; s1.schoolname ="Delhi Public School"; School";
www.testingmasters.com
Te Testin ting Mas Masters tersInc Inc.
Page 47
Testing Masters Technologies
Example for printing the values of an object variables:
System.ou System.out .println(s1.name name); ); t .println(s System.ou System.out .println(s1.fathername fathername); ); t .println(s t .println(s System.ou System.out .println(s1.standard standard); ); System.ou System.out .println(s1.id id); ); t .println(s System.ou System.out .println(s1.gender gender); ); t .println(s System.ou System.out .println(s1.schoolname schoolname); ); t .println(s Complete code: package basicJava; public pub lic cla class ss ClassNObject
{ public pub lic sta static tic voi void d main(String[] args args))
{ Students Student s1 =new Student(); s1.name name= ="kiran" "kiran";; s1.fathername fathername= ="sai" "sai";; s1.standard =10; s1.id =415; s1.gender ='M 'M''; s1.schoolname ="Delhi Public School"; School"; System.ou System.out .println(s1.name name); ); t .println(s System.ou System.out .println(s1.fathername fathername); ); t .println(s System.ou System.out .println(s1.standard standard); ); t .println(s System.ou System.out .println(s1.id id); ); t .println(s t .println(s System.ou System.out .println(s1.gender gender); ); System.ou System.out .println(s1.schoolname schoolname); ); t .println(s } } class Student
{ String name name;; String fathername fathername;; int standard standard;; int id id;; char gender gender;; String schoolname schoolname;; }
Static –Non Static Variables: Non-Static Variables: ¸ ¸ ¸ ¸
All All the vari variab ables les which which do not contai contain stati static c keyword in the declar declaration ation are non-static variables. By defau default lt vari varia ableswi bles willll be non-static. non-static. For non-static var variables mem memory will wi ll be all alloca ocated ted at at object level. To access non-sta -static tic variab riables les, we need to use objec jectna tname[objectname.variablename]
Static Variables:
www.testingmasters.com
Te Testin ting Mas Masters tersInc Inc.
Page 48
Testing Masters Technologies
¸ ¸ ¸
The The variab riables les whic which h contain tain,, the the stati tatic c key keyword word in the declara laratio tion n are static tatic varible ribles s. For static variables, the memory is allocated at the class level. to access static variables, we can use classname[ classname.variablename]
Example Prog For static Variables: package basicJava; public pub lic cla class ss ClassNObject
{ public pub lic sta static tic voi void d main(String[] args args))
{ Student s1 =new Student(); s1.name name= ="kiran" "kiran";; s1.fathername fathername= ="sai" "sai";; s1.standard =10; s1.id =415; s1.gender ='M 'M''; System.ou System.out t .println(s .println(s1.name name); ); System.ou System.out .println(s1.fathername fathername); ); t .println(s t .println(s System.ou System.out .println(s1.standard standard); ); System.ou System.out .println(s1.id id); ); t .println(s System.ou System.out .println(s1.gender gender); ); t .println(s System.ou System.out .println(Student.schoolname); t .println(Student. Student s2 =new Student(); s2.name name= ="srinivas" "srinivas";; s2.fathername fathername= ="maruthi" "maruthi";; s2.standard =9; s2.id =514; s2.gender ='M 'M''; System.ou System.out .println(s2.name name); ); t .println(s System.ou System.out .println(s2.fathername fathername); ); t .println(s t .println(s System.ou System.out .println(s2.standard standard); ); System.ou System.out .println(s2.id id); ); t .println(s t .println(s System.ou System.out .println(s2.gender gender); ); schoolname System.ou System.out .println(Student. ); t .println(Student. } } class Student
{ String name name;; String fathername fathername;; int standard standard;; int id id;; char gender gender;; static String schoolname ="Delhi Public School"; School"; } Constructor:
www.testingmasters.com
Te Testin ting Mas Masters tersInc Inc.
Page 49
Testing Masters Technologies
constr constructor uctor is i s something something which is is used used for constructi constructing ng an an object ver very easil easily y
¸
Syntax:
[modifi [modifier] er] ClassNam ClassName([ e([datatype datatype argument1, argument1, datatype argument2,… argument2,…..]) { Propertyname1=argument1; Proper Pr opertyname2=argume tyname2=argument2; nt2; . . . . . } Inheritance:
It is i s a concept concept provided provided in jav java a which is is used used for extending extending the par parent class class stub to the child child
¸
class. Note: v
one class can’t extend more than one classes at a time in java.
v
one class can can implem implement one or more ore interf interfac aces es at at a tim ti me.
Overriding: ¸
if at all a function is existing in the parent class and the same function with same arguments we wri write in child chil d class class that conce concept pt is is known as ove overri rr iding.
Overloading: ¸
If at all we have the same function more than once in a class with different arguments (may be no or type of arguments) then that concept is known as overloading.
Note: v
While Whil e call calliing any any function we we can can call the required required values values..
v
A function can return a value, if at all we want to return a value in the place of void we need to write data type of function and in the body we must write a return statement.
www.testingmasters.com
Te Testin ting Mas Masters tersInc Inc.
Page 50
Testing Masters Technologies
Collections: The following are the drawbacks of using arrays: Once the arrays arr ays are are defined, defi ned, we can cannot change the size of an array at run ti time. ¸ Once ¸ ¸ ¸ ¸ ¸
To verify the the existe isten nce of value lues in an array rray the there is no pred redefine fined metho thod. It is not possible to add or remove the memory locations of the indexes indexes in an ar array. It is not possible to verify the duplicate values automa automati tica calllly y in in an ar array. For an ar array the inde index x is alway always s an integ integer with wi th consecutive consecutive values values [ 0 to n-1] n-1] Collections Collections can be be used used to over overcome come the drawbacks of using arrays arrays..
Collections: ¸ ¸ ¸
Coll Collec ecti tions ons refer to a kind of dynam dynamic ar arrays ays in jav java. a. I f we we use collections, coll ections, elements elements can can be searched searched easil easily, y, removed removed or added easil easily. y. The The follo followin wing g are the the basic typ type of collec llection tions: * ArrayLi Ar rayList{ st{Class} Class}-- List{ Li st{I nterface} nterface} * HashSet{ HashSet{Class}-- Set{ Set{Interface} nterface} * HashMap{Class}-- Map{Interface} nterface}
Array List: ¸ ¸
¸
Arr Array list li st can have have can can have have duplicate dupli cate values. values. I mport the followi foll owing ng packag packages es import jav java.util. til.Array rrayList; List; import jav java.util. til.List; List; Code to declare arraylist and assign values Listarr1 Listarr1 =new Arr ArrayList< ayList Stri ng>(); arr1.add( arr1 .add("Kiran" "Kiran"); ); arr1.add( arr1 .add("Arjun" "Arjun"); ); arr1.add( arr1 .add("Avinash" "Avinash"); ); arr1.add( arr1 .add("Arjun" "Arjun"); );
¸
Code to veri verify existance of va vallue: System.ou System.out .println(arr1.contains( .contains("Arjun" "Arjun")); )); t .println(arr1
¸
Code to remove value from list arr1.remove( arr1 .remove("Avinash" "Avinash"); );
¸
Code Code to print print all the values values of a list list for(String ele le::arr1 arr1)) { System.ou System.out t .println(e .println(ele le); ); } Code to add value at speci specified fied index arr1.add(0, arr1 .add(0,"xyz" "xyz"); );
¸
HashSet: ¸ ¸
duplicate values. Set Set is is similar similar to list, list, but only differenc difference e is that Set does not accept duplicate Set Set wil willl ignore if if we are trying trying to assign assign any any duplica duplicate te values. values.
www.testingmasters.com
Te Testin ting Mas Masters tersInc Inc.
Page 51
Testing Masters Technologies
public pub lic sta static tic voi void d main(String[] args args))
{ String str1 ="abcdcaabbccccddddefa" "abcdcaabbccccddddefa";; char charr1 charr1[] [] =str1 str1.toCharArray(); .toCharArray(); Setarr1 Setarr1 =new HashSet(); for(char c1:charr1 charr1)) { if (arr1 arr1.add( .add(c c1)) { System.out System.out .println(c .println(c1); } } } Note: ¸ ¸ ¸
In List and Set, the index value is an integer. I n order to to use theindex the index value as String or any other datatype, we can can use Maps. HashMap is the class of Map Interface.
HashMap: ¸ ¸ ¸ ¸
I n HashMap HashMap the values values can can be stored in the form form of key and and value value pairs. pair s. The The follo followin wing g is the code for for declarin laring g the the hashmap and using ing the them. I n Map, the key text should always be unique . The The value can be duplicated. micromax icromax -- 5 apple -- 65 htc -- 30 sam samsung-- 20 Example:
Map er>allitems allitems =new HashMap<>(); allitems.put( allitems .put("micromax" "micromax",, 55); allitems.put( allitems .put("apple" "apple",, 65); allitems.put( allitems .put("htc" "htc",, 30); allitems.put( allitems .put("samsung" "samsung",, 20); System.ou System.out .println(allitems.get( .get("htc" "htc")); )); t .println(allitems Map er>allitems allitems =new HashMap<>(); allitems.put( allitems .put("micromax" "micromax",, 55); allitems.put( allitems .put("apple" "apple",, 65); allitems.put( allitems .put("htc" "htc",, 30); allitems.put( allitems .put("samsung" "samsung",, 20); Setallkeys =allitems allitems.keySet(); .keySet(); for(String ek:allkeys allkeys)) { System.ou System.out .println(allitems.get( .get(e ek)); t .println(allitems }
www.testingmasters.com
Te Testin ting Mas Masters tersInc Inc.
Page 52
Testing Masters Technologies
www.testingmasters.com
Te Testin ting Mas Masters tersInc Inc.
Page 53