Selenium - Webdriver Notes
Selenium - Webdriver Notes
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.
Canexecutescriptsonvarious WorksonlywithWindows.
operating systems.
Supportsmobiledevices. Supportsmobiledeviceswiththehelpof
third-party tools.
1
i
Selenium
DisadvantagesofSelenium
LetusnowdiscussthepitfallsofSeleniumoverQTP.
Selenium QTP
2
SELENESECOMMANDS
SSeellee
nniiuum
Command/Syntax Description
3
Selenium
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
4
Selenium
open(url) OpensaURLinthespecified
browser and it accepts both
relative and absolute URLs.
pause(waitTime) Waitsforthespecified
amount of time (in
milliseconds)
5
Selenium
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.
storeAllLinks(variableName) ReturnstheIDsofalllinks on
the page.
7
Selenium
storeBodyText(variableName) Getstheentiretextofthe
page.
storeConfirmation(variableName) Retrievesthemessageof
aJavaScriptconfirmation
dialog generated during
the previous action.
storeElementIndex(locator,variableName) Gettherelativeindexof
anelementtoitsparent
(starting from 0).
8
Selenium
storeValue(locator,variableName) Getsthe(whitespace-
trimmed) value of an
inputfield.
9
Selenium
storeElementPresent(locator,variableName) Verifiesthatthespecified
elementissomewhereon
the page.
storeTextPresent(pattern,variableName) Verifiesthatthespecified
text pattern appears
somewhere on the
rendered page shown to
the user.
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
10
Selenium
verifySelected(selectLocator,optionLocator) Verifiesthattheselected
option of a drop-down
satisfies the
optionSpecifier.
verifyAllLinks(pattern) Verifiesalllinks;usedwith
theaccessorstoreAllLinks.
11
Selenium
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.
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
13
6. WEBDRIVER
Selenium
Architecture
WebDriverisbestexplainedwithasimplearchitecturediagramasshownbelow.
14
Selenium
SeleniumRCVsWebDriver
SeleniumRC SeleniumWebDriver
It’sasimpleandsmallAPI. ComplexandabitlargeAPIas
compared to RC.
Lessobject-orientedAPI. Purelyobject-orientedAPI.
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.
19
Selenium
Step8:Nownametheclassandmakeitthemainfunction.
20
Selenium
Step9:Theclassoutline isshownasbelow.
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/");
//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");
//GettheResultTextbasedonitsxpath String
result =
driver.findElement(By.xpath(".//*[@id='content']/p[2]/span/
font/b")
)
.getText();
//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
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.close() Closesthecurrentbrowser
associated withthe driver.
driver.quit() Quitsthedriverandclosesallthe
associatedwindow ofthatdriver.
driver.refresh() Refreshesthecurrentpage.
24
7. LOCATORS
Selenium
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
25
Selenium
HTML tag
By driver.findElement(By.partialLinkText(<linktext>)) Locatesa
partial linkusingthe
linktext link's partial
text
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
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");
//Entervalue10inthefirstnumberofthepercentCalculator
driver.findElement(By.id("cpar1")).sendKeys("10");
Thread.sleep(5000);
//Getthetextboxfromtheapplication String
result =
driver.findElement(By.id("cpar1")).getAttribute("value");
//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.
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
();
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();
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());
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.
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:
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
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
PageObjectModel
ParameterizingusingExcel
Log4jLogging
ExceptionHandling
MultiBrowser Testing
Capture Screenshots
CaptureVideos
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.
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.
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");
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
Step2:ClickontheMirrorLinktodownload theJAR's.
Step3:Unzipthecontentstoa folder.
Step4:Unzippedcontentswouldbedisplayedasshownbelow.
58
Selenium
Step6:Nowaddallthe'ExternalJARs'underthe'ooxml-lib'folder.
59
Selenium
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;
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;
}
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
Step2:Create'NewJavaProject'bynavigatingtotheFilemenu.
70
Selenium
Step3:Enterthenameoftheprojectas'log4j_demo'andclick'Next'.
Step4:ClickAddExternalJarandadd'Log4j-1.2.17.jar'.
71
Selenium
Step5:ClickAddExternalJarandaddSeleniumWebDriverLibraries.
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
{
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");
logger.info("ClickedMathCalculatorLink");
//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");
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.
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.");
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");
//GettheResultTextbasedonitsxpath String
result =
driver.findElement(By.xpath(".//*[@id='content']/p[2]/span
/font/b")).getText();
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/");
//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");
//GettheResultTextbasedonitsxpath String
result =
driver.findElement(By.xpath(".//*[@id='content']/p[2]
/span/font/b")).getText();
File screenshot =
((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
//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();
//Screenshotwouldbesavedonthesystemwherethescriptis
//executedandNOTonremotemachine.
//Entervalue10inthefirstnumberofthepercentCalculator
driver.findElement(By.id("cpar1")).sendKeys("10");
//Entervalue50inthesecondnumberofthepercentCalculator
driver.findElement(By.id("cpar2")).sendKeys("50");
94
Selenium
//GettheResultTextbasedonitsxpath String
result =
driver.findElement(By.xpath(".//*[@id='content']/p[2]
/span/font/b")).getText();
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'.
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.
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.
101
Selenium
Wecanpassadditionalparameterstoannotations.
Annotationsarestronglytyped,sothecompilerwillflaganymistakes right
away.
Testclassesnolongerneedtoextendanything(suchasTestCase,for JUnit 3).
Annotation Description
@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.
@Listeners Defineslistenersonatestclass.
@Parameters Describeshowtopassparameterstoa@Testmethod.
@Test Marksaclassoramethodaspartofthetest.
103
Selenium
TestNG-EclipseSetup
Step1:LaunchEclipseand createa'NewJavaProject'asshownbelow.
Step2:Entertheprojectnameandclick'Next'.
104
Selenium
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.
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");
//GettheResultTextbasedonitsxpath String
result =
driver.findElement(By.xpath(".//*[@id='content']/p[2]
/span/font/b")).getText();
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