Selenium Tutorial
Selenium Tutorial
Table of Contents
1.
OVERVIEW···························································································
································1
Introduction
···············································································································
·····························1
Advantages of Selenium··························································································································2
2. SELENIUM – IDE
··········································································································
········4
Selenium – IDE
···············································································································
·························4
3.ENVIRONMENT
ii
SETUP·······································································································2
8
4. SELENIUM RC
··········································································································
··········44
What is Selenium
RC?·········································································································
···················44
Selenium RC Architecture······················································································································44
RC – Scripting ········································································································································45
5. SELENESE
COMMANDS··························································································
············54
Actions
···············································································································
···································54
Accessors ··············································································································································58
Assertions ·············································································································································61
6.
WEBDRIVER·························································································
······························65
Architecture
···············································································································
···························65
Selenium RC Vs WebDriver····················································································································66
7.LOCATORS
················································································································
········
Selenium
Parameterization ································································································································112
Log4j Logging·······································································································································118
10.
TESTNG································································································
····························148
What is
TestNG?····································································································
······························148
11. SELENIUM
GRID··········································································································
·····166
iv
Architecture ········································································································································167
v
1.
Selenium
OVERVIEW
Introduction
Selenium is an open-source and a portable automated software testing tool for
testing web applications. It has capabilities to operate across different browsers
and operating systems. Selenium is not just a single tool but a set of tools that
helps testers to automate web-based applications more efficiently.
Let us now understand each one of the tools available in the Selenium suite and
their usage.
Tool Description
1
Selenium
Advantages of Selenium
QTP and Selenium are the most used tools in the market for software
automation testing. Hence it makes sense to compare the pros of Selenium over
QTP.
Selenium QTP
Can be extended for various Limited add-ons and needs add-ons for
technologies that expose DOM. each one of the technologies.
Executes tests within the Needs Focus during script execution, as the
browser, so focus is NOT tool acts on the browser (mimics user
required while script execution is actions).
in progress.
2
Selenium
Disadvantages of Selenium
Cannot access controls within the Can access controls within the browser
browser. such as favorites bar, backward, and
forward buttons.
No default test report generation. Default test result generation within the
tool.
3
2.
Selenium
SELENIUM –
IDE
Selenium – IDE
The Selenium-IDE (Integrated Development Environment) is an easy-to-use
Firefox plug-in to develop Selenium test cases. It provides a Graphical User
Interface for recording user actions using Firefox which is used to learn and use
Selenium, but it can only be used with Firefox browser as other browsers are not
supported.
The following table lists the sections that we are going to cover in this chapter. .
Title Description
Download Selenium This section deals with how to download and configure
IDE Selenium IDE.
Creating Selenium This section deals with how to create IDE tests using
IDE Tests recording feature.
Selenium IDE Script This section deals with debugging the Selenium IDE
Debugging script.
4
Selenium
Selenium Pattern This section deals with how to work with regular
Matching expressions using IDE.
Selenium User The Java script that allows users to customize or add
Extensions new functionality.
Different Browser This section deals with how to execute Selenium IDE
Execution scripts on different browsers.
Under the Selenium IDE section, click on the link that shows the current version
number as shown below.
Step 2 : Firefox add-ons notifier pops up with allow and disallow options. User
has to allow the installation.
5
Selenium
Step 3 : The add-ons installer warns the user about untrusted add-ons. Click
'Install Now'.
Step 4 : The Selenium IDE can now be accessed by navigating to Tools >>
Selenium IDE.
Step 5 : The Selenium IDE can also be accessed directly from the quick access
menu bar as shown below.
6
Selenium
The following image shows the features of Selenium IDE with the help of a
simple tooltip.
7
Selenium
The following steps are involved in creating Selenium tests using IDE:
Step 2 : Open Selenium IDE from the Tools menu and press the record button
that is on the top-right corner.
8
Selenium
Step 3 : Navigate to "Math Calculator" >> "Percent Calculator >> enter "10" as
number1 and 50 as number2 and click "calculate".
Step 4 : User can then insert a checkpoint by right clicking on the webelement
and select "Show all available commands" >> select "assert text css=b 5"
9
Selenium
Step 5 : The recorded script is generated and the script is displayed as shown
below.
The test can also be saved with an extension htm, shtml, and xhtml.
10
Selenium
Step 1 : Create a test suite by navigating to "File" >> "New Test Suite" as
shown below.
Step 2 : The tests can be recorded one by one by choosing the option "New Test
Case" from the "File" Menu.
Step 3 : The individual tests are saved with a name along with saving a "Test
Suite".
11
Selenium
Step 1 : The Run status can be seen in the status pane that displays the
number of tests passed and failed.
Step 2 : Once a step is executed, the user can see the result in the "Log" Pane.
Step 3 : After executing each step, the background of the test step turns
"Green" if passed and "Red" if failed as shown below.
12
Selenium
Script Debugging
Debugging is the process of finding and fixing errors in the test script. It is a
common step in any script development. To make the process more robust, we
can use a plugin "Power Debugger" for Selenium IDE.
Step 2 : Now launch 'Selenium IDE' and you will notice a new icon, "Pause on
Fail" on the recording toolbar as shown below. Click it to turn it ON. Upon
clicking again, it would be turned "OFF".
14
Selenium
Step 3 : Users can turn "pause on fail" on or off any time even when the test is
running.
Step 4 : Once the test case pauses due to a failed step, you can use the
resume/step buttons to continue the test execution. The execution will NOT be
paused if the failure is on the last command of any test case.
15
Selenium
Step 6 : Upon inserting the breakpoint, the particular step is displayed with a
pause icon as shown below.
Step 7 : When we execute the script, the script execution is paused where the
breakpoint is inserted. This will help the user to evaluate the value/presence of
an element when the execution is in progress.
16
Selenium
To insert a verification point in recording mode, "Right click" on the element and
choose "Show all Available Commands" as shown below.
17
Selenium
18
Selenium
Given below are the mostly used verification commands that help us check if a
particular step has passed or failed.
verifyElementPresent
assertElementPresent
verifyElementNotPresent
assertElementNotPresent
verifyText
assertText
19
Selenium
verifyAttribute
assertAttribute
verifyChecked
assertChecked
verifyAlert
assertAlert
verifyTitle
assertTitle
Synchronization Points
During script execution, the application might respond based on server load,
hence it is required for the application and script to be in sync. Given below are
a few commands that we can use to ensure that the script and application are in
sync.
waitForAlertNotPresent
waitForAlertPresent
waitForElementPresent
waitForElementNotPresent
waitForTextPresent
waitForTextNotPresent
waitForPageToLoad
waitForFrameToLoad
Pattern Matching
20
Selenium
globbing,
exact patterns.
Globbing
Most techies who have used file matching patterns in Linux or Windows while
searching for a certain file type like *.doc or *.jpg would be familiar with term
"globbing".
[ ] - called a character class, lets you match any single character found
within the brackets. [0-9] matches any digit.
To specify a glob in a Selenium command, prefix the pattern with the keyword
'glob:'. For example, if you would like to search for the texts "tax year 2013" or
"tax year 2014", then you can use the glob "tax year *" as shown below.
However the usage of "glob:" is optional while specifying a text pattern because
globbing patterns are the default in Selenium.
clickAndWait link=search
Exact Patterns
Patterns with the prefix 'exact:' will match the given text as it is. Let us say, the
user wants an exact match with the value string, i.e., without the glob operator
doing its work, one can use the 'exact' pattern as shown below. In this example,
the operator '*' will work as a normal character rather than a pattern-matching
wildcard character.
21
Selenium
clickAndWait link=search
Regular Expressions
Regular expressions are the most useful among the pattern matching techniques
available. Selenium supports the complete set of regular expression patterns
that Javascript supports. Hence the users are no longer limited by *, ?, and []
globbing patterns.
Example
For example, the following will test if an input field with the id 'name' contains
the string 'tax year', 'Tax Year', or 'tax Year'.
clickAndWait link=search
Let us add a 'while' Loop in Selenium IDE with the help of JavaScript.
Step 2 : Now launch 'Selenium IDE' and navigate to "Options" >> "Options" as
shown below.
23
Selenium
Step 3 : Click the 'Browse' button under 'Selenium Core Extensions' area and
point to the js file that we have saved in Step 1.
Step 5 : Now you will have access to a few more commands such as "Label",
"While", etc.
Step 6 : Now we will be able to create a While loop within Selenium IDE and it
will execute as shown below.
24
Selenium
25
Selenium
Step 2 : Navigate to "File" menu and select "Export Test Suite As" and the
options would be listed.
Step 3 : Now let us export the script to "WebDriver" and save it with a name.
26
Selenium
27
3.
Selenium
ENVIRONMENT
SETUP
In order to develop Selenium RC or WebDriver scripts, users have to ensure that
they have the initial configuration done. Setting up the environment involves the
following steps.
Configure Selenium RC
We need to have JDK (Java Development Kit) installed in order to work with
Selenium WebDriver/Selenium. Let us see how to download and install Java.
28
Selenium
29
Selenium
Step 4 : Select the appropriate installation. In this case, it is 'Windows 7-64' bit.
Click the appropriate link and save the .exe file to your disk.
Step 5 : Run the downloaded exe file to launch the Installer wizard. Click 'Next'
to continue.
30
Selenium
Step 7 : The installer is extracted and its progress is shown in the wizard.
31
Selenium
Step 8 : The user can choose the install location and click 'Next'.
Step 9 : The installer installs the JDK and new files are copied across.
32
Selenium
Step 10 : The Installer installs successfully and displays the same to the user.
33
Selenium
34
Selenium
35
Selenium
Step 5 : To configure the workspace, select the location where the development
has to take place.
36
Selenium
Step 2 : The add-on installer is shown to the user and it is installed upon
clicking the 'Install' button.
37
Selenium
Step 4 : FirePath, a plugin that works within Firebug, helps users to grab the
'XPath' of an element. Install FirePath by navigating to
"https://addons.mozilla.org/en-US/firefox/addon/firepath/"
38
Selenium
Step 5 : The add-on installer is shown to the user and it is installed upon
clicking the 'Install' button.
Example
Now let us understand how to use FireBug and FirePath with an example. For
demonstration, we will use www.google.com and capture the properties of the
text box of "google.com".
Step 1 : First click on the arrow icon as highlighted in the following screenshot
and drag it to the object for which we would like to capture the properties. The
HTML/DOM of the object would be displayed as shown below. We are able to
capture the 'ID' of the input text box with which we can interact.
39
Selenium
Step 2 : To fetch the XPath of the object, go to 'firepath' tab and perform the
following steps.
Select the Control for which we would like to capture the XPath.
Configure Selenium RC
Now let us look at how to configure Selenium Remote control. We will
understand how to develop scripts with Selenium RC in later chapters, however
for now, we will understand just the configuration part of it.
40
Selenium
Step 3 : To start the server, use the command 'java -jar <<downloaded jar
name >> and if java JDK is installed properly, you would get a success message
as shown below. Now we can start writing Selenium RC scripts.
41
Selenium
42
Selenium
Step 2 : The downloaded file is in Zipped format and one has to unzip the
contents to map it to the project folder.
43
4.
Selenium
SELENIUM
RC
What is Selenium RC?
Selenium Remote Control (RC) was the main Selenium project that sustained
for a long time before Selenium WebDriver (Selenium 2.0) came into existence.
Now Selenium RC is hardly in use, as WebDriver offers more powerful features,
however users can still continue to develop scripts using RC.
It allows us to write automated web application UI tests with the help of full
power of programming languages such as Java, C#, Perl, Python, and PHP to
create more complex tests such as reading and writing files, querying a
database, and emailing test results.
Selenium RC Architecture
Selenium RC works in such a way that the client libraries can communicate with
the Selenium RC Server passing each Selenium command for execution. Then
the server passes the Selenium command to the browser using Selenium-Core
JavaScript commands.
The browser executes the Selenium command using its JavaScript interpreter.
44
Selenium
RC – Scripting
Now let us write a sample script using Selenium Remote Control. Let us use
http://www.calculator.net/ for understanding Selenium RC. We will perform a
Percent calculation using 'Percent Calculator' that is present under the 'Math
Calculators' module.
Step 1 : Start Selenium Remote Control (with the help of command prompt).
Step 2 : After launching Selenium RC, open Eclipse and create a "New Project"
as shown below.
45
Selenium
46
Selenium
Step 4 : Verify the Source, Projects, Libraries, and Output folder and click
'Finish'.
47
Selenium
Step 5 : Right click on 'project' container and choose 'Configure Build Path'.
Step 6 : Properties for 'selrcdemo' opens up. Navigate to 'Libraries' tab and
select 'Add External JARs'. Choose the Selenium RC jar file that we have
downloaded and it would appear as shown below.
48
Selenium
Step 8 : Create a new class file by performing a right click on 'src' folder and
select 'New' >> 'class'.
49
Selenium
Step 9 : Enter a name of the class file and enable 'public static void main' as
shown below.
Step 10 : The Created Class is created under the folder structure as shown
below.
50
Selenium
Step 11 : Now it is time for coding. The following code has comments
embedded in it to make the readers understand what has been put forth.
package selrcdemo;
import
com.thoughtworks.selenium.DefaultSelenium;
import com.thoughtworks.selenium.Selenium;
51
Selenium
if (result == "5")
{
System.out.println("Pass");
}else
{
System.out.println("Fail");
}
}
}
Step 11 : Now, let us execute the script by clicking the 'Run' Button.
52
Selenium
Step 12 : The script would start executing and the user would be able to see
the command history under the 'Command History' Tab.
Step 13 : The final state of the application is shown as below. The percentage is
calculated and it displays the result on the screen as shown below.
Step 14 : The output of the test is printed on the Eclipse console as shown
below, as we have printed the output to the console. In real time, the output is
written to an HTML file or in a simple Text file.
53
5.
Selenium
SELENESE
COMMANDS
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
54
Selenium
specified location
55
Selenium
56
Selenium
locator.
57
Selenium
selected window
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
58
Selenium
59
Selenium
60
Selenium
input field.
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
61
Selenium
62
Selenium
63
Selenium
Locators
Element Locators help Selenium to identify the HTML element the command
refers to. All these locators can be identified with the help of FirePath and
FireBug plugin of Mozilla. Please refer the Environment Setup chapter for details.
identifier=id Select the element with the specified "id" attribute and
if there is no match, select the first element whose @name attribute is id.
id=id Select the element with the specified "id" attribute.
name=name Select the first element with the specified "name"
attribute
dom=javascriptExpression Selenium finds an element by evaluating
the specified string that allows us to traverse through the HTML Document
Object Model using JavaScript. Users cannot return a value but can
evaluate as an expression in the block.
xpath=xpathExpression Locate an element using an XPath
expression.
link=textPattern Select the link element (within anchor
tags) which contains text matching the specified pattern.
css=cssSelectorSyntax Select the element using css
selector.
64
6.
Selenium
WEBDRIVER
WebDriver is a tool for automating testing web applications. It is popularly
known as Selenium 2.0. WebDriver uses a different underlying framework, while
Selenium RC uses JavaScript Selenium-Core embedded within the browser which
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:
AJAX-based UI elements.
Architecture
65
Selenium
Selenium RC Vs WebDriver
It’s a simple and small API. Complex and a bit large API as
compared to RC.
66
Selenium
67
Selenium
68
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.
69
Selenium
Step 7 : Now right-click on the package and select 'New' >> 'Class' to create a
'Class'.
70
Selenium
Step 8 : Now name the class and make it the main function.
71
Selenium
import
java.util.concurrent.TimeUnit;
import org.openqa.selenium.*;
import
org.openqa.selenium.firefox.FirefoxD
river;
73
Selenium
The following table lists some of the most frequently used commands in
WebDriver along with their syntax.
Command Description
74
Selenium
75
7.
Selenium
LOCATORS
Locating elements in Selenium WebDriver is performed with the help of
findElement() and findElements() methods provided by WebDriver and
WebElement class.
The following table lists all the Java syntax for locating elements in Selenium
WebDriver.
76
Selenium
HTML tag
By driver.findElement(By.partialLinkText(<linktext>)) Locates a
partial link using the
link text link's partial
text
By driver.findElement(By.xpath(<xpath>)) Locates an
XPath element
using XPath
query
Locators Usage
Now let us understand the practical usage of each of the locator methods with
the help of http://www.calculator.net
By ID
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).
77
Selenium
driver.findElement(By.id("cdensity")).sendKeys("10");
78
Selenium
By Name
Here an object is accessed with the help of names. In this case, it is the name of
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");
79
Selenium
By Class Name
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("smalltext smtb"));
By Tag Name
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.
80
Selenium
By Link Text
This method helps to locate a link element with matching visible text.
driver.findElements(By.linkText("Volume")).click();
81
Selenium
driver.findElements(By.partialLinkText("Volume")).click();
By CSS
The CSS is used as a method to identify the webobject, however NOT all
browsers support CSS identification.
WebElement loginButton =
driver.findElement(By.cssSelector("input.login"))
;
By XPath
XPath stands for XML path language. It is a query language for selecting nodes
from an XML document. XPath is based on the tree representation of
XML
82
Selenium
documents and provides the ability to navigate around the tree by selecting
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");
83
8.
Selenium
INTERACTIONS
User Interactions
Selenium WebDriver is the most frequently used tool among all the tools
available in the Selenium tool set. Therefore it is important to understand how to
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 are
no predefined commands.
Listed below are the different kinds of actions against those GUI objects:
Synchronization
Keyboard Actions
Mouse Actions
Multi Select
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.
84
Selenium
import
java.util.concurrent.TimeUnit;
import org.openqa.selenium.*;
import
org.openqa.selenium.firefox.FirefoxD
river;
/percent-calculator.html");
Thread.sleep(5000);
// Close the
Browser
Output driver.close();
The}output of the above script is displayed as shown below.
}
86
Selenium
In this section, we will understand how to interact with Radio Buttons. We can
select a radio button option using the 'click' method and unselect using the same
'click' method.
import
java.util.concurrent.TimeUnit;
import org.openqa.selenium.*;
import
org.openqa.selenium.firefox.FirefoxD
river;
driver.manage().window().maximize()
;
// Close the
Browser.
Selenium
import
java.util.concurrent.TimeUnit;
import org.openqa.selenium.*;
import 89
org.openqa.selenium.firefox.FirefoxD
river;
Selenium
90
driver.close();
}
}
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.
Dropdown Interaction
In this section, we will understand how to interact with Dropdown Boxes. We can
select an option using 'selectByVisibleText' or 'selectByIndex' or 'selectByValue'
methods.
91
Selenium
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.*;
import
org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.Select;
dropdown.selectByVisibleText("continuously"
);
driver.findElement(By.id("ccompound")).isSelected());
driver.findElement(By.id("ccompound")).isEnabled())
;
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.Sleep is a static wait and it is not a good way to use in scripts, as it is
sleep without condition.
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 once it is visible.
93
Selenium
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 is a kind of global wait which means the wait is applicable for the entire driver.
Hence, hardcoding this wait for longer time periods will hamper the execution
time.
Fluent Wait
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 say we will 60 seconds for an element to be available on the page, but we
will check its availability once in every 10 seconds.
In the example, we would like to drag an element 'Disable Node' from 'initially
open' folder to 'Parent Node' Folder.
import
java.util.concurrent.TimeUnit;
import org.openqa.selenium.*;
import
org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.interactions.Action; 95
Selenium
WebElement From =
driver.findElement(By.xpath(".//*[@id='j3_7']/a"))
;
WebElement To =
driver.findElement(By.xpath(".//*[@id='j3_1']/a"))
;
driver.clos
e();
96
}
}
Selenium
Output
After performing the drag-drop operation, the output would be as shown below.
Keyboard Actions
Given below are the methods to perform keyboard actions:
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.
Here are the syntax to call keyboard functions using Selenium WebDriver.
void sendKeys(java.lang.CharSequence
keysToSend) void
pressKey(java.lang.CharSequence keyToPress)
void releaseKey(java.lang.CharSequence
keyToRelease)
Mouse Actions
Listed below are some of the key mouse actions that one would come across in
most of the applications:
97
Selenium
Here are the syntax to call mouse actions using Selenium WebDriver:
Example
Let us say, we want to select 3 items from this list as shown below:
98
Selenium
import java.util.List;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.*;
import
org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.interactions.Action;
driver.manage().timeouts().implicitlyWait(10,
TimeUnit.SECONDS); driver.navigate().to("
http://demos.devexpress.com
/aspxeditorsdemos/ListEditors/MultiSelect.aspx");
//driver.manage().window().maximize(); 99
driver.findElement(By.id("ContentHolder_lbSelectionMode_I")).click(
);
driver.findElement(By.id("ContentHolder_lbSelectionMode
Selenium
_DDD_L_LBI1T0")).click();
Thread.sleep(5000);
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.
100
Selenium
Testers might be in a situation to find all the links on a 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
import org.openqa.selenium.*;
import
org.openqa.selenium.firefox.FirefoxDriver;
public class getalllinks
{
public static void main(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("Number of Links in the Page is "
+ links.size());
for (int i = 1; i<=links.size(); i=i+1)
{
System.out.println("Name of Link# " + i -
+ links.get(i).getText());
}
}
}
Output
The output of the script would be thrown to the console as shown below. Though
there are 65 links, only partial output is shown below.
101
Selenium
102
9.
Selenium
TEST DESIGN
TECHNIQUES
There are various components involved in designing the tests. Let us understand
some of the important components involved in designing a framework as well.
We will learn the following topics in this chapter:
Log4j Logging
Exception Handling
Capture Screenshots
Capture Videos
Selenium acts on webelements with the help of their properties such ID, name,
XPath, etc. Unlike QTP which has an inbuilt object repository (OR), Selenium has
no inbuilt ORs.
Advantages
POM is an implementation where test objects and functions are separated
from each other, thereby keeping the code clean.
Objects are created for each one of the pages and methods are developed 103
exclusively to access to those objects. Let us use http://calculator.net for
understanding the same.
Selenium
There are various calculators associated with it and each one of those objects in
a particular page is created in a separate class file as static methods and they 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 percent calculator test.
package PageObject;
import org.openqa.selenium.*;
public class
page_objects_perc_calc
{
private static WebElement
element = null;
// Calculate Button
public static WebElement btn_calc(WebDriver
driver)
{
element =
driver.findElement(By.xpath(".//*[@id='content']/table/tbod
y
/tr/td[2]/input"));
return element;
} 105
// Result
public static
WebElement
web_result(WebDriver
Selenium
{
element =
driver.findElement(By.xpath(".//*[@id='content']/p[2]/span/font/b"));
return element;
}
}
Step 2 : Create a class with main and import the package and create methods
for each one of those object identifiers as shown below.
package PageObject;
import java.util.concurrent.TimeUnit;
import
org.openqa.selenium.WebDriver;
import
org.openqa.selenium.firefox.FirefoxDr
iver;
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();
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(" The Result is Pass");
}
else
{
System.out.println(" The Result is Fail");
}
driver.close();
}
}
Output
The test is executed and the result is printed in the console. Given below is the
snapshot of the same.
Download JAR
107
Selenium
108
Selenium
Step 5 : Now create a new project and add all the 'External JARs' under 'poi-
3.10.FINAL' folder.
Step 6 : Now add all the 'External JARs' under the 'ooxml-lib' folder.
109
Selenium
Step 7 : Now add all the 'External JARs' under the 'lib' folder.
110
Selenium
Step 9 : The Package Explorer is displayed as shown below. Apart from that,
add 'WebDriver' related JAR's
111
Selenium
Parameterization
For demonstration, we will parameterize the percent calculator test.
Step 1 : We will parameterize all the inputs required for percent calculator using
Excel. The designed Excel is shown below.
Step 2 : Execute all the percent calculator functions for all the specified
parameters.
112
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.
import java.io.*;
import org.apache.poi.xssf.usermodel.*;
{
try
{
Selenium
return
ExcelWSheet.getPhysicalNumberOfRows();
}
catch (Exception e)
{
throw (e);
}
}
// This method to get the data and get the value as strings.
public String getCellDataasstring(int RowNum, int ColNum) throws Exception
{
try
{
String CellData =
ExcelWSheet.getRow(RowNum).getCell(ColNum).getStringCellValue();
System.out.println("The value of CellData " + CellData);
return CellData;
}
catch (Exception e)
{
return "Errors in Getting Cell Data";
}
}
// This method to get the data and get the value as number.
public double getCellDataasnumber(int RowNum, int ColNum) throws Exception
{
try
{
double CellData =
ExcelWSheet.getRow(RowNum).getCell(ColNum).getNumericCellValue();
114
Selenium
catch (Exception e)
{
return 000.00;
}
}
}
Step 4 : Now add a main method which will access the Excel methods that we
have developed.
import java.io.*;
import org.apache.poi.xssf.usermodel.*;
}
catch (Exception e)
Selenium
{
throw (e);
}
}
catch (Exception e)
{
throw (e);
}
}
// This method to get the data and get the value as number.
public double getCellDataasnumber(int RowNum, int ColNum) throws Exception
{
try
{
double CellData =
ExcelWSheet.getRow(RowNum).getCell(ColNum).getNumericCellValue();
// Cell = ExcelWSheet.getRow(RowNum).getCell(ColNum);
// String CellData = Cell.getStringCellValue();
System.out.println("The value of CellData " +
CellData); return CellData;
}
catch (Exception e)
{
return 000.00;
}
}
}
Output
Upon executing the script, the output is displayed in the console as shown
below.
117
Selenium
Log4j Logging
Log4j is an audit logging framework that gives information about what has
happened during execution. It offers the following advantages:
Can also be used for auditing purposes to look at the application's health.
Components
1. Instance of Logger class.
2. Log level methods used for logging the messages as one of the following:
error
warn
info
debug
log
Example
Let us use the same percent calculator for this demo.
118
Selenium
119
Selenium
Step 3 : Enter the name of the project as 'log4j_demo' and click 'Next'.
120
Selenium
Step 5 : Click Add External Jar and add Selenium WebDriver Libraries.
Step 6 : Click Add External Jar and add Selenium WebDriver JAR's located in the
Libs folder.
121
Selenium
Step 7 : Add a New XML file using which we can specify the Log4j properties.
122
Selenium
Step 10 : Now add the properties of Log4j which would be picked up during
execution.
import
java.util.concurrent.TimeUnit;
import org.openqa.selenium.*;
import
org.openqa.selenium.firefox.FirefoxD
river;
logger.info("# # # # # # # # # # # # # # # # # # #
# # # # # # # # ");
logger.info("TEST Has Started");
124
// Maximize the browser
driver.manage().window().maximize()
;
125
if(result.equals("5"))
{
logger.info("The Result is Pass");
Selenium
}
else
{
logger.error("TEST FAILED. NEEDS INVESTIGATION");
}
logger.info("# # # # # # # # # # # # # # # # # # # # # # # # # # # ");
// Close the
Browser.
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.
126
Selenium
Exception Handling
When we are developing tests, we should ensure that the scripts can continue
their execution even if the test fails. An unexpected exception would be thrown if
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
{
// Perform Action
}
catch(ExceptionType1 exp1)
{
// Catch block 1
}
catch(ExceptionType2 exp2)
{
// Catch block 2
}
catch(ExceptionType3 exp3)
{
// Catch block 3
}
finally
{
// The finally block always executes.
}
127
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 have a try-catch block if we want to
exit smoothly from a function.
FileUtils.copyFile(screenshot, new
File("D:\\framework\\
screenshots.jpg"));
throw(e1);
}
Multi
} Browser Testing
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.
128
Selenium
First of all, ensure that you have appropriate drivers downloaded. Please refer
the chapter "Selenium Grid" for downloading IE and Chrome drivers.
Example
For demonstration, we will perform percent calculator in all the browsers
simultaneously.
package TestNG;
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.*;
import
org.testng.annotations.*;
@Parameters("browser"
) @BeforeTest
public void
launchapp(String
browser)
{
if
(browser.equalsIgnore
Case("firefox"))
{
System.out.println
(" Executing on
FireFox");
129
driver = new
FirefoxDriver();
driver.get(URL);
driver.manage().timeouts().implicitlyWait(10,
TimeUnit.SECONDS); driver.manage().window().maximize();
Selenium
{
System.out.println(" Executing on CHROME");
System.out.println("Executing on IE");
System.setProperty("webdriver.chrome.driver"
, "D:\\chromedriver.exe");
driver = new
ChromeDriver();
driver.get(URL);
driver.manage().timeouts().implicitlyWait(10,
TimeUnit.SECONDS); driver.manage().window().maximize();
}
else if (browser.equalsIgnoreCase("ie"))
{
System.out.println("Executing on IE");
System.setProperty("webdriver.ie.driver"
, "D:\\IEDriverServer.exe");
driver = new
InternetExplorerDriver();
driver.get(URL);
driver.manage().timeouts().implicitlyWait(10,
TimeUnit.SECONDS); driver.manage().window().maximize();
}
else
{
throw new IllegalArgumentException("The Browser Type is
Undefined");
}
}
@Test
public void calculatepercent()
{
// Click on Math Calculators
driver.findElement(By.xpath(".//*[@id='menu']/div[3]/a")).click()
; 130
if(result.equals("5"))
{
System.out.println(" The Result is
Pass");
}
else
{
System.out.println(" The Result is Fail");
}
}
@AfterTest
public void closeBrowser()
{
131
driver.close();
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.
132
Selenium
Execute the script by performing right-click on the XML file and select 'Run As'
>> 'TestNG' Suite as shown below.
Output
All the browsers would be launched simultaneously and the result would be
printed in the console.
133
Selenium
134
Selenium
Capture Screenshots
Screenshots are configured differently for local executions and Selenium Grid
(remote) executions. Let us take a look at each one them with an example.
Localhost Execution
In the following example, we will take a screenshot after calculating the
percentage. Ensure that you give a valid path to save the screenshot.
import java.io.File;
import
java.io.IOException;
import
java.util.concurrent.TimeUn
it;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.*;
import
org.openqa.selenium.firefox.FirefoxDriv
er;
135
// Launch website driver.navigate().to("
http://www.calculator.net/");
File screenshot =
((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE)
;
FileUtils.copyFile(screenshot, new
File("D:\\screenshots\\
screenshots1.jpg"));
// Close the
Browser.
driver.close();
Selenium
Output
Upon executing the script, the screenshot is saved in the 'D:\screenshots' folder
with the name 'screenshots1.jpg' as shown below.
Example
We will execute the script on a Firefox node attached to a hub. For more on
configuring hub and nodes, please refer the Selenium Grids chapter.
package TestNG;
import org.openqa.selenium.remote.Augmenter;
import
org.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; 137
import java.net.URL;
import java.net.MalformedURLException;
import
org.apache.commons.io.FileUtils;
Selenium
import
org.openqa.selenium.remote.RemoteWebDriver;
import java.io.IOException;
@Parameters("browser"
) @BeforeTest
public void
launchapp(String
browser) throws
MalformedURLException
{
String URL = "http://www.calculator.net
"; if
(browser.equalsIgnoreCase("firefox"))
{
System.out.println(" Executing on FireFox");
String Node =
"http://10.112.66.52:5555/wd/hub";
DesiredCapabilities cap =
DesiredCapabilities.firefox();
cap.setBrowserName("firefox");
// Launch website
driver.navigate().to(URL);
Selenium
Undefined");
}
}
@Test
public void calculatepercent() throws IOException
{
// Click on Math Calculators
driver.findElement(By.xpath(".//*[@id='menu']/div[3]/a")).click()
;
if(result.equals("5"))
{
System.out.println(" The Result is
Pass");
}
else
{
System.out.println(" The Result is
Fail");
}
}
@AfterTest
public void closeBrowser()
{
driver.quit();
Output
}
Upon
} executing the script, the screenshot is captured and saved in the specified
location as shown below.
140
Selenium
Capturing Videos
Sometimes we may not be able to analyze the failures just with the help of a log
file or a screenshot. At times, it helps to capture the complete execution as a
video. Let us understand how to capture videos.
Configuration
Step 1 : Navigate to the URL - http://www.randelshofer.ch/monte/index.html
and download the screen recorder JAR as shown below.
141
Selenium
142
Selenium
Step 2 : After downloading, add the JAR file to the Libraries of the current
project.
Step 3 : We will use Java's AWT package to initialize the graphics configuration.
GraphicsConfiguration gc = GraphicsEnvironment
.getLocalGraphicsEnvironment()
.getDefaultScreenDevice()
.getDefaultConfiguration();
Parameter Description
143
Selenium
Video and compression format The output format (AVI) of the movie with
number of frames/sec.
Color of the mouse cursor and Specifies the mouse cursor color and
refresh rate refresh rate.
Example
We will capture a video of the simple test execution - percent calculation.
import java.io.File;
import
java.io.IOException;
import
java.util.concurrent.TimeUn
it;
import
org.apache.commons.io.FileUtils;
import org.openqa.selenium.*;
import
org.openqa.selenium.firefox.FirefoxDri
ver;
import
org.openqa.selenium.WebDriver;
import org.openqa.selenium.By;
import org.monte.media.math.Rational;
import org.monte.media.Format;
import
org.monte.screenrecorder.ScreenRecord
er;
144
import static
org.monte.media.AudioFormatKeys.*; import
static org.monte.media.VideoFormatKeys.*;
import java.awt.*;
Selenium
File screenshot =
((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE)
;
FileUtils.copyFile(screenshot, new
File("D:\\screenshots\\ 146
screenshots1.jpg"));
Selenium
// Close the
Browser.
driver.close();
// Stop the
ScreenRecorder
screenRecorder.stop();
Output
}
The
} recorded video is saved in the "C:\users\<<UserName>>\Videos" folder as
shown below.
147
10.
Selenium
TestNG
What is TestNG?
TestNG is a powerful testing framework, an enhanced version of JUnit which was
in use for a long time before TestNG came into existence. NG stands for 'Next
Generation'.
Inbuilt reporting
148
Selenium
Step 3 : The dialog box 'Add Repository' opens. Enter the name as 'TestNG' and
click 'OK'
149
Selenium
Step 4 : Click 'Select All' and 'TestNG' would be selected as shown in the figure.
150
Selenium
Step 6 : Review the items that are selected and click 'Next'.
151
Selenium
Step 8 : TestNG starts installing and the progress would be shown follows.
Step 10 : The Installer prompts to restart Eclipse for the changes to take effect.
Click 'Yes'.
Annotations in TestNG
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.
Annotations are strongly typed, so the compiler will flag any mistakes
right away.
Annotation Description
@BeforeSuite The annotated method will be run only once before all the
tests in this suite have run.
@AfterSuite The annotated method will be run only once after all the
tests in this suite have run.
@BeforeClass The annotated method will be run only once before the first
test method in the current class is invoked.
@AfterClass The annotated method will be run only once after all the test
methods in the current class have run.
@BeforeTest The annotated method will be run before any test method
belonging to the classes inside the <test> tag is run.
@AfterTest The annotated method will be run after all the test methods
belonging to the classes inside the <test> tag have run.
@BeforeGroups The list of groups that this configuration method will run
before. This method is guaranteed to run shortly before the
first test method that belongs to any of these groups is
invoked.
@AfterGroups The list of groups that this configuration method will run
153
Selenium
@BeforeMethod The annotated method will be run before each test method.
@AfterMethod The annotated method will be run after each test method.
154
Selenium
TestNG-Eclipse Setup
Step 1 : Launch Eclipse and create a 'New Java Project' as shown below.
155
Selenium
Step 3 : Navigate to "Libraries" Tab and add the Selenium Remote Control
Server JAR file by clicking on "Add External JAR's" as shown below.
Step 4 : The added JAR file is shown here. Click 'Add Library'.
156
Selenium
Step 5 : The 'Add Library' dialog opens. Select 'TestNG' and click 'Next' in the
'Add Library' dialog box.
157
Selenium
Step 7 : Upon creating the project, the structure of the project would be as
shown below.
158
Selenium
159
Selenium
160
Selenium
Step 11 : Select the 'Package name', the 'class name', and click 'Finish'.
Step 12 : The Package explorer and the created class would be displayed.
161
Selenium
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
followed by '@Test' and then '@AfterTest'. Please note that there can be any number of '@Test'
annotation in a class but '@BeforeTest' and '@AfterTest' can appear only once.
package TestNG;
import
java.util.concurrent.TimeUnit;
import org.openqa.selenium.*;
import
org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.AfterTest;
import
org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
@BeforeTest
public void launchapp()
{
//Puts an Implicit wait, Will wait
for 10 seconds
// before throwing exception
driver.manage().timeouts().implicitlyWait(10,
TimeUnit.SECONDS);
//Launch website
driver.navigate().to("http://www.calculator.net
"); driver.manage().window().maximize(); 162
@Test
public void calculatepercent()
Selenium
{
// Click on Math Calculators
driver.findElement(By.xpath(".//*[@id='menu']/div[3]/a")).click()
;
Calculator driver.findElement(By.id("cpar2")).sendKeys("50");
}
}
@AfterTest
public void terminatetest()
{
driver.close();
}
}
Execution
To execute, right-click on the created XML and select "Run As" >> "TestNG
Suite"
164
Selenium
Result Analysis
The output is thrown to the console and it would appear as shown below. The
console output also has an execution summary.
The result of TestNG can also be seen in a different tab. Click on 'HTML Report
View' button as shown below.
165
11.
Selenium
SELENIUM
GRID
Selenium Grid is a tool that distributes the tests across multiple physical or
virtual machines so that we can execute scripts in parallel (simultaneously). It
dramatically accelerates the testing process across browsers and across
platforms by giving us quick and accurate feedback.
Hub - The hub can also be understood as a server which acts as the
central point where the tests would be triggered. A Selenium Grid has
only one Hub and it is launched on a single machine once.
Node - Nodes are the Selenium instances that are attached to the Hub
which execute the tests. There can be one or more nodes in a grid which
can be of any OS and can contain any of the Selenium supported
browsers.
166
Selenium
Architecture
Test Execution
Result Analysis
167
Selenium
Step 1 : Download the latest Selenium Server standalone JAR file from
http://docs.seleniumhq.org/download/. Download it by clicking on the version as
shown below.
Step 2 : Start the Hub by launching the Selenium Server using the following
command. Now we will use the port '4444' to start the hub.
Note : Ensure that there are no other applications that are running on port#
4444.
168
Selenium
Step 3 : Now open the browser and navigate to the URL http//localhost:4444
from the Hub (The system where you have executed Step#2).
Step 4 : Now click on the 'console' link and click 'view config'. The config of the
hub would be displayed as follows. As of now, we haven't got any nodes, hence
we will not be able to see the details.
Where,
D:\JAR\selenium-server-standalone-2.42.2.jar = Location of the
Selenium Server Standalone Jar File(on the Node Machine)
http://10.30.217.157:4444 = IP Address of the Hub and 4444 is the
port of the Hub
browserName = firefox (Parameter to specify the Browser name on
Nodes) 5555 = Port on which Firefox Node would be up and running.
Step 3 : After executing the command, come back to the Hub. Navigate to the
URL - http://10.30.217.157:4444 and the Hub would now display the node
attached to it.
170
Selenium
Step 4 : Now let us launch the Internet Explorer Node. For launching the IE
Node, we need to have the Internet Explorer driver downloaded on the node
machine.
Where,
D:\IEDriverServer.exe = The location of the downloaded the IE
Driver(on the Node Machine)
D:\JAR\selenium-server-standalone-2.42.2.jar = Location of the
Selenium Server Standalone Jar File(on the Node Machine)
http://10.30.217.157:4444 = IP Address of the Hub and 4444 is the
port of the Hub
browserName = ie (Parameter to specify the Browser name on
Nodes) 5558 = Port on which IE Node would be up and running.
171
Selenium
Step 7 : After executing the command, come back to the Hub. Navigate to the
URL - http://10.30.217.157:4444 and the Hub would now display the IE node
attached to it.
Step 8 : Let us now launch the Chrome Node. For launching the Chrome Node,
we need to have the Chrome driver downloaded on the node machine.
172
Selenium
Step 10 : Download the driver based on the type of your OS. We will execute it
on Windows environment, hence we will download the Windows Chrome Driver.
After you have downloaded, unzip the exe file and place it in a folder which has
to be referred while launching chrome nodes.
173
Selenium
Where,
D:\chromedriver.exe = The location of the downloaded the
chrome Driver(on the Node Machine)
D:\JAR\selenium-server-standalone-2.42.2.jar = Location of the
Selenium Server Standalone Jar File(on the Node Machine)
http://10.30.217.157:4444 = IP Address of the Hub and 4444 is the
port of the Hub
browserName = chrome (Parameter to specify the Browser name on
Nodes) 5557 = Port on which chrome Node would be up and running.
Step 12 : After executing the command, come back to the Hub. Navigate to the
URL - http://10.30.217.157:4444 and the Hub would now display the chrome
node attached to it.
174
Selenium
package TestNG;
import
org.openqa.selenium.remote.DesiredCapabilities;
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.net.URL;
import
java.net.MalformedURLException;
import
org.openqa.selenium.remote.RemoteWebDriver;
@Parameters("browser")
@BeforeTest
public void
launchapp(String
browser) throws
MalformedURLException
175
{
String URL = "http://www.calculator.net
"; if
(browser.equalsIgnoreCase("firefox"))
{
Selenium
// Launch website
driver.navigate().to(URL);
driver.manage().window().maximize()
;
}
else if
(browser.equalsIgnoreCase("chrome"))
{
System.out.println(" Executing on CHROME");
DesiredCapabilities cap =
DesiredCapabilities.chrome();
cap.setBrowserName("chrome");
String Node = "http://10.112.66.52:5557/wd/hub";
driver = new RemoteWebDriver(new URL(Node),
cap); driver.manage().timeouts()
.implicitlyWait(10, TimeUnit.SECONDS);
//Launch website
driver.navigate().to(URL);
driver.manage().window().maximize()
;
}
else if (browser.equalsIgnoreCase("ie"))
{
System.out.println(" Executing on IE");
DesiredCapabilities cap =
DesiredCapabilities.chrome(); 176
cap.setBrowserName("ie");
String Node = "http://10.112.66.52:5558/wd/hub";
driver = new RemoteWebDriver(new URL(Node),
cap); driver.manage().timeouts()
Selenium
//Launch website
driver.navigate().to(URL);
driver.manage().window().maximize()
;
}
else
{
throw new IllegalArgumentException
("The Browser Type is
Undefined");
}
}
@Test
public void calculatepercent()
{
// Click on Math Calculators
driver.findElement(By.xpath(".//*[@id='menu']/div[3]/a")).click()
;
/span/font/b")).getText();
// Print a Log In message to the screen
System.out.println(" The Result is " +
result);
if(result.equals("5"))
{
System.out.println(" The Result is Pass");
}
else
{
System.out.println(" The Result is Fail");
}
}
@AfterTest
public void closeBrowser()
{
driver.quit();
}
}
Step 2 : The Browser parameter will be passed using XML. Create an XML under
the project folder.
178
Selenium
179
Selenium
Step 6 : The contents of the XML file are shown below. We create 3 tests and
put them in a suite and mention parallel="tests" so that all the tests would be
executed in parallel.
180
Selenium
</classes>
</test>
<test name="ChromeTest">
<parameter name="browser" value="chrome" />
<classes>
<class name="TestNG.TestNGClass" />
</classes>
</test>
<test name="IETest">
<parameter name="browser" value="ie" />
<classes>
<class name="TestNG.TestNGClass" />
</classes>
</test>
</suite>
Test Execution
Step 1 : Select the created XML; right-click and choose 'Run As' >> 'TestNG
Suite'.
181
Selenium
182
Selenium
Step 2 : Now open the Node, where we have launched all the browser nodes.
You will see all the three browsers in execution simultaneously.
Result Analysis
Step 1 : Upon completing the execution, we can analyze the result like any
other execution. The result summary is printed in the console as shown in the
following snapshot.
183
Selenium
Step 2 : Navigate to the 'Results of Running Suite' Tab and TestNG would
display the result summary as shown below.
Step 3 : Upon generating the HTML, we will be able to see the test results in
HTML format.
184