0% found this document useful (0 votes)
6 views115 pages

Selenium - Webdriver Notes

The document compares Selenium and QTP, highlighting Selenium's advantages as an open-source tool that supports multiple browsers and operating systems, while noting its limitations in testing non-web applications and lack of built-in features like an IDE. It details various Selenium commands categorized into actions, accessors, and assertions, along with locators for identifying HTML elements. Additionally, it introduces WebDriver, a more advanced tool for automating web application testing, emphasizing its direct interaction with browsers and improved functionality over Selenium RC.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views115 pages

Selenium - Webdriver Notes

The document compares Selenium and QTP, highlighting Selenium's advantages as an open-source tool that supports multiple browsers and operating systems, while noting its limitations in testing non-web applications and lack of built-in features like an IDE. It details various Selenium commands categorized into actions, accessors, and assertions, along with locators for identifying HTML elements. Additionally, it introduces WebDriver, a more advanced tool for automating web application testing, emphasizing its direct interaction with browsers and improved functionality over Selenium RC.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 115

Selenium

AdvantagesofSelenium
QTP and Selenium are the most used tools in the market forsoftware automation
testing. Hence it makes sense to compare the pros of Selenium over QTP.

Selenium QTP

Seleniumisanopen-sourcetool. QTPisacommercialtoolandthereisacost
involved in each one of the licenses.

Can be extended for various Limitedadd-onsandneedsadd-onsfor


technologiesthatexposeDOM. each one of the technologies.

Hascapabilitiestoexecute CanruntestsinspecificversionsofFirefox, IE,


scripts across different and Chrome.
browsers.

Canexecutescriptsonvarious WorksonlywithWindows.
operating systems.

Supportsmobiledevices. Supportsmobiledeviceswiththehelpof
third-party tools.

Executes tests within the NeedsFocusduringscriptexecution,asthe tool


browser, so focus is NOT acts on the browser (mimics user actions).
requiredwhilescriptexecutionis in
progress.

Can execute tests in parallel QTP cannot execute tests in parallel,


withtheuseofSeleniumGrids. however integrating QTP with QC allows
testerstoexecuteinparallel.QCisalsoa
commercial tool.

1
i
Selenium

DisadvantagesofSelenium
LetusnowdiscussthepitfallsofSeleniumoverQTP.

Selenium QTP

Supportsonlyweb-based Cantestbothwebanddesktop applications.


applications.

No feature such as Object QTPhasbuilt-inobjectrepositoriesand


Repository/RecoveryScenario recovery scenarios.

NoIDE,sothescriptdevelopment won't MoreintuitiveIDE;automationcanbe


be as fast as QTP. achieved faster.

Cannotaccesscontrolswithinthe Canaccesscontrolswithinthebrowser such


browser. as favorites bar, backward, and forward
buttons.

Nodefaulttestreport generation. Defaulttestresultgenerationwithinthe


tool.

For parameterization, users has to Parameterizationisbuilt-inandeasyto


relyontheprogramminglanguage. implement.

2
SELENESECOMMANDS
SSeellee
nniiuum

A command refers to what Selenium has to do and the commands in Selenium


are of three types:
 Actions
 Accessors
 Assertions
Actions
Actions are commands that manipulate the state of the application. Upon
execution, if an action fails, the execution of the current test is stopped. For
example, "click a link" and "select an option".
The following table lists the Selenium action commands that are used very
frequently, however the list is note exhaustive.

Command/Syntax Description

click(locator) Clicks on a link, button,


checkboxorradiobutton

clickAt(locator,coordString) Clicks on an element with


thehelpoflocatorandco-
ordinates

close() Simulates the user clicking


the"close"buttoninthetitle
bar of a popup window or
tab.

contextMenuAt(locator,coordString) Simulates opening the


context menu of the
specifiedelementfroma
specified location

3
Selenium

doubleClick(locator) Double clicks on a


webelementbasedonthe
specified element.

dragAndDrop(locator,movementsString) Dragsanelementandthen
drops it based on specified
distance.

dragAndDropToObject(Dragobject,dropobject) Dragsanelementanddrops it
on another element.

Echo(message) Printsthespecifiedmessage
on consolewhich is used for
debugging.

fireEvent(locator,eventName) Explicitlysimulateanevent,
totriggerthecorresponding
"onevent" handler

focus(locator) Movethefocustothe
specified element

highlight(locator) Changes the background


color of the specified
elementtoyellowwhichis
useful for debugging
purposes.

mouseDown(locator) Simulates a user pressing


theleftmousebuttononthe
specified element.

4
Selenium

mouseDownAt(locator,coordString) Simulates a user pressing


theleftmousebuttonatthe
specified location on the
specified element.

mouseUp(locator) Simulates the event that


occurs when the user
releasesthemousebutton

mouseUpAt(locator,coordString) Simulates the event that


occurs when the user
releasesthemousebutton
at the specified location.

open(url) OpensaURLinthespecified
browser and it accepts both
relative and absolute URLs.

openWindow(url,windowID) Opens a popup window.


Afteropeningthewindow,
user need to activate it
using the selectWindow
command.

pause(waitTime) Waitsforthespecified
amount of time (in
milliseconds)

refresh() Simulates the user clicking


the"Refresh"buttonontheir
browser.

select(selectLocator,optionLocator) Select an option from a


drop-downusinganoption
locator.

5
Selenium

selectWindow(windowID) Selects a popup window


using a window locator;
onceapopupwindowhas
been selected, all focus
shifts to that window.

store(expression,variableName) The name of a variable in


which the result is to be
storedandexpressionisthe
value to store.

type(locator,value) Sets the value of an input


field,similartousertyping
action.

typeKeys(locator,value) Simulates keystroke events


onthespecifiedelement,as
though you typed the value
key-by-key.

waitForCondition(script,timeout) Executes the specified


JavaScript snippet
repeatedlyuntilitevaluates
to "true".

waitForPageToLoad(timeout) Waitsforanewpageto
load.

waitForPopUp(windowID,timeout) Waitsforapopupwindowto
appear and load.

windowFocus() Givesfocustothecurrently
selected window

6
Selenium

windowMaximize() Resizethecurrentlyselected
windowtotakeuptheentire
screen

Accessors
Accessors evaluate the state of the application and store the results in a variable
which is used in assertions. For example, "storeTitle".
The following table lists the Selenium accessors that are used very frequently,
however the list is not exhaustive.

Command/Syntax Description

assertErrorOnNext(message) PingsSeleniumtoexpect
an error on the next
commandexecutionwith
an expected message.

storeAllButtons(variableName) ReturnstheIDsofall
buttonsonthe page.

storeAllFields(variableName) Returns the IDs of all


inputfieldsonthepage.

storeAllLinks(variableName) ReturnstheIDsofalllinks on
the page.

storeAllWindowIds(variableName) Returns the IDs of all


windowsthatthebrowser
knows about in an array.

7
Selenium

storeAllWindowTitles(variableName) Returns the names of all


windowsthatthebrowser
knows about in an array.

storeAllWindowNames(variableName) Returns the titles of all


windowsthatthebrowser
knows about in an array.

storeAttribute(attributeLocator,variableName) Gets the value of an


element attribute. The
valueoftheattributemay
differ across browsers.

storeBodyText(variableName) Getstheentiretextofthe
page.

storeConfirmation(variableName) Retrievesthemessageof
aJavaScriptconfirmation
dialog generated during
the previous action.

storeElementIndex(locator,variableName) Gettherelativeindexof
anelementtoitsparent
(starting from 0).

storeLocation(variableName) GetstheabsoluteURLof the


current page.

storeSelectedIds(selectLocator,variableName) Gets all element IDs for


selected options in the
specifiedselectormulti-
select element.

8
Selenium

storeSelectedIndex(selectLocator,variableName) Gets index (option


number,startingat0)for
selected option in the
specified select element.

storeSelectedLabel(selectLocator,variableName) Gets label (visible text)


forselectedoptioninthe
specifiedselectelement..

storeSelectedValue(selectLocator,variableName) Gets value (value


attribute)forselected
optioninthespecified
select element.

storeSelectOptions(selectLocator,variableName) Gets all labels in the


specifiedselectdrop-
down.

storeTable(tableCellAddress,variableName) Gets the text from a cell


ofatable.ThecellAddress
syntax:
tableLocator.row.column,
where row and column
start at 0.

storeText(locator,variableName) Gets the text of an


element. This works for
anyelementthatcontains
text.

storeTitle(variableName) Getsthetitleofthe current


page.

storeValue(locator,variableName) Getsthe(whitespace-
trimmed) value of an
inputfield.

9
Selenium

storeChecked(locator,variableName) Gets whether a toggle-


button(checkbox/radio)is
checked.

storeElementPresent(locator,variableName) Verifiesthatthespecified
elementissomewhereon
the page.

storeTextPresent(pattern,variableName) Verifiesthatthespecified
text pattern appears
somewhere on the
rendered page shown to
the user.

storeVisible(locator,variableName) Determines if the


specifiedelementis
visible.

Assertions
Assertions enable us to verify the state of an application and compares against
the expected. It is used in 3 modes, viz. - "assert", "verify", and "waitfor". For
example, "verify if an item from the dropdown is selected".

The following table lists the Selenium assertions that are used very frequently,
however the list is not exhaustive.

Command/Syntax Description

waitForErrorOnNext(message) Waitsforerror;usedwith the


accessor assertErrorOnNext.

10
Selenium

verifySelected(selectLocator,optionLocator) Verifiesthattheselected
option of a drop-down
satisfies the
optionSpecifier.

waitForSelected(selectLocator,optionLocator) Waits for getting the


optionselected;usedwith
the accessor
assertSelected.

waitForNotSelected(selectLocator,optionLocator) Waits for not getting the


optionselected;usedwith
the accessor
assertSelected.

verifyAlert(pattern) Verifies the alert text;


usedwiththeaccessor
storeAlert.

waitForAlert(pattern) Waitsforthealert;used with


the accessor storeAlert.

verifyAllButtons(pattern) Verifiesthebutton;used with


the accessor
storeAllButtons.

waitForAllButtons(pattern) Waits for the button to


load; used with the
accessorstoreAllButtons.

verifyAllLinks(pattern) Verifiesalllinks;usedwith
theaccessorstoreAllLinks.

11
Selenium

waitForAllLinks(pattern) Waitsforalllinks;used with


the accessor storeAllLinks.

verifyAllWindowIds(pattern) Verifiesthewindowid;
usedwiththeaccessor
storeAllWindowIds.

waitForAllWindowIds(pattern) Waitsthewindowid;used
with the accessor
storeAllWindowIds.

verifyAttribute(attributeLocator,pattern) Verifiesanattributeofan
element; used with the
accessor storeAttribute.

waitForAttribute(attributeLocator,pattern) Waitsforanattributeofan
element; used with the
accessor storeAttribute.

verifyBodyText(pattern) Verifies the body text;


usedwiththeaccessor
storeBodyText.

waitForBodyText(pattern) Waitsforthebodytext; used


with the accessor
storeBodyText.

waitForConfirmation(pattern) Waits for confirmation;


used with the accessor
storeConfirmationPresent

12
Selenium

Locators
Element Locators help Selenium to identify the HTML element the command
refers to. All these locators can be identified with the help ofFirePath and
FireBugplugin of Mozilla. Please refer the Environment Setup chapter fordetails.
 identifier=idSelect the element with the specified "id" attribute and if
there is no match, select the first element whose @name attribute is id.
 id=id Selecttheelementwiththespecified"id"attribute.

 name=nameSelectthefirstelementwiththespecified"name"attribute

 dom=javascriptExpressionSelenium finds an element by evaluating


thespecifiedstring thatallowsus totraversethroughtheHTML Document
Object Model using JavaScript. Users cannot return a value but can
evaluate as an expression in the block.
 xpath=xpathExpressionLocateanelementusinganXPath expression.
 link=textPattern Select the link element (within anchor tags)
which contains text matching the specified pattern.
 css=cssSelectorSyntax Selecttheelementusingcssselector.

13
6. WEBDRIVER
Selenium

WebDriver is a tool for automating testing web applications. It ispopularly known


as Selenium 2.0. WebDriver uses a different underlying framework, while
Selenium RCuses JavaScriptSelenium-Coreembeddedwithinthebrowserwhich has
got some limitations. WebDriver interacts directly with the browser without any
intermediary, unlike Selenium RC that depends on a server. It is used in the
following context:
 Multi-browser testing including improved functionality for browsers which
is not well-supported by Selenium RC (Selenium 1.0).
 Handlingmultipleframes,multiplebrowserwindows,popups,andalerts.
 Complexpagenavigation.
 Advancedusernavigationsuchasdrag-and-drop.
 AJAX-basedUIelements.

Architecture
WebDriverisbestexplainedwithasimplearchitecturediagramasshownbelow.

14
Selenium

SeleniumRCVsWebDriver

SeleniumRC SeleniumWebDriver

The architecture of Selenium RC is WebDriver's architecture is simpler


complicated,astheserverneedstobe up thanSeleniumRC,asitcontrolsthe
and running before starting a test. browser from the OS level.

Seleniumserveractsasamiddleman WebDriver interacts directly with


between the browser and Selenese thebrowserandusesthebrowser's
commands. engine to control it.

Selenium RC script execution is slower, WebDriverisfaster,asitinteracts


sinceitusesaJavascripttointeractwith RC. directly with the browser.

Selenium RC cannot support headless WebDrivercansupporttheheadless


execution,asitneedsarealbrowserto work execution.
with.

It’sasimpleandsmallAPI. ComplexandabitlargeAPIas
compared to RC.

Lessobject-orientedAPI. Purelyobject-orientedAPI.

CannottestmobileApplications. CantestiPhone/Android applications.

ScriptingusingWebDriver
LetusunderstandhowtoworkwithWebDriver.Fordemonstration,wewould
usehttp://www.calculator.net/.Wewillperforma"PercentCalculator"whichis

15
Selenium

ScriptingusingWebDriver
LetusunderstandhowtoworkwithWebDriver.Fordemonstration,wewould use
http://www.calculator.net/. We will perform a "Percent Calculator" which is
locatedunder"MathCalculator”
Step1:Launch"Eclipse"fromtheExtractedEclipsefolder.

Step2:SelecttheWorkspacebyclickingthe'Browse'button.

16
Selenium

Step3:Nowcreatea'NewProject'from'File'menu.

Step4:EntertheProjectNameandClick'Next'.

17
Selenium

Step 5 : Go to Libraries Tab and select all the JAR's that we have downloaded.
Add reference to all the JAR's of Selenium WebDriver Library folder and also
selenium-java-2.42.2.jar and selenium-java-2.42.2-srcs.jar.

18
Selenium

Step6:ThePackageis createdasshownbelow.

Step7: Now right-click on the package and select 'New'>>'Class' to create a


'Class'.

19
Selenium

Step8:Nownametheclassandmakeitthemainfunction.

20
Selenium

Step9:Theclassoutline isshownasbelow.

Step10 : Now it is time to code. The following script is easier to understand, as it


has comments embedded in it to explain the steps clearly.Please take a look at
the chapter "Locators" to understand how to capture object properties.

import java.util.concurrent.TimeUnit;
import org.openqa.selenium.*;
importorg.openqa.selenium.firefox.FirefoxDriver;

publicclasswebdriverdemo
{
publicstaticvoidmain(String[]args)
{
WebDriverdriver=newFirefoxDriver();

//PutsanImplicitwait,Willwaitfor10seconds
// before throwing exception
driver.manage().timeouts().implicitlyWait(10,
TimeUnit.SECONDS);

// Launch website
driver.navigate().to("http://www.calculator.net/");

// Maximize the browser


driver.manage().window().maximize(
);

// Click on Math Calculators


driver.findElement(By.xpath(".//*[@id='menu']/div[3]/a")).click
21
Selenium

//ClickonPercentCalculators
driver.findElement(By.xpath(".//*[@id='menu']/div[4]/div[3]/
a")).click();

//Entervalue10inthefirstnumberofthepercentCalculator
driver.findElement(By.id("cpar1")).sendKeys("10");

//Entervalue50inthesecondnumberofthepercentCalculator
driver.findElement(By.id("cpar2")).sendKeys("50");

// Click Calculate Button


driver.findElement(By.xpath(".//*[@id='content']/table/tbody
/tr/td[2]/input")).click();

//GettheResultTextbasedonitsxpath String
result =
driver.findElement(By.xpath(".//*[@id='content']/p[2]/span/
font/b")
)
.getText();

//Print a Log In message to the screen


System.out.println("TheResultis"+result);

//ClosetheBrowser.
driver.close();
}
Step11:Theoutputoftheabovescriptwouldbeprintedin Console.

22
Selenium

MostUsedCommands
The following table lists some of the most frequently used commands in
WebDriver along with their syntax.

Command Description

driver.get("URL") To navigate to an application.

element.sendKeys("inputtext") Enter some text into an input box.

element.clear() Clearthecontentsfromtheinput box.

select.deselectAll() DeselectallOPTIONsfromthefirst
SELECT on the page.

select.selectByVisibleText("sometext") SelecttheOPTIONwiththeinput
specified by the user.

driver.switchTo().window("windowName") Movethefocusfromonewindow to
another.

driver.switchTo().frame("frameName") Swingfromframetoframe.

driver.switchTo().alert() Helpsinhandlingalerts.

driver.navigate().to("URL") NavigatetotheURL.

23
Selenium

driver.navigate().forward() Tonavigateforward.

driver.navigate().back() Tonavigate back.

driver.close() Closesthecurrentbrowser
associated withthe driver.

driver.quit() Quitsthedriverandclosesallthe
associatedwindow ofthatdriver.

driver.refresh() Refreshesthecurrentpage.

24
7. LOCATORS
Selenium

Locating elements in Selenium WebDriver is performed with the help of


findElement() and findElements() methods provided by WebDriver and
WebElement class.

 findElement() returns a WebElement object based on a specified search


criteria or ends up throwing an exception if it does not find any element
matching the search criteria.

 findElements() returns a list of WebElements matching thesearch criteria.


If no elements are found, it returns an empty list.
The following table lists all the Java syntax for locating elements in Selenium
WebDriver.

Method Syntax Description

By ID driver.findElement(By.id(<elementID>)) Locates an
element
usingtheID
attribute

By driver.findElement(By.name(<elementname>)) Locatesan
name element
using the
Name
attribute

Byclass driver.findElement(By.className(<elementclass>)) Locatesan


name element
using the
Class
attribute

Bytag driver.findElement(By.tagName(<htmltagname>)) Locatesan


name element
using the

25
Selenium

HTML tag

Bylink driver.findElement(By.linkText(<linktext>)) Locatesa


text linkusing
link text

By driver.findElement(By.partialLinkText(<linktext>)) Locatesa
partial linkusingthe
linktext link's partial
text

ByCSS driver.findElement(By.cssSelector(<cssselector>)) Locates an


element
using the
CSSselector

By driver.findElement(By.xpath(<xpath>)) Locates an
XPath element
usingXPath
query

LocatorsUsage
Now let us understand the practical usage of each of the locator methods with
the help of http://www.calculator.net

ByID
Here an object is accessed with the help of IDs. In this case, it is the ID of the
text box. Values are entered into the text box using the sendkeys method with
the help of ID(cdensity).

26
Selenium

driver.findElement(By.id("cdensity")).sendKeys("10");

27
Selenium

ByName
Here anobject isaccessedwith the help of names. In this case, it is the nameof
the text box. Values are entered into the text box using the sendkeys method
with the help of ID(cdensity).

driver.findElement(By.name("cdensity")).sendKeys("10");

28
Selenium

ByClassName
Here an object is accessed with the help of Class Names. In this case, it is the
Class name of the WebElement. The Value can be accessed with the help of the
gettext method.

List<WebElement>byclass=driver.findElements(By.className("smalltex
t smtb"));

ByTagName
The DOM Tag Name of an element can be used to locate that particular element
in the WebDriver. It is very easy to handle tables with the help of this method.
Take a look at the following code.

WebElement table =
driver.findElement(By.id("calctable"));
List<WebElement>row=table.findElements(By.tagName("tr"))
; int rowcount = row.size();

29
Selenium

ByLink Text
Thismethodhelpstolocatealinkelementwithmatchingvisibletext.

driver.findElements(By.linkText("Volume")).click();

30
Selenium

ByPartialLinkText
Thismethodhelpslocatealinkelementwithpartialmatchingvisibletext.

driver.findElements(By.partialLinkText("Volume")).click();

ByCSS
The CSS is used as a method to identify the web object,however NOT all browsers
support CSS identification.

WebElement loginButton =
driver.findElement(By.cssSelector("input.login"));

ByXPath
XPath stands for XML path language. It is a query language for selecting nodes
fromanXMLdocument.XPathisbasedonthetreerepresentationofXML

31
Selenium

documentsandprovidestheabilitytonavigatearoundthetreebyselecting nodes using


a variety of criteria.

driver.findElement(By.xpath(".//*[@id='content']/table[1]/tbody/
tr/td/ta ble/tbody/tr[2]/td[1]/input")).sendkeys("100");

32
8.INTERACTIONS
Selenium

UserInteractions
Selenium WebDriver is the most frequently used tool among all the tools
availablein the Seleniumtoolset. Thereforeit is importanttounderstandhowto use
Selenium to interact with web apps. In this module,let us understand how to
interact with GUI objects using Selenium WebDriver.
We need to interact with the application using some basic actions or even some
advanced user action by developing user-defined functions for which there areno
predefined commands.

ListedbelowarethedifferentkindsofactionsagainstthoseGUIobjects:
 TextBoxInteraction
 RadioButtonSelection
 CheckBox Selection
 DropDownItemSelection
 Synchronization
 Drag&Drop
 KeyboardActions
 MouseActions
 MultiSelect
 FindAllLinks

TextBoxInteraction
In this section, we will understand how to interact with text boxes. We can put
values into a text box using the 'sendkeys' method. Similarly, we can also
retrieve text from a text box using the getattribute("value") command. Take a
look at the following example.

33
Selenium

import java.util.concurrent.TimeUnit;
import org.openqa.selenium.*;
importorg.openqa.selenium.firefox.FirefoxDriver;

publicclasswebdriverdemo
{
publicstaticvoidmain(String[]args)throwsInterruptedException
{
WebDriverdriver=newFirefoxDriver();

//PutsanImplicitwait,Willwaitfor10seconds
// before throwing exception
driver.manage().timeouts().implicitlyWait(10,
TimeUnit.SECONDS);

// Launch website
driver.navigate().to("http://www.calculator.net
34
Selenium

/percent-calculator.html");

// Maximize the browser


driver.manage().window().maximize
();

//Entervalue10inthefirstnumberofthepercentCalculator
driver.findElement(By.id("cpar1")).sendKeys("10");

Thread.sleep(5000);

//Getthetextboxfromtheapplication String
result =
driver.findElement(By.id("cpar1")).getAttribute("value");

// Print a Log In message to the screen


System.out.println("TheResultis"+result);

//ClosetheBrowser
driver.close();
}
}
Output
Theoutputoftheabovescriptisdisplayedas shown below.

35
Selenium

RadioButtonInteraction
In this section, we will understand how to interact with Radio Buttons. We can
select aradiobuttonoptionusingthe 'click' methodandunselectusingthe same
'click' method.

Let us understand how to interact with radio buttons using


http://www.calculator.net/mortgage-payoff-calculator.html. Wecanalso check if a
radio button is selected or enabled.

import java.util.concurrent.TimeUnit;
import org.openqa.selenium.*;
importorg.openqa.selenium.firefox.FirefoxDriver;

publicclasswebdriverdemo
{
publicstaticvoidmain(String[]args)throwsInterruptedException
{

36
Selenium

WebDriverdriver=newFirefoxDriver();

//PutsanImplicitwait,Willwaitfor10seconds
// before throwing exception
driver.manage().timeouts().implicitlyWait(10,
TimeUnit.SECONDS);

// Launch website
driver.navigate().to("http://www.calculator.net
/mortgage-payoff-
calculator.html");
driver.manage().window().maximize
();

// Click on Radio Button


driver.findElement(By.id("cpayoff1")).click();

System.out.println("TheOutputoftheIsSelected"+
driver.findElement(By.id("cpayoff1")).isSelected());

System.out.println("TheOutputoftheIsEnabled"+
driver.findElement(By.id("cpayoff1")).isEnabled());

System.out.println("TheOutputoftheIsDisplayed"+
driver.findElement(By.id("cpayoff1")).isDisplayed());

driver.close();

//ClosetheBrowser.
driver.close();
Output
Uponexecution,theradiobuttonisselectedandtheoutputofthecommands are
displayed in the console.
37
Selenium

CheckBoxInteraction
In thissection,wewillunderstandhowtointeractwithCheckBox.Wecanselect a check
box using the 'click' method and uncheck using the same 'click' method.
Let us understand how to interact with a check box using
http://www.calculator.net/mortgage-calculator.html. We can also check if a check
box is selected/enabled/visible.

import java.util.concurrent.TimeUnit;
import org.openqa.selenium.*;
importorg.openqa.selenium.firefox.FirefoxDriver;

38
Selenium

publicclasswebdriverdemo
{
publicstaticvoidmain(String[]args)throwsInterruptedException
{
WebDriverdriver=newFirefoxDriver();

//PutsanImplicitwait,Willwaitfor10seconds
// before throwing exception
driver.manage().timeouts().implicitlyWait(10,
TimeUnit.SECONDS);

// Launch website
driver.navigate().to("http://www.calculator.net
/mortgage-calculator.html");
driver.manage().window().maximize();

// Click on check box


driver.findElement(By.id("caddoptional")).click();

System.out.println("The Output of the IsSelected " +


driver.findElement(By.id("caddoptional")).isSelected());

System.out.println("The Output of the IsEnabled " +


driver.findElement(By.id("caddoptional")).isEnabled());

System.out.println("The Output of the IsDisplayed " +


driver.findElement(By.id("caddoptional")).isDisplayed());

driver.close();

}
}

39
Selenium

Output
Upon execution, the check box is unchecked after the click command (as it was
checked by default) and the output of the commands are displayed in the
console.

DropdownInteraction
In this section,we willunderstandhowtointeractwithDropdownBoxes.Wecan select
an option using 'selectByVisibleText' or 'selectByIndex' or
'selectByValue'methods.
Let us understand how to interact with a dropdown box using
http://www.calculator.net/interest-calculator.html. We can also check if a
dropdown box is selected/enabled/visible.

40
Selenium

importjava.util.concurrent.TimeUnit;

importorg.openqa.selenium.*;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.Select;

publicclasswebdriverdemo
{
publicstaticvoidmain(String[]args)throwsInterruptedException
{
WebDriverdriver=newFirefoxDriver();

//PutsanImplicitwait,Willwaitfor10seconds
// before throwing exception
driver.manage().timeouts().implicitlyWait(10,
TimeUnit.SECONDS);

// Launch website
driver.navigate().to("http://www.calculator.net
/interest-calculator.html");
driver.manage().window().maximize();

//SelectinganitemfromDropDownlistBox Select
dropdown =
newSelect(driver.findElement(By.id("ccompound")));

dropdown.selectByVisibleText("continuously");

//youcanalsousedropdown.selectByIndex(1)to
//selectsecondelementasindexstartswith0.
//Youcanalsousedropdown.selectByValue("annually");

System.out.println("TheOutputoftheIsSelected"+
41
Selenium

driver.findElement(By.id("ccompound")).isSelected());

System.out.println("The Output of the IsEnabled " +


driver.findElement(By.id("ccompound")).isEnabled());

System.out.println("The Output of the IsDisplayed " +


driver.findElement(By.id("ccompound")).isDisplayed());

driver.close();

}
}

Output
Upon execution, the dropdown is set with the specified value and the output of
the commands are displayed in the console.

Synchronization
To synchronize between script execution and application, we need to wait after
performing appropriate actions. Let us look at the ways to achieve the same.

Thread.Sleep
Thread.Sleepisastaticwaitanditisnotagoodwaytouseinscripts,asitis sleep without
condition.

Thread.Sleep(1000);//Willwaitfor1second.

Explicit Waits
An 'explicit wait' waits for a certain condition to occur before proceeding further.
It is mainly used when we want to click or act on an object onceit is visible.

42
Selenium

WebDriverdriver=newFirefoxDriver();
driver.get("Enter an URL"S);
WebElement DynamicElement = (new WebDriverWait(driver,
10)).until(ExpectedConditions.presenceOfElementLocated(By.id("Dynam
icEle ment")));

ImplicitWait
Implicit wait is used in cases where the WebDriver cannot locate an object
immediately because of its unavailability. The WebDriver will wait for a specified
implicit waittime anditwillnottryto find theelementagainduringthespecified time
period.
Once the specified time limit is crossed, the WebDriver will try to search the
element once again for one last time. Upon success, it proceeds with the
execution; upon failure, it throws an exception.
It isakindofglobalwaitwhichmeansthe waitisapplicableforthe entiredriver. Hence,
hardcoding this wait for longer time periods will hamper the execution time.

WebDriver driver = new FirefoxDriver();


driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.get("Enter an URL");
WebElementDynamicElement=driver.findElement(By.id("DynamicElement")
);

FluentWait
A FluentWait instance defines the maximum amount of time to wait for a
condition to take place, as well as the frequency with which to check the
existence of the object condition.
Let us saywewill 60 seconds for an element to beavailable on the page,butwe will
check its availability once in every 10 seconds.

Waitwait=newFluentWait(driver)
.withTimeout(60,SECONDS)
.pollingEvery(10,SECONDS)
.ignoring(NoSuchElementException.class);
WebElementdynamicelement=wait.until(ne
w Function<webdriver,webElement>()
{

43
Selenium

publicWebElementapply(WebDriverdriver)
{
returndriver.findElement(By.id("dynamicelement"));
}
}
);

Drag&Drop
Asatester,youmightbeinasituationtoperforma'Drag&drop'operation.We
willperform a dragand drop operation by picking up a treegrid that is available for
us on
http://www.keenthemes.com/preview/metronic/templates/admin/ui_tree.html.
In the example, we wouldlike to drag an element 'Disable Node' from 'initiallyopen'
folder to 'Parent Node' Folder.

import java.util.concurrent.TimeUnit;
import org.openqa.selenium.*;
importorg.openqa.selenium.firefox.FirefoxDriv
er; import
org.openqa.selenium.interactions.Actions;
import
org.openqa.selenium.interactions.Action; 44
Selenium

publicclasswebdriverdemo
{
publicstaticvoidmain(String[]args)throwsInterruptedException
{
WebDriverdriver=newFirefoxDriver();

//PutsanImplicitwait,Willwaitfor10seconds
// before throwing exception
driver.manage().timeouts().implicitlyWait(10,
TimeUnit.SECONDS);

// Launch website
driver.navigate().to("http://www.keenthemes.com/preview/
metronic/templates/admin/ui_tree.html");
driver.manage().window().maximize();

WebElement From =
driver.findElement(By.xpath(".//*[@id='j3_7']/a"));

WebElement To =
driver.findElement(By.xpath(".//*[@id='j3_1']/a"));

Actionsbuilder=newActions(driver);
ActiondragAndDrop=builder.clickAndHold(From)
.moveToElement(To)
.release(To)
.build();
dragAndDrop.perform();

driver.close();

}
}

45
Selenium

Output
Afterperformingthedrag-dropoperation,theoutputwouldbeasshownbelow.

KeyboardActions
Givenbelowarethemethodstoperformkeyboardactions:

 sendKeys - Sends keys to the keyboard representation in the browser.


Specialkeysthatarenottext,represented asKeysarerecognizedbothas part of
sequences of characters, or individually.
 pressKey - Press a key on the keyboard that is NOT text. The keys such
as function keys "F1", "F2", "Tab", "Control", etc. If keyToPress is a
sequence of characters, different driver implementations may choose to
throw an exception or to read only the first character in the sequence.

 releaseKey- Releasea keyonthekeyboardafter executing thekeypress


event. It usually holds good for non-text characters.
HerearethesyntaxtocallkeyboardfunctionsusingSeleniumWebDriver.

void sendKeys(java.lang.CharSequence
keysToSend) void
pressKey(java.lang.CharSequence keyToPress)
voidreleaseKey(java.lang.CharSequencekeyToRelea

MouseActions
Listed below are some of the key mouse actions that one would come across in
most of the applications:

46
Selenium

 Click -Performs a Click. We can also performaclick basedon


coordinates.
 contextClick - Performs a context click/right-click on an element or
based on the coordinates.
 doubleClick -Performsadouble-clickonthewebelementorbasedonthe
coordinates.Ifleft empty, itperformsdouble-click onthecurrentlocation.
 mouseDown -Performsamouse-downactiononanelementor basedon
coordinates.
 mouseMove - Performsa mouse-moveaction on an element or based on
coordinates.

 mouseUp -Releasesthemouseusuallyfollowedbymouse-downand acts


based on coordinates.
HerearethesyntaxtocallmouseactionsusingSeleniumWebDriver:

voidclick(WebElementonElement)
voidcontextClick(WebElementonElemen
t) void doubleClick(WebElement
onElement) void
mouseDown(WebElement onElement)
void mouseUp(WebElementonElement)
void mouseMove(WebElement
toElement)

MultiSelectAction
Sometimeswewouldbeinasituationtoselecttwoormoreitemsinalist boxor text area.
To understand the same, we would demonstrate multiple selection from the list
using
'http://demos.devexpress.com/aspxeditorsdemos/ListEditors/MultiSelect.aspx'.

Example
Letussay,wewanttoselect3itemsfromthislistasshownbelow:

47
Selenium

Letusseehowtocodefor thisfunctionality:

importjava.util.List;
importjava.util.concurrent.TimeUnit;

importorg.openqa.selenium.*;
import
org.openqa.selenium.firefox.FirefoxDriver;
import
org.openqa.selenium.interactions.Actions;
import
org.openqa.selenium.interactions.Action;

publicclasswebdriverdemo
{
publicstaticvoidmain(String[]args)throwsInterruptedException
{
WebDriverdriver=newFirefoxDriver();

driver.manage().timeouts().implicitlyWait(10,TimeUnit.SECONDS)
;

driver.navigate().to("http://demos.devexpress.com
/aspxeditorsdemos/ListEditors/MultiSelect.aspx");

//driver.manage().window().maximize();
48
Selenium

_DDD_L_LBI1T0")).click();

Thread.sleep(5000);

//PerformMultipleSelect
Actionsbuilder=newActions(driver);
WebElement select =
driver.findElement(By.id("ContentHolder_lbFeatures_LBT"));
List<WebElement>options=select.findElements(By.tagName("td"))
; System.out.println(options.size());
ActionmultipleSelect=builder.keyDown(Keys.CONTROL)
.click(options.get(2))
.click(options.get(4))
.click(options.get(6))
.build();
multipleSelect.perform();

driver.close();

}
}

Output
Upon executing the script, the items would be selected as displayed above and
the size of the list box would also be printed in the console.

49
Selenium

FindAllLinks
Testers mightbe in a situation tofind all the linksona website.We can easily do so
by finding all elements with the Tag Name "a", as we know that for any link
reference in HTML, we need to use "a" (anchor) tag.

Example

importorg.openqa.selenium.*;
import
org.openqa.selenium.firefox.FirefoxDriver;
public class getalllinks
{
publicstaticvoidmain(String[]args)
{
WebDriver driver = new FirefoxDriver();
driver.navigate().to("http://www.calculator.net");
java.util.List<WebElement> links =
driver.findElements(By.tagName("a"));
System.out.println("NumberofLinksinthePageis"+
links.size());
for(inti=1;i<=links.size();i=i+1)
{
System.out.println("NameofLink#"+i -+
links.get(i).getText());
}
}
}
Output
Theoutputofthe scriptwould bethrown totheconsole asshownbelow. Though there
are 65 links, only partial output is shown below.

50
Selenium

51
9. TEST DESIGN
Selenium

TECHNIQUES

Therearevarious components involved in designing thetests. Let us understand


some of the important components involved in designing a framework as well.
We will learn the following topics in this chapter:

 PageObjectModel
 ParameterizingusingExcel
 Log4jLogging
 ExceptionHandling
 MultiBrowser Testing
 Capture Screenshots
 CaptureVideos

Page Object Model


Selenium acts on webelements with the help of their properties such ID, name,
XPath, etc. UnlikeQTP which has an inbuilt object repository(OR), Selenium has
no inbuilt ORs.

Hence we need to build an OR which should also be maintainable and accessible


on demand. Page Object Model (POM) is a popular design pattern to create an
Object Repository in which each one of those webelements propertiesare created
using a class file.

Advantages
 POM is an implementation where test objects and functions are separated
from each other, thereby keeping the code clean.
 The objects are kept independent of test scripts. An object can be
accessed by one or more test scripts, hence POM helps us to create
objects once and use them multiple times.

 Since objects are created once, it is easy to access as well as update a


particular property of an object.

POMFlowDiagram
Objects are created for each one of the pages and methods are developed

52
exclusively to access to those objects. Let us use http://calculator.net for
understanding the same.

53
Selenium

There are various calculators associated with it and each one of those objects in
a particularpageis created in aseparateclass fileas staticmethodsandthey all are
accessed through the 'tests' class file in which a static method would be
accessing the objects.

Example
Let us understand it by implementing POM for percentcalculator test.

Step 1 : Create a simple class (page_objects_perc_calc.java) file within a


package and create methods for each one of those object identifiers as shown
below.

packagePageObject;

importorg.openqa.selenium.*;

publicclasspage_objects_perc_calc
{
Private static WebElement element=null;

//MathCalcLink
Public static WebElement lnk_math_calc(WebDriverdriver)
{
element =
driver.findElement(By.xpath(".//*[@id='menu']/div[3]/a")
); return element;
}

54
Selenium

//PercentageCalcLink
publicstaticWebElementlnk_percent_calc(WebDriverdriver)
{
element =
driver.findElement(By.xpath(".//*[@id='menu']/div[4]/div[3]/a"))
; return element;
}

//Number1Text Box
publicstaticWebElementtxt_num_1(WebDriverdriver)
{
element=driver.findElement(By.id("cpar1")
); return element;
}

//Number2Text Box
publicstaticWebElementtxt_num_2(WebDriverdriver)
{
element=driver.findElement(By.id("cpar2"));
return element;
}

//CalculateButton
publicstaticWebElementbtn_calc(WebDriverdriver)
{
element =
driver.findElement(By.xpath(".//*[@id='content']/table/tbody
/tr/td[2]/input"));
return element;
}

//Result
publicstaticWebElementweb_result(WebDriverdriver)

55
Selenium

{
element =
driver.findElement(By.xpath(".//*[@id='content']/p[2]/span/font/b")
); return element;
}
}

Step2 : Create a class with main and import the package and create methods for
each one of those object identifiers as shown below.

packagePageObject;

importjava.util.concurrent.TimeUnit;

importorg.openqa.selenium.WebDriver;
importorg.openqa.selenium.firefox.FirefoxDriver;

publicclasspercent_calculator
{
privatestaticWebDriverdriver=null;

publicstaticvoidmain(String[]args)
{
driver = new FirefoxDriver();
driver.manage().timeouts().implicitlyWait(10,
TimeUnit.SECONDS); driver.get("http://www.calculator.net");

// Use page Object library now


page_objects_perc_calc.lnk_math_calc(driver).click();
page_objects_perc_calc.lnk_percent_calc(driver).click();

page_objects_perc_calc.txt_num_1(driver).clear();
page_objects_perc_calc.txt_num_1(driver).sendKeys("10");
page_objects_perc_calc.txt_num_2(driver).clear();
page_objects_perc_calc.txt_num_2(driver).sendKeys("50");

56
Selenium

page_objects_perc_calc.btn_calc(driver).click();

String result =
page_objects_perc_calc.web_result(driver).getText()
;

if(result.equals("5"))
{
System.out.println("TheResultisPass");
}
else
{
System.out.println("TheResultisFail");
}

driver.close();
}
}
Output
The test is executed and the result is printed in the console. Given below is the
snapshot of the same.

DataDrivenusingExcel
While designing a test, parameterizing the tests is inevitable. We will make use
of Apache POI - Excel JAR's to achieve the same. It helps us read and write into
Excel.

DownloadJAR

57
Selenium

Step 1 : Navigate to the URL – http://poi.apache.org/download.html and


download the ZIP format.

Step2:ClickontheMirrorLinktodownload theJAR's.

Step3:Unzipthecontentstoa folder.

Step4:Unzippedcontentswouldbedisplayedasshownbelow.

58
Selenium

Step5:Nowcreateanewprojectandaddall the'ExternalJARs'under'poi- 3.10.FINAL'


folder.

Step6:Nowaddallthe'ExternalJARs'underthe'ooxml-lib'folder.

59
Selenium

Step7:Nowaddallthe 'ExternalJARs' under the'lib'folder.

60
Selenium

Step8:TheAddedJARisdisplayedasshownbelow.

Step9:ThePackageExplorerisdisplayedasshownbelow.Apartfromthat, add
'WebDriver' related JAR's

61
Selenium

Parameterization
Fordemonstration,wewillparameterizethepercentcalculatortest.
Step 1:Wewillparameterizeallthe inputsrequiredforpercentcalculatorusing Excel.
The designed Excel is shown below.

Step 2: Execute all the percent calculator functions for all the specified
parameters.

62
Selenium

Step 3 : Let us create generic methods to access the Excel file using the
imported JARs. These methods help us get a particular cell data or to set a
particular cell data, etc.

importjava.io.*;
importorg.apache.poi.xssf.usermodel.*;

publicclassexcelutils
{
private XSSFSheet ExcelWSheet;
privateXSSFWorkbookExcelWBook;

//Constructor to connect to the Excel with sheetname and


Path
publicexcelutils(StringPath,StringSheetName)throwsException
{
tr
y
{
//OpentheExcelfile
FileInputStreamExcelFile=newFileInputStream(Path);

// Access the required test data sheet


ExcelWBook = new XSSFWorkbook(ExcelFile);
ExcelWSheet=ExcelWBook.getSheet(SheetName);

catch(Exceptione)
{
throw(e);
}
}

//Thismethodistosettherowcountoftheexcel. public
int excel_get_rows() throws Exception
{
try 63
Selenium
{

64
Selenium

returnExcelWSheet.getPhysicalNumberOfRows();
}
catch(Exceptione)
{
throw(e);

}
}

//Thismethodtogetthedataandgetthevalueasstrings.
publicStringgetCellDataasstring(intRowNum,intColNum)throwsException
{
try
{
String CellData =
ExcelWSheet.getRow(RowNum).getCell(ColNum).getStringCellValu
e(); System.out.println("The value of CellData " +
CellData); return CellData;
}
catch(Exceptione)
{
return"ErrorsinGettingCellData";
}
}

//Thismethodtogetthedataandgetthevalueasnumber.
publicdoublegetCellDataasnumber(intRowNum,intColNum)throwsException
{
try
{
doubleCellData =
ExcelWSheet.getRow(RowNum).getCell(ColNum).getNumericCellValue(
);

65
Selenium

System.out.println("ThevalueofCellData"+CellData);
return CellData;
}

catch(Exceptione)
{
return000.00;
}
}
}

Step4 : Now add a main method which will access the Excel methods that we
have developed.

importjava.io.*;
importorg.apache.poi.xssf.usermodel.*;

publicclassexcelutils
{
private XSSFSheet ExcelWSheet;
privateXSSFWorkbookExcelWBook;

//Constructor to connect to the Excel with sheetname and


Path
publicexcelutils(StringPath,StringSheetName)throwsException
{
try
{
//OpentheExcelfile
FileInputStreamExcelFile=newFileInputStream(Path);
// Access the required test data sheet
ExcelWBook = new XSSFWorkbook(ExcelFile);
ExcelWSheet=ExcelWBook.getSheet(SheetName);

}
catch(Exceptione) 66
Selenium

{
throw(e);
}
}

//Thismethodistosettherowcountoftheexcel. public
int excel_get_rows() throws Exception
{
try
{
returnExcelWSheet.getPhysicalNumberOfRows();
}

catch(Exceptione)
{
throw(e);
}
}

//Thismethodtogetthedataandgetthevalueasstrings.
publicStringgetCellDataasstring(intRowNum,intColNum)throwsException
{
try
{
StringCellData =
ExcelWSheet.getRow(RowNum).getCell(ColNum).getStringCellValue(
);
//Cell=ExcelWSheet.getRow(RowNum).getCell(ColNum);
// String CellData = Cell.getStringCellValue();
System.out.println("ThevalueofCellData"+CellData);
return CellData;
}
catch(Exceptione)
{
67
Selenium

return"ErrorsinGettingCellData";
}
}

//Thismethodtogetthedataandgetthevalueasnumber.
publicdoublegetCellDataasnumber(intRowNum,intColNum)throwsException
{
try
{
doubleCellData =
ExcelWSheet.getRow(RowNum).getCell(ColNum).getNumericCellValue(
);
//Cell=ExcelWSheet.getRow(RowNum).getCell(ColNum);
// String CellData = Cell.getStringCellValue();
System.out.println("ThevalueofCellData"+CellData);
return CellData;
}
catch(Exceptione)
{
return000.00;
}
}
}

Output
Uponexecutingthescript,theoutputisdisplayedintheconsoleasshown below.

68
Selenium

Log4jLogging
Log4jisanauditloggingframeworkthatgivesinformationaboutwhathas happened
during execution. It offers the following advantages:
 Enablesustounderstandtheapplicationrun.
 Logoutputcanbesavedthatcanbeanalyzed later.
 Helpsindebugging,incaseoftestautomationfailures.
 Canalsobeusedforauditingpurposestolookattheapplication's health.

Components
1. InstanceofLoggerclass.
2. Loglevelmethodsusedforloggingthemessagesasoneofthefollowing:
 error
 warn
 info
 debug
 log

Example
Letususethesamepercentcalculatorforthis demo.

69
Selenium

Step 1 : Download log4j JAR file from


https://logging.apache.org/log4j/1.2/download.htmlanddownloadtheZipped format
of the JAR file.

Step2:Create'NewJavaProject'bynavigatingtotheFilemenu.

70
Selenium

Step3:Enterthenameoftheprojectas'log4j_demo'andclick'Next'.

Step4:ClickAddExternalJarandadd'Log4j-1.2.17.jar'.

71
Selenium

Step5:ClickAddExternalJarandaddSeleniumWebDriverLibraries.

Step6 :ClickAddExternalJarandaddSeleniumWebDriverJAR'slocatedinthe Libs


folder.

72
Selenium

Step7:AddaNewXMLfileusingwhichwecanspecifytheLog4jproperties.

Step8:EntertheLogfilenameas'Log4j.xml'.

73
Selenium

Step9:Thefinalfolderstructureisshownbelow.

Step10:NowaddthepropertiesofLog4jwhichwouldbepickedupduring execution.

<?xmlversion="1.0"encoding="UTF-8"?>
<!DOCTYPElog4j:configurationSYSTEM"log4j.dtd">
<log4j:configurationxmlns:log4j="http://jakarta.apache.org/
log4j/"debug="false">
<appender
name="fileAppender"class="org.apache.log4j.FileAppen
der">
<paramname="Threshold"value="INFO"/>
<paramname="File"value="percent_calculator.log"/>
<layoutclass="org.apache.log4j.PatternLayout">
<paramname="ConversionPattern"value="%d{yyyy-MM-dd
HH:mm:ss}[%c] (%t:%x) %m%n" />
</layout>
</appender>
<root>
<levelvalue="INFO"/>
<appender-refref="fileAppender"/>
</root>
</log4j:configuration>
Step11 : Now for demonstration purpose, we will incorporatelog4j in the same
test that we have been performing (percent calculator). Add a class file in the
'Main' function.

packagelog4j_demo;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
importorg.apache.log4j.xml.DOMConfigurator;

74
Selenium

import
java.util.concurrent.TimeUnit;
import org.openqa.selenium.*;
importorg.openqa.selenium.firefox.FirefoxDriver;

publicclasslog4j_demo
{

static final Logger logger =


LogManager.getLogger(log4j_demo.class.getName());

publicstaticvoidmain(String[]args)
{
DOMConfigurator.configure("log4j.xml");

logger.info("###########################");
logger.info("TESTHasStarted");

WebDriverdriver=newFirefoxDriver();

//PutsanImplicitwait,Willwaitfor10seconds
// before throwing exception
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

// Launch website
driver.navigate().to("http://www.calculator.net/");
logger.info("Open Calc Application");

// Maximize the browser


driver.manage().window().maximize();

// Click on Math Calculators


driver.findElement(By.xpath(".//*[@id='menu']/div[3]/a")).click();
75
Selenium

logger.info("ClickedMathCalculatorLink");

// Click on Percent Calculators


driver.findElement(By.xpath(".//*[@id='menu']/div[4]/div[3]/a"))
.click();logger.info("ClickedPercentCalculatorLink");

//Entervalue10inthefirstnumberofthepercentCalculator
driver.findElement(By.id("cpar1")).sendKeys("10");
logger.info("Entered Value into First Text Box");

//Entervalue50inthesecondnumberofthepercentCalculator
driver.findElement(By.id("cpar2")).sendKeys("50");
logger.info("Entered Value into Second Text Box");

// Click Calculate Button


driver.findElement(By.xpath(".//*[@id='content']/table
/tbody/tr/td[2]/input")).click();
logger.info("ClickCalculateButton");

// Get the Result Text based on its xpath


String result =
driver.findElement(By.xpath(".//*[@id='conte
nt']
/p[2]/span/font/b")).getText();
logger.info("Get Text Value");

// Print a Log In message to the screen


logger.info("TheResultis"+result);

if(result.equals("5"))
{
logger.info("TheResultisPass");

76
Selenium

}
else
{
logger.error("TESTFAILED.NEEDSINVESTIGATION");
}

logger.info("###########################");

//ClosetheBrowser.
driver.close();
}
}

Execution
Upon execution, the log file is created on the root folder as shown below. You
CANNOT locate the file in Eclipse. You should open 'Windows Explorer' to show
the same.

Thecontentsofthefileisshownbelow.

77
Selenium

ExceptionHandling
When we are developing tests, we should ensure that the scripts can continue
theirexecutioneven ifthetestfails.Anunexpectedexceptionwouldbethrownif the
worst case scenarios are not handled properly.

If an exception occurs due to an element not found or if the expected result


doesn't match with actuals, we should catch that exception and end the test in a
logical way rather than terminating the script abruptly.

Syntax
The actual code should be placed in the try block and the action after exception
should be placed in the catch block. Note that the 'finally' block executes
regardless of whether the script had thrown an exception or NOT.

try
{
//PerformAction
}
catch(ExceptionType1exp1)
{
//Catchblock1
}
catch(ExceptionType2exp2)
{
//Catchblock2
}
catch(ExceptionType3exp3)
{
//Catchblock3
}
finally
{
//Thefinallyblockalwaysexecutes.
}

78
Selenium

Example
If an element is not found (due to some reason), we should step out of the
function smoothly. So we always need to havea try-catch block if we want to exit
smoothly from a function.

publicstaticWebElementlnk_percent_calc(WebDriverdriver)throwsException
{
try
{
element =
driver.findElement(By.xpath(".//*[@id='menu']/div[4]/div[3]/a")
); return element;
}
catch(Exceptione1)
{
//AddamessagetoyourLogFiletocapturetheerror Logger.error("Link
is not found.");

// Take a screenshot which will be helpful for


analysis. File screenshot =
((TakesScreenshot)driver).getScreenshotAs(OutputType.FI
LE);

FileUtils.copyFile(screenshot, new File("D:\\framework\\


screenshots.jpg"));

throw(e1);
}
}

MultiBrowserTesting
Users can execute scripts in multiple browsers simultaneously. For
demonstration, we will use the same scenario that we had taken for Selenium
Grid. In the Selenium Grid example, we had executed the scripts remotely; here
we will execute the scripts locally.

79
Selenium

First of all, ensure that you haveappropriate drivers downloaded. Please referthe
chapter "Selenium Grid" for downloading IE and Chrome drivers.

Example
For demonstration, we will perform percent calculator in all the browsers
simultaneously.

packageTestNG;

import org.openqa.selenium.chrome.ChromeDriver;
import
org.openqa.selenium.firefox.FirefoxDriver;
import
org.openqa.selenium.ie.InternetExplorerDriver;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.*;
importorg.testng.annotations.*;

publicclassTestNGClass
{
Private WebDriver driver;
Private String URL="http://www.calculator.net";

@Parameters("browser")
@BeforeTest
publicvoidlaunchapp(Stringbrowser)
{

if(browser.equalsIgnoreCase("firefox"))
{
System.out.println("ExecutingonFireFox")
; driver = new FirefoxDriver();
driver.get(URL);
driver.manage().timeouts().implicitlyWait(10,
TimeUnit.SECONDS); driver.manage().window().maximize();
}
80
Selenium

{
System.out.println(" Executing on CHROME");
System.out.println("Executing on IE");
System.setProperty("webdriver.chrome.driver", "D:\\
chromedriver.exe");
driver=newChromeDriver();
driver.get(URL);
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.manage().window().maximize();
}
elseif(browser.equalsIgnoreCase("ie"))
{
System.out.println("Executing on IE");
System.setProperty("webdriver.ie.driver", "D:\\
IEDriverServer.exe");
driver=newInternetExplorerDriver();
driver.get(URL);
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.manage().window().maximize();
}
else
{
thrownewIllegalArgumentException("TheBrowserTypeisUndefined");
}
}

@Test
publicvoidcalculatepercent()
{
// Click on Math Calculators
driver.findElement(By.xpath(".//*[@id='menu']/div[3]/a")).click()
;

//ClickonPercentCalculators
driver.findElement(By.xpath(".//*[@id='menu']/div[4]/div[3]/ 81
Selenium
a")).click();

82
Selenium

//Entervalue10inthefirstnumberofthepercentCalculator
driver.findElement(By.id("cpar1")).sendKeys("10");

//Entervalue50inthesecondnumberofthepercentCalculator
driver.findElement(By.id("cpar2")).sendKeys("50");

// Click Calculate Button


driver.findElement(By.xpath(".//*[@id='content']/table/tbody/
tr/td[2]/input")).click();

//GettheResultTextbasedonitsxpath String
result =
driver.findElement(By.xpath(".//*[@id='content']/p[2]/span
/font/b")).getText();

// Print a Log In message to the screen


System.out.println("TheResultis"+result);

if(result.equals("5"))
{
System.out.println("TheResultisPass");
}
else
{
System.out.println("TheResultisFail");
}
}

@AfterTest
publicvoidcloseBrowser()
{
driver.close();

83
Selenium

}
}

Create an XML which will help us in parameterizing the browser name and don't
forget to mention parallel="tests" in order to execute in all the browsers
simultaneously.

84
Selenium

Executethescriptbyperformingright-clickontheXMLfileandselect'RunAs'
>>'TestNG'Suiteasshownbelow.

Output
All the browsers would be launched simultaneously and the result would be
printed in the console.
Note : To execute on IE successfully, ensure that the check box 'Enable
Protected Mode' under the security tab of 'IE Option' is either checked or
unchecked across all zones.

85
Selenium

TestNGresultscanbeviewedinHTMLformatfordetailed analysis.

86
Selenium

CaptureScreenshots
This functionality helps to grab screenshots at runtime when required, in
particularly when a failure happens. With the help of screenshots and log
messages, we will be able to analyze the results better.

Screenshots are configured differently for local executions and Selenium Grid
(remote) executions. Let us take a look at each one them with an example.

LocalhostExecution
In the following example, we will take a screenshot after calculating the
percentage. Ensure that you give a valid path to save the screenshot.

importjava.io.File;
importjava.io.IOExceptio
n;
importjava.util.concurrent.TimeUnit;

importorg.apache.commons.io.FileUtils;
import org.openqa.selenium.*;
importorg.openqa.selenium.firefox.FirefoxDriver;

publicclasswebdriverdemo
{
publicstaticvoidmain(String[]args)throwsIOException
{
WebDriverdriver=newFirefoxDriver();

//PutsanImplicitwait,Willwaitfor10seconds
// before throwing exception
driver.manage().timeouts().implicitlyWait(10,
TimeUnit.SECONDS);

// Launch website
driver.navigate().to("http://www.calculator.net/");

// Maximize the browser


driver.manage().window().maximize(
87
Selenium

// Click on Math Calculators


driver.findElement(By.xpath(".//*[@id='menu']/div[3]/a")).click()
;

//ClickonPercentCalculators
driver.findElement(By.xpath(".//*[@id='menu']/div[4]/div[3]/
a")).click();

//Entervalue10inthefirstnumberofthepercentCalculator
driver.findElement(By.id("cpar1")).sendKeys("10");

//Entervalue50inthesecondnumberofthepercentCalculator
driver.findElement(By.id("cpar2")).sendKeys("50");

// Click Calculate Button


driver.findElement(By.xpath(".//*[@id='content']/table
/tbody/tr/td[2]/input")).click();

//GettheResultTextbasedonitsxpath String
result =
driver.findElement(By.xpath(".//*[@id='content']/p[2]
/span/font/b")).getText();

File screenshot =
((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);

FileUtils.copyFile(screenshot, new File("D:\\screenshots\\


screenshots1.jpg"));

// Print a Log In message to the screen


System.out.println("TheResultis"+result);

//ClosetheBrowser.
driver.close();

88
Selenium
}

89
Selenium

Output
Upon executing the script, the screenshot is saved in the 'D:\screenshots' folder
with the name 'screenshots1.jpg' as shown below.

SeleniumGrid–ScreenshotCapture
WhileworkingwithSeleniumGrids,weshouldensurethatwearetakingthe screenshots
correctly from the remote system. We will use augmented driver.

Example
WewillexecutethescriptonaFirefoxnodeattachedtoahub.Formoreon configuring hub
and nodes, please refer the Selenium Grids chapter.

packageTestNG;

importorg.openqa.selenium.remote.Augmenter;
importorg.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.TakesScreenshot;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.*;
import
org.testng.annotations.AfterTest;
import
org.testng.annotations.BeforeTest;
import
org.testng.annotations.Parameters;
import org.testng.annotations.Test;
import java.io.File;
importjava.net.URL;
90
Selenium

import org.openqa.selenium.remote.RemoteWebDriver;
import java.io.IOException;

publicclassTestNGClass
{
publicWebDriverdriver;
publicStringURL,Node;
protectedThreadLocal<RemoteWebDriver>threadDriver=null;

@Parameters("browser")
@BeforeTest
publicvoidlaunchapp(Stringbrowser)throwsMalformedURLException
{
StringURL="http://www.calculator.net";
if
(browser.equalsIgnoreCase("firefox"))
{
System.out.println(" Executing on FireFox");
StringNode="http://10.112.66.52:5555/wd/hub"
;
DesiredCapabilitiescap=DesiredCapabilities.firefox();
cap.setBrowserName("firefox");

driver=newRemoteWebDriver(newURL(Node),cap);
//PutsanImplicitwait,Willwaitfor10seconds
// before throwing exception
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

// Launch website
driver.navigate().to(URL);
driver.manage().window().maximize();
}
else
{
91
Selenium
thrownewIllegalArgumentException("TheBrowserTypeis

92
Selenium

Undefined");
}
}

@Test
publicvoidcalculatepercent()throwsIOException
{
// Click on Math Calculators
driver.findElement(By.xpath(".//*[@id='menu']/div[3]/a")).click()
;

//ClickonPercentCalculators
driver.findElement(By.xpath(".//*[@id='menu']/div[4]/div[3]/
a")).click();

// Make use of augmented Driver to capture Screenshots.


WebDriver augmentedDriver = new
Augmenter().augment(driver); File screenshot =
((TakesScreenshot)augmentedDriver).getScreenshotAs(OutputType.
FILE);

FileUtils.copyFile(screenshot, new File("D:\\screenshots\\


remotescreenshot1.jpg"));

//Screenshotwouldbesavedonthesystemwherethescriptis
//executedandNOTonremotemachine.

//Entervalue10inthefirstnumberofthepercentCalculator
driver.findElement(By.id("cpar1")).sendKeys("10");

//Entervalue50inthesecondnumberofthepercentCalculator
driver.findElement(By.id("cpar2")).sendKeys("50");

// Click Calculate Button


93
Selenium
driver.findElement(By.xpath(".//*[@id='content']/table/tbody
/tr/td[2]/input")).click();

94
Selenium

//GettheResultTextbasedonitsxpath String
result =
driver.findElement(By.xpath(".//*[@id='content']/p[2]
/span/font/b")).getText();

// Print a Log In message to the screen


System.out.println("TheResultis"+result);

if(result.equals("5"))
{
System.out.println("TheResultisPass");
}
else
{
System.out.println("TheResultisFail");
}
}

@AfterTest
publicvoidcloseBrowser()
{
driver.quit();
}
}

Output
Upon executing the script, the screenshot is captured and saved in the specified
location as shown below.

95
Selenium

96
10.
Selenium

TestNG

WhatisTestNG?
TestNG is a powerfultesting framework, anenhanced version of JUnit which was in
use for a long time before TestNG came into existence. NG stands for 'Next
Generation'.
TestNGframeworkprovidesthefollowingfeatures:
 Annotationshelpusorganizethetestseasily.
 Flexibletestconfiguration.
 Testcasescanbegroupedmoreeasily.
 ParallelizationoftestscanbeachievedusingTestNG.
 Supportfordata-driventesting.
 Inbuiltreporting

InstallingTestNGforEclipse
Step1:LaunchEclipseandselect'InstallNew Software'.

97
Selenium

Step2:EntertheURLas'http://beust.com/eclipse'andclick'Add'.

Step 3: The dialogbox 'AddRepository' opens.Enter the nameas 'TestNG'and click


'OK'

98
Selenium

Step4:Click'SelectAll'and'TestNG'would beselectedasshowninthefigure.

Step5:Click'Next'tocontinue.

99
Selenium

Step6:Reviewtheitemsthatareselectedandclick'Next'.

Step7:"AccepttheLicenseAgreement"andclick'Finish'.

100
Selenium

Step8:TestNGstartsinstallingandtheprogresswould beshownfollows.

Step 9 : Security Warning pops up as the validity of the software cannot be


established. Click 'Ok'.

Step 10:TheInstaller promptstorestartEclipseforthe changestotakeeffect. Click


'Yes'.

AnnotationsinTestNG
Annotations were formally added to the Java language in JDK 5 and TestNG made
the choice to use annotations to annotate test classes. Following are some of the
benefits of using annotations. More about TestNG can be found here.

 TestNG identifies the methods it is interested in by lookingup annotations.


Hence, method names are not restricted to any pattern or format.

101
Selenium

 Wecanpassadditionalparameterstoannotations.
 Annotationsarestronglytyped,sothecompilerwillflaganymistakes right
away.
 Testclassesnolongerneedtoextendanything(suchasTestCase,for JUnit 3).

Annotation Description

@BeforeSuite Theannotatedmethodwillberunonly oncebeforeallthe tests in


this suite have run.

@AfterSuite Theannotatedmethodwillberunonly onceafterallthe tests in


this suite have run.

@BeforeClass Theannotatedmethodwillberunonly oncebeforethefirst test


method in the current class is invoked.

@AfterClass Theannotatedmethodwillberunonlyonceafterallthetest
methods in the current class have run.

@BeforeTest Theannotatedmethodwillberunbeforeanytestmethod
belonging to the classes inside the <test> tag is run.

@AfterTest Theannotatedmethodwillberunafterallthetestmethods
belonging to the classes inside the <test> tag have run.

@BeforeGroups The list of groups that this configuration method will run
before.Thismethodisguaranteedtorunshortlybeforethe first
test method that belongs to any of these groups is invoked.

@AfterGroups Thelistofgroupsthatthisconfigurationmethodwillrun

102
Selenium

after.Thismethodisguaranteedtorunshortlyafterthelast
testmethod that belongs to anyofthese groups is invoked.

@BeforeMethod Theannotatedmethodwillberunbeforeeachtestmethod.

@AfterMethod Theannotatedmethodwillberunaftereachtestmethod.

@DataProvider Marks a method as supplying data for a test method. The


annotated method must return an Object[ ][ ] where each
Object[ ] can be assigned the parameter list of the test
method.The@Testmethodthatwantstoreceivedatafrom this
DataProvider needs to use a dataProvider name equals to
the name of this annotation.

@Factory Marksamethodasafactorythatreturnsobjectsthatwillbe used by


TestNG as Test classes. The method must return Object[ ].

@Listeners Defineslistenersonatestclass.

@Parameters Describeshowtopassparameterstoa@Testmethod.

@Test Marksaclassoramethodaspartofthetest.

103
Selenium

TestNG-EclipseSetup
Step1:LaunchEclipseand createa'NewJavaProject'asshownbelow.

Step2:Entertheprojectnameandclick'Next'.

104
Selenium

Step3 :Navigateto"Libraries"TabandaddtheSeleniumRemoteControl Server JAR file


by clicking on "Add External JAR's" as shown below.

Step4:TheaddedJARfileisshownhere.Click'AddLibrary'.

105
Selenium

Step5 : The 'AddLibrary' dialogopens. Select 'TestNG' and click 'Next'inthe 'Add
Library' dialog box.

106
Selenium

Step6:Theadded'TestNG'Libraryisaddedanditisdisplayedasshown below.

Step7 :Uponcreatingtheproject,thestructureoftheprojectwouldbeas shown below.

107
Selenium

Step8:Right-clickon'src'folderandselectNew>>Other.

108
Selenium

Step9:Select'TestNG'andclick'Next'.

Step10:Selectthe'SourceFolder'nameandclick'Ok'.

109
Selenium

Step11:Selectthe'Packagename',the'classname',andclick'Finish'.

Step12:ThePackageexplorerandthecreatedclasswouldbedisplayed.

110
Selenium

FirstTestinTestNG
Now let us start scripting using TestNG. Let us script for the same example that
we used for understanding the WebDriver. We will use the demo application,
www.calculator.net, and perform percent calculator.

In the following test, you will notice that there is NO main method, as testNG will drive the
program execution flow. After initializing the driver, it will execute the '@BeforeTest' method
followedby'@Test'andthen'@AfterTest'.Pleasenotethat therecanbeany number of '@Test'
annotation in a class but '@BeforeTest' and '@AfterTest' can appear only once.

packageTestNG;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.*;
importorg.openqa.selenium.firefox.FirefoxDriv
er; import org.testng.annotations.AfterTest;
import
org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;

publicclassTestNGClass
{
WebDriverdriver=newFirefoxDriver();

@BeforeTest
publicvoidlaunchapp()
{
//PutsanImplicitwait,Willwaitfor10seconds
// before throwing exception
driver.manage().timeouts().implicitlyWait(10,
TimeUnit.SECONDS);
//Launch website
driver.navigate().to("http://www.calculator.net");
driver.manage().window().maximize();
}

@Test
111
Selenium

{
// Click on Math Calculators
driver.findElement(By.xpath(".//*[@id='menu']/div[3]/a")).click()
;

//ClickonPercentCalculators
driver.findElement(By.xpath(".//*[@id='menu']/div[4]/div[3]/
a")).click();

//Entervalue10inthefirstnumberofthepercentCalculator
driver.findElement(By.id("cpar1")).sendKeys("10");

//Entervalue50inthesecondnumberofthepercentCalculator

driver.findElement(By.id("cpar2")).sendKeys("50");

// Click Calculate Button


driver.findElement(By.xpath(".//*[@id='content']/table
/tbody/tr/td[2]/input")).click();

//GettheResultTextbasedonitsxpath String
result =
driver.findElement(By.xpath(".//*[@id='content']/p[2]
/span/font/b")).getText();

// Print a Log In message to the screen


System.out.println("TheResultis"+result);

if(result.equals("5"))
{
{

}
els
e
112
Selenium
System.o
ut.print
ln("TheR
esultisP
ass");

System.o
ut.print
ln("TheR
esultisF
ail");

113
Selenium

}
}

@AfterTest
publicvoidterminatetest()
{
driver.close();
}
}

Execution
Toexecute,right-clickonthecreatedXMLandselect"RunAs">>"TestNG Suite"

114
ResultAnalysis
Selenium
Theoutputisthrowntotheconsoleanditwouldappearasshownbelow.The console
output also has an execution summary.

The result of TestNG can also be seenin adifferent tab. Click on 'HTML Report View'
button as shown below.

TheHTMLresultwouldbedisplayedasshownbelow.

115

You might also like