You are on page 1of 104

1

Vol.

SELENIUM WEBDRIVER WITH PRACTICAL EXAMPLES


Notes for Corporate Training

SeleniumWebDriver
FOR CORPORATE TRAINING

Selenium WebDriver Training Notes

 Raj
Hyderabad • Telangana State
Phone 000.000.0000 • Fax 000.000.0000
Topics
01. Why Selenium?
02. History of Selenium
03. WebDriver Architecture
04. Setting Up the Project in Eclipse
05. Object Identification Using Firebug
06. Finding WebElements
07. Actions on WebElements
08. Verification of Element State
09. Browser Commands
10. Wait Commands
11. Switching Control between Windows
12. Handling Different WebElements
13. Advanced Concepts of WebDriver
14. Handling Different Browsers
15. File Handling Using POI
16. Page Object Model
17. Log4j
18. Selenium Grid
19. Selenium Remote Control
20. Selenium IDE
21. JUnit
22. Maven
23. Automation Framework
24. Java
1
S E L E N I U M W E B D R I V E R
Topic

Why Selenium?

A
s the current industry trends have shown that there is mass movement
towards automation testing. The cluster of repetitive manual testing
scenarios has raised a demand to bring in the practice of automating these
manual scenarios.
The benefits of implementing automation test are many; let us take a look at them:
 Supports execution of repeated test cases
 Aids in testing a large test matrix
 Enables parallel execution
 Encourages unattended execution
 Improves accuracy thereby reducing human generated errors
 Saves time and money

All this results in to the following:


 High ROI
 Faster go to market

Automation testing benefits are many and well understood and largely talked about in
the software test industry.
One of the most commonly asked question comes with this is –
 What is the best tool for me to get my tests automated?
 Is there a cost involved?
 Is it easy to adapt?

One of the best answers to all the above questions for automating web based
applications is Selenium. Because:

 It‟s open source


 have a large user base and helping communities
 have multi browser and platform compatibility
 has active repository developments
 supports multiple language implementations

First glance at Selenium

1 Raj
S E L E N I U M W E B D R I V E R

Selenium is one of the most popular automated testing suites. Selenium is designed in
a way to support and encourage automation testing of functional aspects of web
based applications and a wide range of browsers and platforms. Due to its existence
in the open source community, it has become one of the most accepted tools
amongst the testing professionals.
Selenium supports a broad range of browsers, technologies and platforms.

2 Raj
2
S E L E N I U M W E B D R I V E R
Topic

History of Selenium

W
ith web applications becoming the defacto approach to developing end
user applications a solution for testing is needed. This has meant more and
more emphasis is needed on a browser automation framework to help
with checking the site. For years people have been using Selenium IDE
and Selenium RC to drive a number of different types of browsers. Selenium, when
originally created by Jason Huggins, solved the issue of getting the browser to do user
interactions.


This is a good automation framework however it is limited by the
JavaScript sandbox in browsers. The JavaScript sandbox enforces
security policies while JavaScript is executing to prevent malicious
code executing on the client machine. The main security policy
people come across is the Same Origin Policy. If you needed to
move from HTTP to HTTPS, like you normally would during a log
on process, the browser would block the action because we are no longer in the same
origin. This was quite infuriating for your average developer!

The Selenium API was originally designed to work from within the server. The
developer or tester writing the tests had to do so in HTML using a three column
design based on the FIT. You can see how this looks if you open up Selenium IDE:
the three input boxes that need to be completed for each line that will be executed. It
has a number of issues in that you cannot do anything that you may do with a Turing
complete language. Patrick Lightbody and Paul Hammant thought that there must be a
better way to drive their tests and in a way that they could use their favorite
development language. They created Selenium Remote Control using Java as a web
server that would proxy traffic. It would inject Selenium onto the page and then it
would be used in a similar manner as to what it was in the three column manner. This
also creates more of a procedural style of development. The Selenium RC API for the
programming languages that are supported have been designed to fit the original three
column syntax. Commonly known as Selenese, it has grown over the life of the project
to support the changes that have been happening to web applications.

This has had the unfortunate consequence that the API has grown organically so that
users can manipulate the browser the way they intend but still keep to the original three
column syntax. There is somewhere in the region of 140 methods available which

3 Raj
S E L E N I U M W E B D R I V E R

makes picking the right method for the job rather difficult. With the move to mobile
devices and HTML5, Selenium RC was starting to show that it wasn't able to fulfill its
original requirement: browser automation to mimic what the user is doing.

Simon Stewart, having hit a number of these issues, wanted to try a different approach
to driving the browser. While working for Thought Works, he started working on the
WebDriver project. It started originally as a way to drive HTMLUnit and Internet
Explorer but having learnt lessons from Selenium RC, Simon was able to design the
API to fit in with the way most developers think. Developers have been doing Object
Orientated development for a while, so moving away from the procedural style of
Selenium RC was a welcome change to developers.

The next section will go through the basic architecture of WebDriver.

4 Raj
S E L E N I U M W E B D R I V E R

3
Topic

WebDriver Architecture

T he WebDriver architecture does not follow the same approach as Selenium RC,
which was written purely in JavaScript for all the browser automation. The
JavaScript, in Selenium RC, would then emulate user actions. This JavaScript
would automate the browser from within the browser. WebDriver on the other hand
tries to control the browser from outside the browser. It uses accessibility API to drive
the browser. The accessibility API is used by
a number of applications for accessing and
controlling applications when they are used
by disabled users and is common to web
browsers. WebDriver uses the most
appropriate way to access the accessibility
API. If we look at Firefox, it uses JavaScript
to access the API. If we look at Internet
Explorer, it uses C++. This approach means
we can control browsers in the best possible
way but has the downside that new browsers
entering the market will not be supported
straight away like we can with Selenium RC.
Where that approach doesn't work we will then inject JavaScript into the page.
Examples of this are found in the new HTML5.

The system is made up of four different sections.

WebDriver API - The WebDriver API is the part of the system that you interact with
all the time. Things have changed from the 140 line long API that the Selenium RC
API had. This is now more manageable and can actually fit on a normal screen. You
will see this when you start using WebDriver in the next chapter. This is made up of
the WebDriver and the WebElement objects.

driver.findElement(By.name("q")) and element.sendKeys("I love cheese");

These commands are then translated to the SPI, which is stateless. This can be seen in
the next section.

5 Raj
S E L E N I U M W E B D R I V E R

WebDriver SPI - When code enters the Stateless Programming Interface or SPI, it is
then called to a mechanism that breaks down what the element is, by using a unique
ID, and then calling a command that is relevant. All of the API calls above then call
down.

Using the example in the previous section would be like the following code, once it
was in the SPI:

findElement(using="name", value="q") sendKeys(element="webdriverID", value="I


love cheese")

From there we call the JSON Wire protocol. We still use HTTP as the main transport
mechanism. We communicate to the browsers and have a simple client server
transport architecture the WebDriver developers created the JSON Wire Protocol.

JSON Wire Protocol - The WebDriver developers created a transport mechanism


called the JSON Wire Protocol. This protocol is able to transport all the necessary
elements to the code that controls it. It uses a REST like API as the way to
communicate.

Selenium Server - The Selenium server or browser, depending on what is processing,


uses the JSON Wire commands to break down the JSON object and then does what it
needs to. This part of the code is dependent on which browser it is running on.

The merging of two projects

Both Simon Stewart and Jason


Huggins thought that it would be a
really good idea to merge the two
projects together. This was then
called Selenium 2 aka Selenium
WebDriver.

6 Raj
S E L E N I U M W E B D R I V E R

4
Topic

Setting Up the Project in Eclipse


Now, let's set up our project in Eclipse and write our first piece of
code to use WebDriver and navigate to a web page. Please follow
the sequence of the following steps to create an Eclipse
WebDriver project:

1. Open Eclipse from the directory you have installed it in earlier. Navigate to File |
New | Java Project.

2. A New Java Project dialog appears, enter the project name of your choice, leave the
rest to default, and click Next.

3. In the next screen, go to the Libraries tab, click on the Add External JARs… button,
and select selenium-java-2.33.0.jar and selenium-java-2.33.0-srcs.jar files from the
downloaded location of Selenium WebDriver.

4. Click on the Add External JARs… button and add all the jars available under the libs
folder of the Selenium WebDriver directory(). Now the Libraries section should look
like this:

5. Click on Finish.

6. Now, let's create our first class that uses WebDriver to navigate to a web page. In the
project explorer window of Eclipse, right-click and navigate to src | New | Class, enter
the details of the class name and package name, and then click on Finish.
import org.junit.Test;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

public class Navigate {

@Test
public void launch() {
WebDriver driver = new FirefoxDriver();
driver.get("http://gmail.com");

}
}

7 Raj
S E L E N I U M W E B D R I V E R

5
Topic

Object Identification Using Firebug


Firebug is a Mozilla Firefox add-on. This tool helps us in identifying
or to be more particular inspecting HTML, CSS and JavaScript
elements on a web page. It helps us identifying the elements uniquely
on a webpage. The elements can be found uniquely based on their
locator types which we would be discussing later.

Installation of Firebug

1) Launch the Mozilla Firefox browser and navigate to this Firebug add-on
download page. The URL takes us to Firefox add-ons section.

2) Click on the “Add to Firefox” button present on the webpage. Refer the
following figure for the same.

3) As soon as we click on the “Add to Firefox” button, a security alert box would
appear, click on the “Allow” button now.

4) Now Firefox downloads the add-on in the backdrop and a progress bar is
displayed.

8 Raj
S E L E N I U M W E B D R I V E R

5) As soon as the process completes, software installation window appears. Now


click on the “Install Now” button.

6) As soon as the installation completes, a pop up appears saying that the firebug
has been installed successfully. Now choose to close this pop up.

7) Now to launch firebug by pressing F12

8) Now the firebug can be seen at the bottom of the Firefox window.

9 Raj
S E L E N I U M W E B D R I V E R

6
Topic

Finding WebElements

A
web page is comprised of many different HTML elements, such as buttons,
links, a body, labels, forms, and so on, that are named web objects. These
objects are also called as WebElements in the context of WebDriver.

Finding Elements
When working with WebDriver on a web application, we will need to find elements on
the page. This is the core to being able to work. All the methods for doing actions to
the web application like typing and clicking require that we find the element first.

Methods of Locating/Finding Elements


Locating elements in Selenium WebDriver is done by using the findElement() and
findElements() methods provided by WebDriver and WebElement class.

 The findElement() method returns a WebElement object based on a


specified search criteria or throws a runtime exception No Such Element
Exception if it does not find any element matching the search criteria.

 The findElements() method returns a list of WebElements matching the


search criteria. If no elements are found, it returns an empty list. Find methods
take a locator or query object as an instance of By class as an argument
WebDriver provides By class to support various locator strategies. Selenium
uses what is called locators to find and match the elements of your page that it
needs to interact with.

What is Locator?

Locator can be termed as an address that identifies a web element uniquely within the
webpage. Locators are the HTML properties of a web element which tells the
Selenium about the web element it need to perform action on.

Using the By locating mechanism

By is the locating mechanism passed to the findElement() method or the


findElements() method to fetch the respective WebElement(s) on a web page. There
are eight different locating mechanisms; that is, eight different ways to identify an

10 Raj
S E L E N I U M W E B D R I V E R

HTML element on a web page. They are located by Name, ID, TagName, Class,
LinkText, PartialLinkText, XPath, and CSS.

The following table lists various locator strategies supported by Selenium WebDriver

Locator Syntax
1 By ID driver.findElement(By.id(<id>))
2 By Name driver.findElement(By.name(<name>))
3 By Class Name driver.findElement(By.className())
4 By Tag Name driver.findElement(By.tagName(<tagName>))
5 By Link Text driver.findElement(By.linkText(<linkName>))
6 By Partial Link Text driver.findElement(By.partialLinkText(<>))
7 By CSS driver.findElement(By.cssSelector(<cssSelector>))
8 By XPath driver.findElement(By.xPath(<xPathXpression>))

Finding elements by the ID attribute

Using the id attribute is the most preferable way to locate elements on a page. The
W3C standard recommends that developers provide an id attribute for elements that
are unique to each element. Having a unique id attribute provides a very explicit and
reliable way to locate elements on the page. While processing the DOM, browsers use
id as the preferred way to identify the elements and this provides the fastest locator
strategy.
public class Gmail {
@Test
void login() {
WebDriver driver = new FirefoxDriver();
driver.get("http://gmail.com");

driver.findElement(By.id("Email")).sendKeys("testing");
}
}

Finding elements by the Name attribute

Finding elements by name is just as fast as their ID equivalent. This method is a helper
method that sets an argument for a more generic findElement.
public class Gmail {
@Test
void login() {
WebDriver driver = new FirefoxDriver();
driver.get("http://gmail.com");

11 Raj
S E L E N I U M W E B D R I V E R

driver.findElement(By.name("Email")).sendKeys("testing");
}
}

Finding elements by the Class Name attribute

In order to apply styles to an element, they can be declared directly in the element tag
or placed in a separate file called the CSS file and can be referenced in the element
using the className() method. For instance, a style attribute for a button can be
declared in a CSS file as follows:
.gbqfba {
background: -moz-linear-gradient(center top , rgb(245, 245, 245),
rgb(241, 241, 241)) repeat scroll 0 0 rgba(0, 0, 0, 0);
border: 1px solid rgba(0, 0, 0, 0.1);
color: rgb(68, 68, 68) !important;
font-size: 11px;
}

Now, this style can be applied on the button element in a web page as follows:
<button id="gbqfba" class="gbqfba" name="btnK" aria-label="Google Search">

So, “gbqfba” is used as value for the class attribute of the button element, and it
inherits all the styles declared in the CSS file. The code for that is as follows:

12 Raj
S E L E N I U M W E B D R I V E R

public class ByClassTesting {


@Test
void gmailTest() {
WebDriver driver = new FirefoxDriver();
driver.get("http://google.com");
driver.findElement(By.className("gbqfba")).click();
}
}

Finding elements by the Tag Name attribute

Using the id attribute is the most preferable way to locate elements on a page. The
W3C standard

Finding elements by the Link Text attribute

The By.linkText locating mechanism can only be used to identify the HTML links. The
HTML link elements are represented on a web page using the <a> tag, abbreviation
for the anchor tag. A typical anchor tag looks like this:

<a href="/intl/en/about.html">About</a>

Here, href is the link to a different page where your web browser will take you when
clicked on the link. So, the preceding HTML code when rendered by the browser
looks like this:

This About is the link text. So the locating mechanism By.linkText uses this text on an
anchor tag to identify the WebElement. The code for this would look like this:
public class ByLinkTextTesting {
@Test
void gmailTest() {
WebDriver driver = new FirefoxDriver();
driver.get("http://google.com");
WebElement aboutLink =
driver.findElement(By.linkText("About"));
aboutLink.click();
}
}

Finding elements by the Partial Link Text attribute

13 Raj
S E L E N I U M W E B D R I V E R

The By.partialLinkText locating mechanism is an extension to the previous one. If you


are not sure of the entire link text or want to use only part of the link text, you can use
this locating mechanism to identify the link element.

public class ByPartialLinkTextTesting {


@Test
void gmailTest() {
WebDriver driver = new FirefoxDriver();
driver.get("http://google.com");
WebElement aboutLink =
driver.findElement(By.partialLinkText("About"));
aboutLink.click();
}
}

What happens if there are multiple links whose text has About in it? If you want all the
WebElements which contain About in its link text, use the findElements() method,
which will return a list of all those elements.

Finding elements by the XPath attribute

Xpath is used to locate a web element based on its XML path. XML stands for
Extensible Markup Language and is used to store, organize and transport arbitrary
data. It stores data in a key-value pair which is very much similar to HTML tags. Both
being mark up languages and since they fall under the same umbrella, xpath can be
used to locate HTML elements.

The fundamental behind locating elements using Xpath is the traversing between
various elements across the entire page and thus enabling a user to find an element
with the reference of another element.

Xpath can be created in two ways:

Relative Xpath
Relative Xpath begins from the current location and is prefixed with a “//”.
For example: //span[@class=‟Email‟]

Absolute Xpath
Absolute Xpath begins with a root path and is prefixed with a “/”.
For example: /html/body/div/div[@id=‟Email‟]

Key Points:

14 Raj
S E L E N I U M W E B D R I V E R

 The success rate of finding an element using Xpath is too high. Along with the
previous statement, Xpath can find relatively all the elements within a web
page. Thus, Xpaths can be used to locate elements having no id, class or name.

 Creating a valid Xpath is a tricky and complex process. There are plug-ins
available to generate Xpath but most of the times, the generated Xpaths fails to
identify the web element correctly.

 While creating xpath, user should be aware of the various nomenclatures and
protocols.

Selenium Xpath Examples

Xpath Checker

Creating Xpath becomes a little simpler by using Xpath Checker. Xpath Checker is a
firefox add-on to automatically generate Xpath for a web element. The add-on can be
downloaded and installed like any other plug-in. The plug-in can be downloaded from
https://addons.mozilla.org/en-US/firefox/addon/xpath-checker/

As soon as the plug-in is installed, it can be seen in the context menu by right clicking
any element whose xpath we want to generate.

Click on the “View Xpath” to see the Xpath expression of the element. An editor
window would appear with the generated Xpath expression. Now user has the liberty

15 Raj
S E L E N I U M W E B D R I V E R

to edit and modify the generated Xpath expression. The corresponding results would
be updated cumulatively.

Note that the Xpath Checker is available for other browsers as well.

But re-iterating the fact, that most of the times, the generated Xpaths fails to identify
the web element rightly. Thus, it is recommended to create our own Xpath following
the pre defined rules and protocols.

In this sample, we would access “Google” image present at the top of the login form at
gmail.com.

Creating a Xpath of a web element

Step 1: Type “//img[@class=‟logo‟]” i.e. the locator value in the target box within the
Selenium IDE.

Syntax: Xpath of the element

16 Raj
S E L E N I U M W E B D R I V E R

Step 2: Click on the Find Button. Notice that the image would be highlighted with
yellow color with a florescent green border around the field.

Finding elements by the CSS attribute

The By.cssSelector() method is similar to the By.xpath() method in its usage but the
difference is that it is slightly faster than the By.xpath locating mechanism. Following
are the commonly used syntaxes to identify elements:

To identify an element using the div element with id #flrs, we use the #flrs syntax

To identify the child anchor element, we use the #flrs > a syntax, which will return the
link element

To identify the anchor element with its attribute, we use the #flrs >
a[a[href="/intl/en/about.html"]] syntax

Let's try to modify the previous code, which uses the XPath-locating mechanism to use
the cssSelector mechanism.

public class ByCssSelectorTesting {


@Test
void gmailTest() {
WebDriver driver = new FirefoxDriver();
driver.get("http://www.google.com");
WebElement searchButton =
driver.findElement(By.cssSelector("#gbqfba"));
System.out.println(searchButton.getText());
}
}

17 Raj
S E L E N I U M W E B D R I V E R

The preceding code uses the By.cssSelector locating mechanism that uses the css
selector ID of the Google Search button.

18 Raj
S E L E N I U M W E B D R I V E R

7
Topic

Actions on WebElements

T his section describes the different user actions that can be taken on a
WebElement. Different WebElements will have different actions that can be
taken on them. For example, in a textbox element, we can type in some text or
clear the text that is already typed in it. Similarly for a button, we can click on it, get the
dimensions of it, and so on.

Note: In case we try to execute a wrong action on a WebElement, we don't see any
exception or error thrown and also we don't see any action that really gets executed;
WebDriver ignores such actions silently.

GetAttribute()

The getAttribute action can be executed on all the WebElements to retrieve the name
of the attribute name.

WebElement in HTML :
<label name="Username" id="uname">Enter Username: </label>
Webdriver script:

WebElement txt = driver.findElement(By.id("uname"));


System.out.println("Name of the text is:
"+txt.getAttribute("name"));
SendKeys()

The sendKeys action is applicable for textbox or textarea HTML elements. This is used
to type text into the textbox. This will simulate the user keyboard and types text into
WebElements exactly as would a user.

WebElement uName = driver.findElement(By.name("q"));


uName.sendKeys("abc@gmail.com");
Using the Keys enumeration, you can simulate many special keys while typing into a
WebElement.

uName. sendKeys(Keys.chord(Keys.SHIFT,"abc@gmail.com"));

19 Raj
S E L E N I U M W E B D R I V E R

Clear()

The clear action is similar to the sendKeys() method, which is applicable for textbox
and textarea elements. This is used to erase the text that is entered in a WebElement
using the sendKeys() method. This can be achieved using the Keys.BACK_SPACE
enum, but WebDriver has given us an explicit method to clear the text easily.

WebElement uName = driver.findElement(By.name("q"));


uName.sendKeys("abc@gmail.com");
uName.clear();
Submit ()

The submit action can be taken on a form or on an element, which is inside a form.
This is used to submit a form of a web page to the server hosting the web application.

Note: when you use the submit() method on a WebElement, make sure it is part of the
form element otherwise its throws NoSuchElementException.

GetCssValue()

The getCssValue action can be taken on all the WebElements. This is used to fetch the
CSS properties' values of the given element. CSS properties can be font-family,
background-color, color, and so on. This is useful when you want to validate the CSS
styles that are applied to your WebElements through your test scripts.

WebElement uName = driver.findElement(By.name("q"));


System.out.println(uName.getCssValue(“font-family”));
GetLocation()

The getLocation action can be executed on all the WebElements. This is used to get
the relative position of an element where it is rendered on the web page. This position
is calculated relative to the top-left corner of the web page of which the (x, y)
coordinates are assumed as (0, 0). This method will be of use if your test script tries to
validate the layout of your web page.

WebElement uName = driver.findElement(By.name("q"));


System.out.println(uName. getLocation ());
Note: output of the getLocation() method is (x,y)

GetSize()

20 Raj
S E L E N I U M W E B D R I V E R

The getSize action can also be applied on all the visible components of HTML. It will
return the width and height of the rendered WebElement.

WebElement uName = driver.findElement(By.name("q"));


System.out.println(uName. getSize ());
Note: output of the getSize() method is the height and width of the WebElement.

GetText()

The getText action can be taken on all the WebElements. It will give the visible text if
the element contains any text on it or else will return nothing.

WebElement searchBtn = driver.findElement(By.name("btnK"));


System.out.println(searchBtn.getText());
Note: output of the getText() method would be the text present on WebElement.

To capture error message on webpage we can use predefined method called getText().
public class ErrorMsg {
@Test
public void testErrorMsg(){
WebDriver driver = new FirefoxDriver();
driver.get("http://gmail.com");
WebElement element = driver.findElement(By.id("signIn"));
element.click();
String errMsg =
driver.findElement(By.id("errormsg_0_Email")).getText();
System.out.println(errMsg);
}
}

GetTagName()

The getTagName action can be taken on all the WebElements. This will return the tag
name of the WebElement. For example, in the following HTML code, button is the
tag name of the HTML element:
<button id="gbqfba" class="gbqfba" name="btnK" aria-
label="GoogleSearch">

WebDriver script:

WebElement searchBtn = driver.findElement(By.name("btnK"));


System.out.println(searchBtn.getTagName());

21 Raj
S E L E N I U M W E B D R I V E R

Note: output of the getTagName () method would be the tag name of the
WebElement.

22 Raj
S E L E N I U M W E B D R I V E R

8
Topic

Verification of Element State


Couple of times while executing the test cases we need to check the certain conditions
like verify the element is enabled or not, verify the particular checkbox or radio button
element is selected or not and verify the element is displayed or not. To check all these
type of conditions we‟ve below predefined methods.

IsDisplayed()

The isDisplayed action verifies if an element is displayed on the web page and can be
executed on all the WebElements.

WebElement searchBtn = driver.findElement(By.name("btnK"));


System.out.println(searchBtn.isDisplayed());
Note: isDisplayed () method returns the true/false for button.

IsEnabled()

The isEnabled action verifies if an element is enabled on the web page and can be
executed on all the WebElements.

WebElement searchBtn = driver.findElement(By.name("btnK"));


System.out.println(searchBtn.isEnabled());
Note: isEnabled() method to determine if the element is displayed on a web page or
not and returns the true/false.

IsSelected()

The isSelected action verifies if an element is selected right now on the web page and
can be executed only on a radio button, options in select, and checkbox WebElements.
When executed on other elements, it will return false.

WebElement searchBox = driver.findElement(By.name("q"));


System.out.println(searchBox.isSelected());
Note: isSelected() method to determine if the element is selected on a web page or not
and returns the true/false.

23 Raj
S E L E N I U M W E B D R I V E R

9
Topic

Browser Commands
Get: This command is use to open a new web page in the current browser.
driver.get("http://google.com");

Get Title: This command is use to get the title of the current web page.
driver.getTitle();

Get Current URL: This command is use to get the URL of the web page
currently loaded in the browser.
driver.getCurrentUrl();

Get Page Source: This command is use to get the source of the last loaded web
page.
driver.getPageSource();

Close Command: This command is use to close the current window of the
browser.
driver.close();

Quit Command: This command is use to quit the browser and all opened
windows in the browser.
driver.quit();

Browser Navigation Commands

Refresh Command: This command is use to refresh the current browser.


driver.navigate().refresh();

Back Command: This command is use to go back to previous.


driver.navigate().back();

Forward Command: This command is use to go on to next page in the browser.


driver.navigate().forward();

To Command: This command is use to navigate on specific page or URL.


driver.navigate().to(“http://www.google.com”);

24 Raj
S E L E N I U M W E B D R I V E R

10
Topic

Wait Commands
ImplicitWait

Using ImplicitWait we can tell Selenium that we would like it to wait for a certain
amount of time before throwing an exception that it cannot find the element on
the page. We should note that implicit waits will be in place for the entire time the
browser is open. This means that any search for elements on the page could take
the time the implicit wait is set for.

public class ImplicitWait {


@Test
public void testImpWait(){
WebDriver driver = new FirefoxDriver();
driver.manage().timeouts().implicitlyWait(10,
TimeUnit.MILLISECONDS);
driver.get("http://google.com");
driver.findElement(By.name("q")).sendKeys("google");

}
}

ExplicitWait

We can create a wait for a set of common conditions using the expected condition
class. First, we need to create an instance of the WebDriverWait class by passing
the driver instance and timeout for a wait as follows.

public class ExplicitWait {


@Test
public void testExplcitWait(){
WebDriver driver = new FirefoxDriver();
WebDriverWait wait = new WebDriverWait(driver, 10);
driver.get("http://google.com");
driver.findElement(By.id("gbqfq")).sendKeys("testing");
WebElement element =
wait.until(ExpectedConditions.elementToBeClickable
(By.id("gbqfba")));
element.click();

}
}

25 Raj
S E L E N I U M W E B D R I V E R

This will wait for 10 seconds for timeout before title is updated with search term
If title is updated in specified time limit test will move to the text step instead of
waiting for 10 seconds

Note: The WebDriverWait object will call the ExpectedCondition class object every 500
milliseconds until it returns successfully.

PageLoadTimeout

Sets the amount of time to wait for a page load to complete before throwing an
error. If the timeout is negative, page loads can be indefinite.

driver.manage().timeouts().pageLoadTimeout(100, SECONDS);

SetScriptTimeout

Sets the amount of time to wait for an asynchronous script to finish execution
before throwing an error. If the timeout is negative, then the script will be allowed
to run indefinitely.

driver.manage().timeouts().setScriptTimeout(100,SECONDS);

Sleep Command

This is rarely used, as it always force the browser to wait for a specific time.
Thread.Sleep is never a good idea and that‟s why Selenium provides wait
primitives. If you use them you can specify much higher timeout value which
makes tests more reliable without slowing them down as the condition can be
evaluated as often as it‟s required.

thread.sleep(1000);

26 Raj
S E L E N I U M W E B D R I V E R

11
Topic

Switching Control between Windows

S ome web applications have many frames or multiple windows. Selenium


WebDriver assigns an alphanumeric id to each window as soon as the
WebDriver object is instantiated. This unique alphanumeric id is called
window handle. Selenium uses this unique id to switch control among several
windows. In simple terms, each unique window has a unique ID, so that Selenium
can differentiate when it is switching controls from one window to the other.

GetWindowHandle

To get the window handle of the current window.


String handle= driver.getWindowHandle();
//Return a string of alphanumeric window handle

GetWindowHandles
To get the window handle of all the current windows.
Set<String> handle= driver.getWindowHandles();
//Return a set of window handle

SwitchTo Window
WebDriver supports moving between named windows using the “switchTo”
method.
driver.switchTo().window("windowName");

SwitchTo pop-up window:


In Selenium WebDriver, testing pop-up windows involves identifying a pop-up
window, switching the driver context to the pop-up window, then executing steps
on the pop-up window, and finally switching back to the parent window. The
Selenium WebDriver allows us to identify a pop-up window by its name attribute
or window handle and switching between the pop-up window and the browser
window is done using the Webdriver.switchTo().window() method.

public class WindowPopUp {


@Test
public void testWindowPopUp() {
WebDriver driver = new FirefoxDriver();
driver.get("file:///C:/Sel/pop-up.html");
String parentWnd = driver.getWindowHandle();

27 Raj
S E L E N I U M W E B D R I V E R

WebElement help =
driver.findElement(By.id("helpbutton"));
help.click();

driver.switchTo().window("RegistrationWindow");
assertTrue(driver.getTitle().equals("Registration"));
driver.close();
driver.switchTo().window(parentWnd);
assertTrue(driver.getTitle().equals("Help"));
}
}

SwitchTo Alert PopUp

WebDriver supports moving between named PopUps using the “switchTo”


method. After you‟ve triggered an action that opens a popup, you can access the
alert and it will return the currently open alert object. With this object you can
now accept, dismiss, read its contents or even type into a prompt. This interface
works equally well on alerts, confirms, and prompts.

Alert alert = driver.switchTo().alert();

Web developers use JavaScript alerts for informing users about validation errors,
warnings, getting a response for an action, accepting an input value, and so on.
Tests will need to verify that the user is shown correct alerts while testing. It
would also be required to handle alerts while performing an end-to-end workflow.
The Selenium WebDriver provides an Alert class for working with JavaScript
alerts.

public class AlertTesting {


@Test
public void testAlert() {
WebDriver driver = new FirefoxDriver();
driver.get("file:///C:/Sel/Alert.html");
driver.findElement(By.xpath("html/body/button")).click();
Alert alert = driver.switchTo().alert();
String txt = alert.getText();
assertEquals("Hello! I am an alert box!", txt);
alert.accept();
}
}

28 Raj
S E L E N I U M W E B D R I V E R

SwitchTo Frame

WebDriver supports moving between named frames using the “switchTo”


method.

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

HTML frames allow developers to present documents in multiple views, which


may be independent windows or sub windows. Multiple views offer developers a
way to keep certain information visible, while other views are scrolled or replaced.
For example, within the same window, one frame might display a static banner,
the second a navigation menu, and the third the main document that can be
scrolled through or replaced by navigating in the second frame. A page with
frames is created by using the <frameset> tag or the <iframe> tag. All frame tags
are nested with a <frameset> tag.

public class FrameTesting {

@Test
public void testFrame(){
WebDriver driver = new FirefoxDriver();
driver.get("file:///C:/Sel/Frame.html");

driver.switchTo().frame("left");
WebElement leftObj =
diver.findElement(By.xpath("html/body/button"));
assertEquals("Alert",leftObj.getText());

driver.switchTo().defaultContent();

driver.switchTo().frame("right");
WebElement txt =
driver.findElement(By.name("textnames"));
txt.sendKeys("Raj");
driver.switchTo().defaultContent();
}
}

29 Raj
S E L E N I U M W E B D R I V E R

12
Topic

Handling Different WebElements


Textbox
Sending text to Textboxes can be done by using
SendKeys() method.

WebDriver driver = new FirefoxDriver();


driver.get("http://gmail.com);
driver.findElement(By.id(“Email”)).sendKeys(“x”);

Button
Clicking the button can be done by using Click()
method.

WebDriver driver = new FirefoxDriver();


driver.get("http://gmail.com);
driver.findElement(By.id(“signIn”)).click();

Checkbox
Selecting the checkbox can be done by using Click()
method.

WebDriver driver = new FirefoxDriver();


driver.get("http://gmail.com);
driver.findElement(By.id(“PersistentCookie”)).click();

Drop-Down List
WebDriver supports testing Dropdown and List
controls using a special Select class instead of the
WebElement class. The Select class provides various
methods and properties to interact with dropdowns.

public class CSS {

@Test
public void cssLoc(){

WebDriver driver = new FirefoxDriver();

30 Raj
S E L E N I U M W E B D R I V E R

driver.get("http://indianfrro.gov.in/frro/formc/acco
m_reg.jsp?t4g=LNO6328X");
Select dropdown = new
Select(driver.findElement(By.id("u_gender")));
dropdown.selectByVisibleText("Female");
}
}

Radio Button
Selenium WebDriver supports Radio Button and Radio
Group controls using the WebElement class. We can
select and deselect the radio buttons using the click()
method of the WebElement class and check whether a
radio button is selected or deselected using the isSelected() method.

public class Rdbtn {

@Test
public void testRdbtn() {

WebDriver driver = new FirefoxDriver();


driver.get("file:///C:/Sel/Registration.html");
WebElement rdb = driver.findElement(By
.xpath("html/body/form/table/tbody/tr[6]/td[2]/input
[1]"));
rdb.click();
System.out.println(rdb.isSelected());

}
}

Link
Selenium WebDriver supports Radio Button and Radio
Group controls using the

WebDriver driver = new FirefoxDriver();


driver.get("http://google.com);
driver.findElement(By. linkText(“Settings”)).click();

31 Raj
S E L E N I U M W E B D R I V E R

13
Topic

Advanced Concepts of WebDriver

T he Selenium Web Driver‟s Advanced User Interactions API allows us to


perform operations from keyboard events and simple mouse events to
complex events such as dragging-and-dropping, holding a key and then
performing mouse operations by using the Actions class, and building a complex
chain of events exactly like a user doing these manually. The Actions class
implements the builder pattern to create a composite action containing a group of
other actions.

@Test
public void testRowSelectionUsingControlKey() {
List<WebElement> tableRows =
driver.findElements(By.id("test"));
Actions builder = new Actions(driver);//instance of Action class
builder.click(tableRows.get(1)).keyDown(Keys.CONTROL)
//performing a click() on the first row, then holding the Ctrl key using
keyDown()
.click(tableRows.get(3)).keyUp(Keys.CONTROL)
//performing a click() on the end row, then holding the Ctrl key using keyUp()
.build().perform();
//performing a composite action by calling the perform() method

Double click
There will be elements in a web application that need double-click events fired for
performing some actions. For example, double-clicking on a row of a table will
launch a new window. The Advanced User Interaction API provides a method to
perform double-click.

WebElement message =
driver.findElement(By.id("message"));
Actions builder = new Actions(driver);
builder.doubleClick(message).build().perform();

Reading the Tool Tip


We can get the Tool Tip by using below script.
String tooltip =
driver.findElement(locator).getAttribute("title");

32 Raj
S E L E N I U M W E B D R I V E R

Drag-and-Drop
Selenium WebDriver implements Selenium RC's Drag-and-Drop command using
Actions class.

public class DrogNDrop {


@Test
public void testDrognDrop() {
WebDriver driver = new FirefoxDriver();
driver.get("http://www.stevefenton.co.uk/cmsfiles/assets/F
ile/mobiledragdrop.html");
WebElement srce = driver.findElement(By.id("drag1"));
WebElement dest = driver.findElement(By.id("drop1"));
Actions builder = new Actions(driver);
builder.dragAndDrop(srce, dest).perform();
}

Capturing Screenshot
Selenium WebDriver provides the Takes Screenshot interface for capturing a
screenshot of a web page.

@Test
public void testTakesScreenShot() {
try {
File scrFile = ((TakesScreenshot)
driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(scrFile, new
File("c:\\tmp\\main_page.png"));
} catch (Exception e) {
e.printStackTrace();
}
}

Scrolling the web page


We can scroll the web page using JavaScript in the java code.

public class Scroll {


@Test
public void testScroll() {
WebDriver driver = new FirefoxDriver();
driver.get("http://fb.com");
driver.manage().window().maximize();
((JavascriptExecutor)
driver).executeScript("window.scroll(0,250)", "");
}}

33 Raj
S E L E N I U M W E B D R I V E R

14
Topic

Handling Different Browsers

34 Raj
S E L E N I U M W E B D R I V E R

15
Topic

File Handling Using POI


import java.io.FileInputStream;
import java.io.IOException;

import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.testng.annotations.Test;

public class Read {

public XSSFWorkbook workbook;


public XSSFSheet sheet;
public XSSFCell cell;

@Test
public void excelRead() throws IOException{
FileInputStream fs = new FileInputStream("D:\\sample.xlsx");
workbook = new XSSFWorkbook(fs);
sheet = workbook.getSheet("Sheet1");
cell = sheet.getRow(0).getCell(0);
String data = cell.getStringCellValue();
System.out.println("Hello "+data);
}

35 Raj
S E L E N I U M W E B D R I V E R

36 Raj
S E L E N I U M W E B D R I V E R

16
Topic

Page Object Model

37 Raj
S E L E N I U M W E B D R I V E R

17
Topic

Log4j
Log4j is open source tool given by apache for
creating log files It help us to generate log file in
various output target. Log file is simple file which
keep track of the record or event or info when any
event happens or any software run. This whole
process is known as logging. We can create log file as
simple log file as well as HTML format. We can
create log file for our simple script also so we can track or debug our script easily
if anything goes wrong in script. With the help of Log4j it is possible to enable
loggings during the Selenium test case execution

Advantages are:
 Log4j allows you to have a very good logging infrastructure without
putting in any efforts.
 Log4j gives you the ability to categorize logs at different levels (Trace,
Debug, Info, Warn, Error and Fatal).
 Log4j gives you the ability to direct logs to different outputs. For e.g. to a
file, Console or a Database.
 Log4j gives you the ability to define the format of output logs.
 Log4j gives you the ability to write Asynchronous logs which helps to
increase the performance of the application.
 Loggers in Log4j follow a class hierarchy which may come handy to your
applications.

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

38 Raj
S E L E N I U M W E B D R I V E R

Step 1: Download log4j JAR file from https://logging.apache.org/log4j/1.2/


download.html and download the Zipped format of the JAR file.

Step 2: Create 'New Java Project' by navigating to File Menu.

39 Raj
S E L E N I U M W E B D R I V E R

Step 3: Enter the name of the project as 'log4j_demo' and click 'Next'

Step 4: Click Add External Jar and add 'Log4j-1.2.17.jar'

40 Raj
S E L E N I U M W E B D R I V E R

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 Libs
folder.

41 Raj
S E L E N I U M W E B D R I V E R

Step 7: Add a New XML file using which we can specify the Log4j Properties.

Step 8: Enter the Log file name as 'Log4j.xml'.

42 Raj
S E L E N I U M W E B D R I V E R

Step 9: Final folder structure is shown below.

Step 10: Now add the properties of Log4j which would be picked up during
execution.
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/"
debug="false">
<appender name="fileAppender"
class="org.apache.log4j.FileAppender">
<param name="Threshold" value="INFO" />
<param name="File" value="percent_calculator.log"/>
<layout
class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern"
value="%d{yyyy-MM-dd HH:mm:ss} [%c] (%t:%x) %m%n" />
</layout>
</appender>
<root>
<level value="INFO"/>
<appender-ref ref="fileAppender"/>
</root>
</log4j:configuration>

Step 11: Now for demo purpose, we will incorporate log4j in the same test that we
have been performing (percent calculator). Add a class files with 'Main' function
package log4j_demo;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.apache.log4j.xml.DOMConfigurator;

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

public class log4j_demo


{
static final Logger logger = LogManager.getLogger(log4j_demo.class.getName());
public static void main(String[] args)
{
DOMConfigurator.configure("log4j.xml");
logger.info("# ## # # # # # # # # # # # # # # # # # # # # # # # ");
logger.info("TEST Has Started");

WebDriver driver = new FirefoxDriver();

//Puts a Implicit wait, Will wait for 10 seconds before throwing exception

43 Raj
S E L E N I U M W E B D R I V E R

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

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

//Maximize the browser


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

// Click on Math Calculators


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

// Click on Percent Calculators


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

// Enter value 10 in the first number of the percent Calculator


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

// Enter value 50 in the second number of the percent Calculator


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

// Click Calculate Button


driver.findElement(By.id("content")).click();
logger.info("Click Calculate Button");

// Get the Result Text based on its xpath


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

//Print a Log In message to the screen


logger.info(" The Result is " + result);

if(result.equals("5"))
{
logger.info("The Result is Pass");

}
else
{
logger.error("TEST FAILED. NEEDS INVESTIGATION");

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

//Close the Browser.


driver.close();
}
}

Execution

44 Raj
S E L E N I U M W E B D R I V E R

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.

The content of the log file is shown below.

45 Raj
S E L E N I U M W E B D R I V E R

18
Topic

Selenium Grid

S 
elenium Grid is a solution enabling web-testing on a larger scale and continu
-ous integration Selenium RC gives a lot of possibilities but:

Selenium RC struggles when running concurrent tests


 It is slow
 How would you simultaneously tests across different OS and browsers?

So that Selenium Grid comes into picture. Selenium Grid is a utility that
distributes the tests across multiple physical or virtual machines so that we can
execute script in parallel (simultaneously) that results in cutting down the time
required for running tests. Selenium Grid is a testing infrastructure with several
different platforms (such as Windows, Mac, Linux, and so on) for your tests to
execute, and these platforms are managed from a central point. The central point
known as hub, has the information of all the different testing platforms known as
nodes, and assigns these nodes to execute tests whenever the test scripts request
them. The following diagram shows what a Selenium Grid looks like:

46 Raj
S E L E N I U M W E B D R I V E R

In the preceding diagram, there is one hub, four nodes of different platforms, and
the machine where your test scripts are located. The test script will communicate
with the hub and request for a target platform to be executed. The hub assigns a
node with the target platform to the test script. The node executes the test script
and sends the result back to the hub, which in turn forwards the results to the test
script. This is what Selenium Grid looks like and how works at a high level.

Hub

The hub is the central point of a Selenium Grid. It has a registry of all the available
nodes that are part of a particular grid. The hub is again a Selenium server running
in the hub mode listening on port 4444 of a machine by default. The test scripts
will try to connect to the hub on this port, just as any Remote WebDriver. The
hub will take care of rerouting the test script traffic to the appropriate test
platform node. Let us see how we can start a hub node. Navigate to the location
where you have your Selenium server jar file and execute the following command:

java -jar selenium-server-standalone-2.43.1.jar -role hub

Doing this will start your server in the hub mode. By default, the server starts
listening on port 4444

Node

Nodes are the Selenium instances that are attached to the Hub which will 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.

java -jar selenium-server-standalone-2.43.1.jar -role node –hub


http://localhost:4444/grid/register

This will start the Selenium server in the node mode and register this node with
the already started hub.

Working with Grid

In order to work with the Grid, we need to ensure that we follow certain protocol.
Below are the major steps gets involved.

47 Raj
S E L E N I U M W E B D R I V E R

Configuring Hub

Step 1 : Download the latest Selenium Server standalone JAR file from
http://docs.seleniumhq.org/download/

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.
java -jar selenium-server-standalone-2.25.0.jar -port 4444 -role
hub -nodeTimeout 1000

Step 3: Now open the browser and navigate to the URL http//localhost:4444
from Hub

Step 4: Now click on 'console' link and click 'view config'. The config of hub
would be shown. As of now we haven't got any nodes, hence we will not be able
to see the details.

48 Raj
S E L E N I U M W E B D R I V E R

Configuring Nodes

Step 1: Logon to node (where you would like to execute the scripts) and place the
'selenium-server-standalone-2.42.2' in a folder. We need to point to the selenium-
server-standalone JAR when launching the nodes.

Step 2: Register the node to the hub using the below command.
java -jar selenium-server-standalone-2.43.1.jar -role node -hub
http://localhost:4444/grid/register -browser browserName=firefox -port 5555

Step 3: After executing the command, now come back to Hub. Navigate to the
URL - http://localhost:4444 and the Hub would now display the node
attached to it.

Step 4: Now let us Launch Internet Explorer Node. For Launching the IE Node,
we need to ensure that we have Internet Explorer driver downloaded on the node
machine.

Step 5: To Download the Internet Explorer Driver, navigate to


http://docs.seleniumhq.org/

Step 6: Launch IE using the below command.

49 Raj
S E L E N I U M W E B D R I V E R

C:\>java -Dwebdriver.ie.driver=C:\IEDriverServer.exe -jar


C:\selenium-server-standalone-2.42.2.jar -role webdriver -hub
http://localhost:4444/grid/register -browser browserName=ie,
platform=WINDOWS -port 5558

Step 7: After executing the command, now come back to Hub. Navigate to the
URL - http://localhost:4444 and the Hub would now display the IE node
attached to it.

Step 8: Now let us Launch Chrome Node. For Launching the Chrome Node, we
need to ensure that we have Chrome driver downloaded on the node machine.

Step 9: To Download the Chrome Driver, navigate to


http://docs.seleniumhq.org/download/

Step 10: Launch chrome using the below command.


java -Dwebdriver.chrome.driver=C:\chromedriver.exe -jar
C:\selenium-server-standalone-2.42.2.jar -role webdriver -
hub http://localhost:4444/grid/register -browser
browserName=chrome,platform=WINDOWS -port 5557

Step 11: After executing the command, now come back to Hub. Navigate to the
URL - http://localhost:4444 and the Hub would now display the chrome node
attached to it.

Develop Script

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;

public class TestNGClass {


public WebDriver driver;
public String URL, Node;

50 Raj
S E L E N I U M W E B D R I V E R

protected ThreadLocal<RemoteWebDriver> threadDriver =


null;

@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://localhost:5555/wd/hub";
DesiredCapabilities cap = DesiredCapabilities.firefox();
cap.setBrowserName("firefox");

driver = new RemoteWebDriver(new URL(Node), cap);


// Puts a Implicit wait, Will wait for 10 seconds before
throwing exception
driver.manage().timeouts().implicitlyWait(10,
TimeUnit.SECONDS);

// 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://localhost: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();
cap.setBrowserName("ie");
String Node = "http://localhost:5558/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 {
throw new IllegalArgumentException("The Browser Type is
Undefined");

51 Raj
S E L E N I U M W E B D R I V E R

}
}

@Test
public void calculatepercent() {
driver.findElement(By.xpath(".//*[@id='menu']/div[3]/a")).click(
); // Click on Math Calculators
driver.findElement(By.xpath(".//*[@id='menu']/div[4]/div[3]/a"))
.click(); // Click on Percent Calc
driver.findElement(By.id("cpar1")).sendKeys("10"); // Enter
value 10 in the first number of the %
driver.findElement(By.id("cpar2")).sendKeys("50"); // Enter
value 50 in the second number %
driver.findElement(By.xpath(".//*[@id='content']/table/tbody/tr/
td[2]/input")).click(); // Click
String result =
driver.findElement(By.xpath(".//*[@id='content']/p[2]/span/font/
b")).getText();

// get result
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();
}
}

Testing.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="Suite" parallel="tests">
<test name="FirefoxTest">
<parameter name="browser" value="firefox" />
<classes>
<class name="TestNG.TestNGClass" />
</classes>
</test>

<test name="ChromeTest">
<parameter name="browser" value="chrome" />
<classes>
<class name="TestNG.TestNGClass" />
</classes>

52 Raj
S E L E N I U M W E B D R I V E R

</test>

<test name="IETest">
<parameter name="browser" value="ie" />
<classes>
<class name="TestNG.TestNGClass" />
</classes>
</test>
</suite>

Test Execution

Result Analysis

53 Raj
S E L E N I U M W E B D R I V E R

19
Topic

Selenium Remote Control

S elenium-RC stands for Selenium Remote Control (known as Selenium 1.0),


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 has 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 like reading and writing
files, querying a database, emailing test results.

While Selenium IDE may seem a productive and efficient tool for writing test-cases, it lacks
many essential features of a testing tool:

Conditional statements, Loops, Logging, Exception handling, Reporting, Test fixtures and
data-driven tests, Test dependencies and Taking screenshots

Selenium RC is the answer to a more powerful test-suite for your applications. It


follows a client/server model allowing client libraries to execute tests on a browser
controlled by the server.

54 Raj
S E L E N I U M W E B D R I V E R

How Selenium remote control does internally Selenium RC stands for Selenium
works? Remote Control aka Selenium 1.0.
Selenium RC launches the browser with itself as the proxy Selenium RC works in such as way
server (hence you may get certificate warning in some that the client libraries communicate
modes) and then it injects JavaScript - to play the test.
This also means it can easily work in ALL
with the Selenium RC Server passing
browsers/platform - and it can be easily used to test each Selenium command for
AJAX (unlike professional tools). 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.

Selenium RC comes in two parts

 The Selenium Server launches and kills browsers in addition to that it


interprets and executes the Selenese commands. It also acts as an HTTP
proxy by intercepting and verifying HTTP messages passed between the
browser and the application under test.
 Client libraries that provide interface between each one of the
programming language (java, C#, perl, python and php) and the Selenium-
RC Server.

Selenium Server

 Selenium server is the program that drives the browser


 It embeds Selenium Core framework and injects it into the browser
 It communicates with the running test client and drives the browser
 Client tests sends commands that the server interprets in order to drive the
browser
 The server sends back results to the client
 Client and server communicates via HTTP GETs and POSTs so you can
easily plug into
 Server is configurable at startup via command-line options.
java -jar selenium-server.jar

import com.thoughtworks.selenium.*;
public class rcDemo {

55 Raj
S E L E N I U M W E B D R I V E R

public static void main(String[] args) throws


InterruptedException {

// Instatiate the RC Server


Selenium selenium = new DefaultSelenium("localhost", 4444,
"firefox", "http://www.calculator.net");
selenium.start(); // Start
selenium.open("/"); // Open the URL
selenium.windowMaximize();

// Click on Link Math Calculator


selenium.click("xpath=.//*[@id='menu']/div[3]/a");
Thread.sleep(2500); // Wait for page load

// Click on Link Percent Calculator

selenium.click("xpath=.//*[@id='menu']/div[4]/div[3]/a");
Thread.sleep(4000); // Wait for page load

// Focus on text Box


selenium.focus("name=cpar1");
// enter a value in Text box 1
selenium.type("css=input[name=\"cpar1\"]", "10");

// enter a value in Text box 2


selenium.focus("name=cpar2");
selenium.type("css=input[name=\"cpar2\"]", "50");

// Click Calculate button

selenium.click("xpath=.//*[@id='content']/table/tbody/tr/t
d[2]/input");

// verify if the result is 5


String result =
selenium.getText(".//*[@id='content']/p[2]");

if (result == "5") {
System.out.println("Pass");
} else {
System.out.println("Fail");
}
}
}

56 Raj
S E L E N I U M W E B D R I V E R

RC - Scripting
Step 1: Start the Selenium Remote Control (with the help of command prompt) as
explained in environmental setup chapter.
Step 2: After launching Selenium RC, open eclipse and create "New Project" as
shown below.

Step 3: Enter the project name and click 'Next' button.

57 Raj
S E L E N I U M W E B D R I V E R

Step 4: Verify the source, Projects, Libraries and Output folder and click 'Finish'.

Step 4: Right click on 'project' container and choose 'Configure Build Path'.

58 Raj
S E L E N I U M W E B D R I V E R

Step 5: Properties for 'selrcdemo' opens up. Navigate to 'Libaries' tab and select
'Add External JARs'. Choose the Selenium RC jar file that we have downloaded
and it would appear as shown below.

Step 6: The referenced Libraries are shown as displayed below.

59 Raj
S E L E N I U M W E B D R I V E R

Step 7: Create a new class file by performing a right click on 'src' folder and select
'New' >> 'class'.

Step 8: Enter a name of the class file and enable 'public static void main' as shown
below.

60 Raj
S E L E N I U M W E B D R I V E R

Step 9: The Created Class is created under the folder structure as shown below.

Step 10: Now it is time for coding. The below code has comments embedded to
make the readers understand what has been put forth.

package selrcdemo;
import com.thoughtworks.selenium.DefaultSelenium;
import com.thoughtworks.selenium.Selenium;

public class rcdemo


{
public static void main(String[] args) throws
InterruptedException

61 Raj
S E L E N I U M W E B D R I V E R

//Instatiate the RC Server


Selenium selenium = new DefaultSelenium("localhost", 4444 ,
"firefox", "http://www.calculator.net");
selenium.start(); // Start
selenium.open("/"); // Open the URL
selenium.windowMaximize();

// Click on Link Math Calculator


selenium.click("xpath=.//*[@id='menu']/div[3]/a");
Thread.sleep(2500); // Wait for page load

// Click on Link Percent Calculator


selenium.click("xpath=.//*[@id='menu']/div[4]/div[3]/a");
Thread.sleep(4000); // Wait for page load

// Focus on text Box


selenium.focus("name=cpar1");
// enter a value in Text box 1
selenium.type("css=input[name=\"cpar1\"]", "10");

// enter a value in Text box 2


selenium.focus("name=cpar2");
selenium.type("css=input[name=\"cpar2\"]", "50");

// Click Calculate button


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

// verify if the result is 5


String result = selenium.getText(".//*[@id='content']/p[2]");

if (result == "5")
{
System.out.println("Pass");
}else
{
System.out.println("Fail");
}

Step 11: Now, let us execute the script by clicking 'Run' Button.

Step 12: The script would start executing and user would be able to see the
command history under 'Command History' Tab.

62 Raj
S E L E N I U M W E B D R I V E R

Step 13: The final state of the application is shown as below. The percentage is
calculated and it displayed the result on 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 a
HTML file or in a simple Text file.

63 Raj
S E L E N I U M W E B D R I V E R

20
Topic

Selenium IDE

64 Raj
S E L E N I U M W E B D R I V E R

21
Topic

JUnit
What is JUnit?

J Unit is a simple framework to write repeatable tests. It is an instance of the


xUnit architecture for unit testing frameworks. It was originally written by
Erich Gamma and Kent Beck.

JUnit features include:

 JUnit is an open source framework which is used for writing & running
tests.
 Provides Annotation to identify the test methods.
 Provides Assertions for testing expected results.
 Provides Test runners for running tests.

65 Raj
S E L E N I U M W E B D R I V E R

 JUnit tests can be run automatically and they check their own results and
provide immediate feedback. There's no need to manually comb through a
report of test results.
 JUnit tests can be organized into test suites containing test cases and even
other test suites.
 JUnit shows test progress in a bar that is green if test is going fine and it
turns red when a test fails.

Configuring JUnit in Eclipse

Method 1:

Step 1: Open eclipse -> right click on project and click on property > Build Path
> Configure Build Path and add the junit-4.10.jar in the libraries using Add
Library button.

66 Raj
S E L E N I U M W E B D R I V E R

Method 2:

Step 1: Download latest JUnit version.

Step 2: Open eclipse -> right click on project and click on property > Build Path
> Configure Build Path and add the junit-4.10.jar in the libraries using Add
External Jar button.

JUnit Annotations Used in Selenium scripts

Annotations are like meta-tags that you can add to your code and apply them to
methods or in class. These annotations in JUnit gives us information about test
methods, which methods are going to run before & after test methods, which
methods run before & after all the methods, which methods or class will be ignore
during execution.

67 Raj
S E L E N I U M W E B D R I V E R

 @Test
The Test annotation tells JUnit that the public void method to which it is
attached can be run as a test case.

 @Before
This annotation tells that method to be run before each Test method.

 @After
This annotation tells that method to be run after each Test method.

 @BeforeClass
Annotating a public static void method with @BeforeClass causes it to be
run once before any of the test methods in the class.

 @AfterClass
This will perform the method after all tests have finished. This can be used
to perform clean-up activities.

 @Ignore
The Ignore annotation is used to ignore the test and that test will not be
executed.

Assertions

 assertEquals(boolean expected, boolean actual)


Check that two primitives/Objects are equal

 assertTrue(boolean expected, boolean actual)


Check that a condition is true

 assertFalse(boolean condition)
Check that a condition is false

 assertNotNull(Object object)
Check that an object isn't null.

68 Raj
S E L E N I U M W E B D R I V E R

 assertNull(Object object)
Check that an object is null

 assertSame(boolean condition)
The assertSame() methods tests if two object references point to the same
object

 assertNotSame(boolean condition)
The assertNotSame() methods tests if two object references not point to
the same object

 assertArrayEquals(expectedArray, resultArray);
The assertArrayEquals() method will test whether two arrays are equal to
each other.

Reporting Errors

The ErrorCollector Rule allows execution of a test to continue after the first
problem is found and report them all at once.

import org.junit.Assert;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ErrorCollector;

public class ErrorCollectorTest {

@Rule
public ErrorCollector errCol = new ErrorCollector();

@Test
public void testErrorColl() {
System.out.println("open browser and go to URL");
System.out.println("click on link");
System.out.println("click on one Login link");

String actual = "actual";


String expected = "Expected";

System.out.println("before Assert.assertEquals(expected,
actual)");

try {
Assert.assertEquals(expected, actual);
} catch (Throwable e) {
System.out.println("Report Error" + e);

69 Raj
S E L E N I U M W E B D R I V E R

errCol.addError(e);
}

System.out.println("After Assert.assertEquals(expected,
actual)");
}
}

Parameterization
Parameterized class is used to run same scenario with multiple dataset. Below is
the example to pass multiple parameters in a Junit test.

@Parameters annotation tag is used to pass multiple data. Here, we have taken
2*2 dimensional array and the data can be visualized like below:

import java.util.Arrays;
import java.util.Collection;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;

//step 1
@RunWith(Parameterized.class)
public class SampleJunit {
// step 2
int a;
int b;
// step 3
public SampleJunit(int a, int b) {

this.a = a;
this.b = b;
}

@Test
public void sampleTest() {
System.out.println(a + " " + b);
}

// step 4
@Parameters
public static Collection<Object[]> getData() {

70 Raj
S E L E N I U M W E B D R I V E R

Object data[][] = new Object[2][2];


data[0][0] = 10;
data[0][1] = 20;

data[1][0] = 30;
data[1][1] = 40;
return Arrays.asList(data);

}
}

Runner (Suite) Class


Using runner class selenium test cases can be executed by specifying the class
names.

import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import org.junit.runners.Suite.SuiteClasses;

@RunWith(Suite.class)
@SuiteClasses({ SampleJunit.class })
public class MyRunner {

71 Raj
S E L E N I U M W E B D R I V E R

22
Topic

Maven
Before getting started with Maven, ensure you have the following installed in your
machine.
 JDK is installed
 JAVA_HOME is correctly defined
 Maven is installed
 JAVA_HOME/bin is added to PATH
 maven_install_folder/bin is added to PATH

Maven is a build automation tool which is distributed under Apache software


foundation. It is mainly used for java projects.

What is build tool?


Build tool is used to setup everything which is required to run your java code
independently. This can be applied to your entire java project. It generates source
code, compiling code, packaging code to a jar etc. Maven provides a common
platform to perform these activities which makes programmer‟s life easier while
handling huge project.

Maven provides pom.xml which is the core to any project. This is the
configuration file where all required information‟s are kept. Many of the IDEs
(Integrated Development Environments) are available which makes it easy to use.
IDEs are available for tools like Eclipse , NetBeans, IntelliJ etc.

<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>sample</groupId>
<artifactId>sample</artifactId>
<version>0.0.1-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>2.44</version>
</dependency>

72 Raj
S E L E N I U M W E B D R I V E R

</dependencies>
</project>

General Phrases used in Maven

groupId: Generally groupId refers to domain id. For best practices company
name is used as groupId. It identifies the project uniquely.

artifactId: It is basically the name of the Jar without version.

version: This tag is used to create a version of the project.

Configuring Eclipse and Maven for WebDriver

Along with Eclipse, Apache Maven provides support for managing the
entire lifecycle of a test project. Maven is used to define project structure,
dependencies, build, and test management. You can use Eclipse and Maven for
building your Selenium WebDriver test framework from a single window. Another
important benefit of using Maven is that you can get all the Selenium library files
and their dependencies by configuring the pom.xml file. Maven automatically
downloads the necessary files from the repository while building the project.

1) Launch the Eclipse IDE.


2) Create a new project by selecting File  New  Other from Eclipse Main
Menu.
3) On the New dialog, select Maven  Maven Project.
4) Next, the New Maven Project dialog will be displayed. Select the Create a
simple project (skip archetype selection) checkbox and set everything to default
and click on the Next button.
5) On the New Maven Project dialog box, enter SeleniumClass in Group Id: and
Artifact Id: textboxes. You can also add a name and description. Set everything
to default and click on the Finish.
6) Eclipse will create the SeleniumClass project with a structure.
7) Right-click on JRE System Library [J2SE-1.5] and select the Properties option
from the menu.
8) On the Properties for JRE System Library [J2SE-1.5] dialog box, make sure
Workspace default JRE (jre6) is selected. If this option is not selected by
default, select this option.
9) Select pom.xml from Package Explorer. This will open the pom.xml file in the
editor area with the Overview tab open. Select the pom.xml tab instead.

73 Raj
S E L E N I U M W E B D R I V E R

10) Add the WebDriver and JUnit dependencies highlighted in the following code
snippet, to pom.xml in the <project> node:
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>Selenium</groupId>
<artifactId>Selenium</artifactId>
<version>0.0.1-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>2.44</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.8.1</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>
11) Select src/test/java in Package Explorer and right-click for the menu. Select
New | Class
12) Enter the class name and click on the Finish button.
13) To run the tests in the Maven lifecycle, select the project in Package Explorer.
Right-click on the project name and select Run As |Maven test.

74 Raj
S E L E N I U M W E B D R I V E R

23
Topic

Automation Framework

A framework is considered to be a combination of set protocols, rules,


standards and guidelines that can be incorporated or followed as a whole so
as to leverage the benefits of the scaffolding provided by the Framework.

Advantage of Test Automation framework

 Reusability of code
 Maximum coverage
 Recovery scenario
 Low cost maintenance
 Minimal manual intervention
 Easy Reporting

Types of Test Automation Frameworks

Data Driven Testing Framework


While automating or testing any application, at times it may be required to
test the same functionality multiple times with the different set of input data.
Thus, in such cases, we can‟t let the test data embedded in the test script. Hence it
is advised to retain test data into some external (like Excel, Notepad.. etc.,) data
base outside the test scripts. Data Driven Testing Framework helps the user
segregate the test script logic and the test data from each other. It lets the user
store the test data into an external file. The external databases can be property
files, xml files, excel files, text files, CSV files, ODBC repositories etc. The data is
conventionally stored in “Key-Value” pairs. Thus, the key can be used to access
and populate the data within the test scripts.

Keyword Driven Testing Framework


The Keyword driven testing framework is an extension to Data driven
Testing Framework in a sense that it not only segregates the test data from the
scripts, it also keeps the certain set of code belonging to the test script into an
external data file.

75 Raj
S E L E N I U M W E B D R I V E R

These set of code are known as Keywords and hence the framework is so named.
Key words are self-guiding as to what actions needs to be performed on the
application.
The keywords and the test data are stored in a tabular like structure and thus it is
also popularly regarded as Table driven Framework. Take a notice that keywords
and test data are entities independent of the automation tool being used.

Example Test case of Keyword Driven Testing Framework

In the above example keywords like login, clickLink and verifyLink are defined
within the code. Depending upon the nature of application keywords can be
derived. And all the keywords can be reused multiple times in a single test case.
Locator column contains the locator value that is used to identify the web
elements on the screen or the test data that needs to be supplied.

All the required keywords are designed and placed in base code of the framework.

Hybrid Driven Framework


As the name suggests, the Hybrid Testing Framework is a combination of
more than one above mentioned frameworks. The best thing about such a setup is
that it leverages the benefits of all kinds of associated frameworks.

76 Raj
S E L E N I U M W E B D R I V E R

Example of Hybrid Driven Testing Framework

The sheet would contain the both keywords and data.

In the above example, keyword column contains all the required keywords used in the
particular test case and data column drives all the data required in the test scenario. If
any step does not need any input then it can be left empty.

77 Raj
S E L E N I U M W E B D R I V E R

24
Topic

Java
J AVA is a distributed technology developed by James Gosling, Patric Naugton,
etc., at Sun Micro System has released lot of rules for JAVA and those rules are
implemented by JavaSoft Inc, USA (which is the software division of Sun
Micro System) in the year 1990. The original name of JAVA is OAK (which is a
tree name). In the year 1995, OAK was revised
and developed software called JAVA (which is a
coffee seed name). JAVA released to the market
in three categories J2SE (JAVA 2 Standard
Edition), J2EE (JAVA 2 Enterprise Edition) and
J2ME (JAVA 2 Micro/Mobile Edition). i. J2SE
is basically used for developing client side
applications/programs. ii. J2EE is used for
developing server side applications/programs. iii. J2ME is used for developing
server side applications/programs. If you exchange the data between client and
server programs (J2SE and J2EE), by default JAVA is having on internal support
with a protocol called http. J2ME is used for developing mobile applications and
lower/system level applications. To develop J2ME applications we must use a
protocol called WAP (Wireless Applications Protocol).

What is Java?

Java is a programming language and platform. Platform any hardware or software


environment in which a program runs known as platform. Since java has its own
Runtime Environment (JRE) and API, it is called as platform.

Features of Java

There is given many features of java. They are also known as java buzzwords. The
Java Features given below are simple and easy to understand.

 Object-Oriented
 Platform independent
 Secured
 Robust
 Portable

78 Raj
S E L E N I U M W E B D R I V E R

 Interpreted
 High Performance
 Multithreaded
 Distributed

Sample Program

public class SampleProgram {

public static void main(String[] args) {


System.out.println("Hello world");
}
}

Output: Hello world

Understanding first java program

 class keyword is used to declare a class in java.


 public keyword is an access modifier which represents visibility, it means
it is visible to all.
 static is a keyword, if we declare any method as static, it is known as static
method. The core advantage of static method is that there is no need to
create object to invoke the static method. The main method is executed by
the JVM, so it doesn't require creating object to invoke the main method.
 void is the return type of the method, it means it doesn't return any value.
 main represents startup of the program.
 String[] args is used for command line argument.
 System.out.println() is used print statement.

Pre-requisites: For developing any java program, you need to


 Install the JDK if you don't have installed it
 Set path of the JDK/bin directory.

Variable
Variable is a name of memory location. (OR) A variable is an identifier
whose value will be changed during execution of the program.

79 Raj
S E L E N I U M W E B D R I V E R

Types of Variable

There are three types of variables in java


 local variable
A variable that is declared inside the method is called local variable.
 instance variable
A variable that is declared inside the class but outside the method is called
instance variable. It is not declared as static.
 static variable
A variable that is declared as static is called static variable. It cannot be
local.

class A {
int data = 50;// instance variable
static int m = 100;// static variable

void method() {
int n = 90;// local variable
}
}

Constant
Constant is an identifier whose value cannot be changed during execution of
the program.
 In JAVA to make the identifiers are as constants, we use a keyword called
final.
 Final is a keyword which is playing an important role in three levels. They
are at variable level, at method level and at class level.
 When we don‟t want to change the value of the variable, then that variable
must be declared as final.
 When the final variable is initialized, no more modifications or
assignments are possible
Example:
final int a =10; //valid
final int b;
b=20; //invalid

80 Raj
S E L E N I U M W E B D R I V E R

Datatypes

There are two types of datatypes in java, primitive and non-primitive.

Object Oriented Programming concepts: (OOPs)

Object means a real word entity such as pen, chair, table etc. Object-Oriented
Programming is a methodology or paradigm to design a program using classes and
objects. It simplifies the software development and maintenance by providing
some concepts:
 Object
 Class
 Inheritance
 Polymorphism
 Abstraction
 Encapsulation

81 Raj
S E L E N I U M W E B D R I V E R

Object based programming language:


Object based programming language follows all the features of OOPs except Inheritance.
JavaScript and VBScript are examples of object based programming languages.

Class and Object:

Class: Class is a way of binding the data and associated methods in a single unit.

Object: Object is an instance of a class where as Class is a template or blueprint


from which objects are created. So object is the instance (result) of a class.

An object has three characteristics:


 state: represents data (value) of an object.
 behavior: represents the behavior (functionality) of an object such as
deposit, withdraw etc.
 identity: Object identity is typically implemented via a unique ID. The
value of the ID is not visible to the external user. But, it is used internally
by the JVM to identify each object uniquely.
For Example: Pen is an object. Its name is Reynolds, color is white etc. known as
its state. It is used to write, so writing is its behavior.

class Room {
int l;// data member (also instance variable)
int w;// data member (also instance variable)

public static void main(String args[]) {


Room rm1 = new Room();// creating an object of Room
System.out.println(rm1.l);
System.out.println(rm1.w);

Room rm2 = new Room();// creating an object of Room


System.out.println(rm2.l);
System.out.println(rm2.w);

}
}

new

82 Raj
S E L E N I U M W E B D R I V E R

The new keyword is used to allocate memory at runtime. This new operator is
known as dynamic memory allocation operator.
Object gets the memory in Heap area and reference variable refers to the
object allocated in the Heap memory area. Here, s1 and s2 both are reference
variables that refer to the objects allocated in memory. Method gets the memory in
Stack. All constants of JAVA program available in associative memory.

Anonymous object

Anonymous simply means nameless. An object that has no reference is


known as anonymous object.
If you have to use an object only once, anonymous object is a good approach.

class Calculation {

void fact(int n) {
int fact = 1;
for (int i = 1; i <= n; i++) {
fact = fact * i;
}
System.out.println("factorial is " + fact);
}

public static void main(String args[]) {


new Calculation().fact(5);
// calling method with annonymous object
}
}

Creating multiple objects by one type only

We can create multiple objects by one type only as we do in case of primitives.

Rectangle r1=new Rectangle(),r2=new Rectangle();//creating two objects

Method overloading

If a class has multiple methods by same name but different parameters, it


is known as Method Overloading. Method overloading increases the readability of
the program.

83 Raj
S E L E N I U M W E B D R I V E R

There are two ways to overload the method in java


 By changing number of arguments
 By changing the data type

Example 1:

class Calc {
void sum(int a, int b) {
System.out.println(a + b);
}

void sum(int a, int b, int c) {


System.out.println(a + b + c);
}

public static void main(String args[]) {


Calc cc = new Calc();
cc.sum(10, 10);
cc.sum(10, 20, 30);
}
}

Example 2:

class Room {
void area(int l, int b) {
System.out.println(l * b);
}

void area(double l, double b) {


System.out.println(l * b);
}

public static void main(String args[]) {


Room rm = new Room();
rm.area(20, 20);
rm.area(10.5, 10.5);
}
}

Constructor

84 Raj
S E L E N I U M W E B D R I V E R

A constructor is a special member method which will be called by the JVM


implicitly (automatically) for placing user/programmer defined values instead of
placing default values. Constructors are meant for initializing the object.

Rules for creating constructor:

There are basically two rules defined for the constructor.

 Constructor name must be same as its class name


 Constructor must have no explicit return type
 Constructors should not be static since constructors will be called each
and every time whenever an object is creating.
 Constructor should not be private provided an object of one class is
created in another class (constructor can be private provided an object of
one class created in the same class).
 Constructors will not be inherited at all.
 Constructors are called automatically whenever an object is creating.

Types of constructors

There are two types of constructors:

 default constructor is one which will not take any parameters (no-arg
constructor)
 parameterized constructor

Example 1:

A constructor that has no parameter is known as default constructor.


In this example, we are creating the no-arg constructor in the Bike class. It will be
invoked at the time of object creation.

class Bike {
Bike() {
System.out.println("Bike is created");
}
public static void main(String args[]) {
Bike b = new Bike();
}
}

85 Raj
S E L E N I U M W E B D R I V E R

If there is no constructor in a class, compiler automatically creates a default constructor.

Example 2:
class Bike {

Bike(String name) {
System.out.println("Bike is created name is :" + name);
}
public static void main(String args[]) {
Bike b = new Bike("Honda");
}
}

Static block

The static keyword is used in java mainly for memory management. We


may apply static keyword with variables, methods, blocks and nested class. The
static keyword belongs to the class than instance of the class.
The static can be:

 variable (also known as class variable)


 method (also known as class method)
 block
 nested class

Inheritance

Inheritance in java is a mechanism in which one object acquires all the


properties and behaviors of parent object. The idea behind inheritance in java is
that you can create new classes that are built upon existing classes. When you
inherit from an existing class, you can reuse methods and fields of parent class,
and you can add new methods and fields also. Inheritance represents the IS-A
relationship, also known as Parent-Child relationship.

class Superclass-name{
//methods and fields
}
class Subclass-name extends Superclass-name{
//methods and fields
}

86 Raj
S E L E N I U M W E B D R I V E R

The keyword extends indicates that you are making a new class that derives from
an existing class.
In the terminology of Java, a class that is inherited is called a super class. The new
class is called a subclass.

class Employee1 {
float salary = 40000;
}
class Programmer extends Employee1 {
int bonus = 10000;
public static void main(String args[]) {
Programmer p = new Programmer ();
System.out.println("Programmer salary is:" +
p.salary);
System.out.println("Bonus of Programmer is:" +
p.bonus);
}
}

Method overriding

If subclass (child class) has the same method as declared in the parent
class, it is known as method overriding. In other words, If subclass provides the
specific implementation of the method that has been provided by one of its parent
class, it is known as Method Overriding.

Advantage of Java Method Overriding:


 Method Overriding is used to provide specific implementation of a
method that is already provided by its super class.
 Method Overriding is used for Runtime Polymorphism

Rules for Method Overriding:


 method must have same name as in the parent class
 method must have same parameter as in the parent class.
 must be IS-A relationship (inheritance).

class Bank {
int getRateOfInterest() {
return 0;
}
}
class SBI extends Bank {
int getRateOfInterest() {
return 7;
}

87 Raj
S E L E N I U M W E B D R I V E R

}
class ICICI extends Bank {
int getRateOfInterest() {
return 8;
}
}
class Customer {
public static void main(String args[]) {
SBI s = new SBI();
ICICI i = new ICICI();
System.out.println("SBI Rate of Interest: " +
s.getRateOfInterest());
System.out.println("ICICI Rate of Interest: " +
i.getRateOfInterest());
}
}

Static method cannot be overridden because static method is bound with class whereas instance
method is bound with object. Static belongs to class area and instance belongs to heap area.

Super
The super is a reference variable that is used to refer immediate parent
class object. Whenever you create the instance of subclass, an instance of parent
class is created implicitly i.e. referred by super reference variable.

Usage of super Keyword:


 super is used to refer immediate parent class instance variable.
 super() is used to invoke immediate parent class constructor.
 super is used to invoke immediate parent class method.

class Account {
public Account() {
System.out.println("opening an account");
}
}

class Savings extends Account {


public Savings() {
super();
System.out.println("specifying the savings a/c to
opened account");
}
}

class Customer {

88 Raj
S E L E N I U M W E B D R I V E R

public static void main(String args[]) {


Savings s = new Savings();

}
}

super() is added in each class constructor automatically by compiler.

this
„this‟ is an internal or implicit object created by JAVA for two purposes. They are
 „this‟ object is internally pointing to current class object.
 Whenever the formal parameters and data members of the class are
similar, to differentiate the data members of the class from formal
parameters, the data members of class must be proceeded by „this‟.

final

The final keyword in java is used to restrict the user. The final keyword can be
used in many contexts. Final can be:
 variable
If you make any variable as final, you cannot change the value of final
variable (It will be constant).
 Method
If you make any method as final, you cannot override it.
 Class
If you make any class as final, you cannot extend it.

final method is inherited but you cannot override it

Runtime polymorphism

Runtime polymorphism or Dynamic Method Dispatch is a process in


which a call to an overridden method is resolved at runtime rather than compile-
time. In this process, an overridden method is called through the reference
variable of a super class. The determination of the method to be called is based on
the object being referred to by the reference variable.
In the below example, we are creating two classes Bike and Splendor.
Splendor class extends Bike class and overrides its run() method. We are calling

89 Raj
S E L E N I U M W E B D R I V E R

the run method by the reference variable of Parent class. Since it refers to the
subclass object and subclass method overrides the Parent class method, subclass
method is invoked at runtime. Since method invocation is determined by the JVM
not compiler, it is known as runtime polymorphism.

Upcasting:
When reference variable of Parent class refers to the object of Child class, it is
known as upcasting.

Example 1:
class Bike {
void run() {
System.out.println("running");
}
}

class Splendor extends Bike {


void run() {
System.out.println("running safely with 60km");
}

public static void main(String args[]) {


Bike b = new Splendor();// upcasting
b.run();
}
}

// Output:running safely with 60km.

Run time polymorphism can’t be achieved by data members.

Example:
class Bike {
int speedlimit = 90;
}

class Honda3 extends Bike {


int speedlimit = 150;

public static void main(String args[]) {


Bike obj = new Honda3();
System.out.println(obj.speedlimit); // 90
}
}

90 Raj
S E L E N I U M W E B D R I V E R

Static Binding and Dynamic Binding

Connecting a method call to the method body is known as binding.

There are two types of binding

 Static binding (also known as early binding)


When type of the object is determined at compiled time(by the compiler),
it is known as static binding. If there is any private, final or static method
in a class, there is static binding.

 Dynamic binding (also known as late binding)


When type of the object is determined at run-time, it is known as dynamic
binding.

Example of static binding


class Dog {
private void eat() {
System.out.println("dog is eating...");
}
public static void main(String args[]) {
Dog d1 = new Dog();
d1.eat();
}
}

Example of Dynamic binding


class Animal {
void eat() {
System.out.println("animal is eating...");
}
}
class Dog extends Animal {
void eat() {
System.out.println("dog is eating...");
}
public static void main(String args[]) {
Animal a = new Dog();
a.eat();
}
}

//output: dog is eating…


In the above example object type cannot be determined by the compiler, because
the instance of Dog is also an instance of Animal. So compiler doesn't know its
type, only its base type.

91 Raj
S E L E N I U M W E B D R I V E R

Interface

An interface in java is a blueprint of a class. It has static constants and


abstract methods only. The interface in java is a mechanism to achieve fully
abstraction. There can be only abstract methods in the java interface not method
body. It is used to achieve fully abstraction and multiple inheritances in Java.
There are mainly three reasons to use interface.

1) It is used to achieve fully abstraction.


2) By interface, we can support the functionality of multiple inheritances.
3) It can be used to achieve loose coupling.

The java compiler adds public and abstract keywords before the interface method
and public, static and final keywords before data members. In other words,
Interface fields are public, static and final by default, and methods are public and
abstract.

Sample example of Java Interface


interface printable {
void print();
}
class Account implements printable {
public void print() {
System.out.println("Hello");
}
public static void main(String args[]) {
Account obj = new Account();
obj.print();
}
}

Packages

A java package is a group of similar types of classes, interfaces and sub-packages.


Package in java can be categorized in two form, built-in package and user-defined

92 Raj
S E L E N I U M W E B D R I V E R

package. There are many built-in packages such as java, lang, awt, javax, swing,
net, io, util, sql etc.

Advantage of Java Package

1) Java package is used to categorize the classes and interfaces so that they can be
easily maintained.
2) Java package provides access protection.
3) Java package removes naming collision.

Example:
A.java

package pack;
public class A {
public void msg() {
System.out.println("Hello");
}
}

B.java

package mypack;
import pack.*;
class B {
public static void main(String args[]) {
A obj = new A();
obj.msg();
}
}
//output: Hello

Encapsulation

Encapsulation in java is a process of wrapping code and data together into a single
unit, for example capsule i.e. mixed of several medicines. We can create a fully
encapsulated class in java by making all the data members of the class private.
Now we can use setter and getter methods to set and get the data in it.

Advantage of Encapsulation in java


 By providing only setter or getter method, you can make the class read-
only or write-only.

93 Raj
S E L E N I U M W E B D R I V E R

 It provides you the control over the data. Suppose you want to set the
value of id i.e. greater than 100 only, you can write the logic inside the
setter method.

Student.java
package com.school;
public class Student {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}

Test.java
package com.school;
public class Test {
public static void main(String[] args) {
Student s = new Student();
s.setName("vijay");
System.out.println(s.getName());
}
}
// output: Vijay

Access Modifiers

There are two types of modifiers in java: access modifiers and non-access
modifiers. The access modifier in java specifies accessibility (scope) of a data
member, method, constructor or class.
There are 4 types of java access modifiers:
1) private
2) default
3) protected
4) public

There are many non-access modifiers such as static, abstract, synchronized, native,
volatile, transient etc.

94 Raj
S E L E N I U M W E B D R I V E R

Private access modifier

The private access modifier is accessible only within class. If we access these
private members from outside the class, so there is compile time error. If any class
constructor is private, you cannot create the instance of that class from outside the
class.

class A {
private int data = 40;

private A() {
System.out.println("In construcotr...");
}

private void msg() {


System.out.println("Hello java");
}
}

public class AccessMod {


public static void main(String args[]) {
A obj = new A(); //// Compile Time Error
System.out.println(obj.data);// Compile Time Error
obj.msg();// Compile Time Error
}
}

Default access modifier

If you don't use any modifier, it is treated as default by default. The default
modifier is accessible only within package. In the below example, the scope of
class A and its method msg() is default so it cannot be accessed from outside the
package.

A.java

package com.school;

class A {
void msg() {
System.out.println("Hello java");
}
}

95 Raj
S E L E N I U M W E B D R I V E R

AccessMod.java

package com.college;
import com.school;

public class AccessMod {


public static void main(String args[]) {
A obj = new A(); //Compile Time Error
obj.msg(); //Compile Time Error
}
}

Protected access modifier


The protected access modifier is accessible within package and outside the
package but through inheritance only. The protected access modifier can be
applied on the data member, method and constructor. It can't be applied on the
class.

Example
In the below example, we have created the two packages college and school. The
B class of college package is public, so can be accessed from outside the package.
But msg method of this package is declared as protected, so it can be accessed
from outside the class only through inheritance.

B.java

package com.college;
public class B {
protected void msg() {
System.out.println("Hello world");
}
}

AccessMod.java

package com.school;
import com.college.*;

class AccessMod extends B {


public static void main(String args[]) {
AccessMod obj = new AccessMod();
obj.msg();
}
}

96 Raj
S E L E N I U M W E B D R I V E R

Public access modifier

The public access modifier is accessible everywhere. It has the widest scope
among all other modifiers.

Example of public access modifier

B.java

package com.college;
public class B {
public void msg() {
System.out.println("Hello");
}
}

AccessMod.java

package com.school;
import com.college.*;

class AccessMod {
public static void main(String args[]) {
B obj = new B();
obj.msg();
}
}

Access Modifier within class within package outside package outside package
by subclass only
Private Y N N N
Default Y Y N N
Protected Y Y Y N
Public Y Y Y Y

97 Raj
S E L E N I U M W E B D R I V E R

Exception Handling

The exception handling in java is one of the powerful mechanisms to handle the
runtime errors so that normal flow of the application can be maintained.

What is exception?

Def 1: Exception is an abnormal condition. In java, exception is an event that


disrupts the normal flow of the program. It is an object which is thrown at
runtime.

Def 2: An exception is an event that occurs during the execution of a program and
disrupts the normal flow of the program‟s instructions.

What is exception handling?

Exception Handling is a mechanism to handle runtime errors such as


ClassNotFound, IO, SQL, Remote etc.

Advantage of Exception Handling

The core advantage of exception handling is to maintain the normal flow of the
application. Exception normally disrupts the normal flow of the application that is
why we use exception handling.

Types of Exception

There are mainly two types of exceptions: checked and unchecked where error is
considered as unchecked exception. The sun Microsystems says there are three
types of exceptions:

1) Checked Exception
The classes that extend Throwable class except RuntimeException and Error
are known as checked exceptions e.g.IOException, SQLException etc.
Checked exceptions are checked at compile-time.

2) Unchecked Exception
The classes that extend RuntimeException are known as unchecked exception
e.g. ArithmeticException, NullPointerException, ArrayIndexOutOfBounds
Exception etc. Unchecked exceptions are not checked at compile-time rather
they are checked at runtime.

98 Raj
S E L E N I U M W E B D R I V E R

3) Error
Error is irrecoverable
e.g. OutOfMemoryError, VirtualMachineError, AssertionError etc.

Exception handling keywords:


 try
 catch
 finally
 throw
 throws
Handling exceptions using try – catch block
Placing try-catch block around the code which might generates exception.

Try block
Enclose the code that might throw an exception in try block. It must be used
within the method and must be followed by either catch or finally block.

Always use try catch block to log your exception in selenium WebDriver reports.

Syntax 1:
Catch block is used to handle the Exception. It must be used after the try block.
try{
........
........
}catch(exception_class_name reference){
........
........
}

Syntax 2:
The finally block is a block that is always executed regardless of exception is
occurred or not. It is mainly used to perform some important tasks such as closing
connection, stream etc.
try{
........
........
}finally {
........
........
}
Note: finally must be followed by try or catch block.

99 Raj
S E L E N I U M W E B D R I V E R

Handling Exception using throw and throws keyword

throw

The throw keyword is used to explicitly throw an exception. We can throw either
checked or unchecked exception. The throw keyword is mainly used to throw
custom exception
public class Testing {
static void validate(int age) {
if (age > 18) {
System.out.println("eligible for voting");
} else {
throw new ArithmeticException("not valid");
}
}
public static void main(String[] args) {
validate(15);
}
}//output: Exception in thread "main" java.lang.ArithmeticException:
not valid

throws

This is the keyword which gives an indication to the calling function to keep the
called function under try and catch blocks.

Example 1:
class Testing1 {
public void div(String s1, String s2) throws
ArithmeticException,
NumberFormatException {
int n1 = Integer.parseInt(s1);
int n2 = Integer.parseInt(s2);
int n3 = n1 / n2;
System.out.println("DIVISOIN = " + n3);
}
}
class Testing {
public static void main(String[] args) {
try {
String s1 = args[0];
String s2 = args[1];
Testing1 eo = new Testing1();
eo.div(s1, s2);
} catch (ArithmeticException Ae) {
System.out.println("DONT ENTER ZERO FOR DENOMINATOR");
} catch (NumberFormatException Nfe) {
System.out.println("PASS INTEGER VALUES ONLY");
} catch (ArrayIndexOutOfBoundsException Aioobe) {
System.out.println("PASS VALUES FROM COMMAND PROMPT");

100 Raj
S E L E N I U M W E B D R I V E R

}
}
};
// output: PASS VALUES FROM COMMAND PROMPT

Example 2:

import java.io.IOException;
public class Testing {
void m() throws IOException {
throw new IOException("device error...");
}
void n() throws IOException {
m();
}

void p() {
try {
n();
} catch (Exception e) {
System.out.println("exception handled");
}
}

public static void main(String[] args) {


Testing t = new Testing();
t.p();
}
}
//output: exception handled

Always keep adding new tools & technologies in your box

101 Raj

You might also like