Selenium Webdriver Notes
Selenium Webdriver Notes
Vol.
SeleniumWebDriver
FOR CORPORATE TRAINING
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
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:
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.
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.
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.
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:
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.
6 Raj
S E L E N I U M W E B D R I V E R
4
Topic
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;
@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
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
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.
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.
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.
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>))
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 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");
}
}
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
Using the id attribute is the most preferable way to locate elements on a page. The
W3C standard
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();
}
}
13 Raj
S E L E N I U M W E B D R I V E R
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.
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.
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.
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.
Step 1: Type “//img[@class=‟logo‟]” i.e. the locator value in the target box within the
Selenium IDE.
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.
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.
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:
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.
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.
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.
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.
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.
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.
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:
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
IsDisplayed()
The isDisplayed action verifies if an element is displayed on the web page and can be
executed on all the WebElements.
IsEnabled()
The isEnabled action verifies if an element is enabled on the web page and can be
executed on all the WebElements.
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.
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();
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.
}
}
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.
}
}
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
GetWindowHandle
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");
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"));
}
}
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.
28 Raj
S E L E N I U M W E B D R I V E R
SwitchTo Frame
driver.switchTo().frame("frameName");
@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
Button
Clicking the button can be done by using Click()
method.
Checkbox
Selecting the checkbox can be done by using Click()
method.
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.
@Test
public void cssLoc(){
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.
@Test
public void testRdbtn() {
}
}
Link
Selenium WebDriver supports Radio Button and Radio
Group controls using the
31 Raj
S E L E N I U M W E B D R I V E R
13
Topic
@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();
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.
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();
}
}
33 Raj
S E L E N I U M W E B D R I V E R
14
Topic
34 Raj
S E L E N I U M W E B D R I V E R
15
Topic
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;
@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
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
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'
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.
42 Raj
S E L E N I U M W E B D R I V E R
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;
//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");
if(result.equals("5"))
{
logger.info("The Result is Pass");
}
else
{
logger.error("TEST FAILED. NEEDS INVESTIGATION");
logger.info("# # # # # # # # # # # # # # # # # # # # # # # ## # ");
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.
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:
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:
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.
This will start the Selenium server in the node mode and register this node with
the already started hub.
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.
49 Raj
S E L E N I U M W E B D R I V E R
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 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;
50 Raj
S E L E N I U M W E B D R I V E R
@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");
// 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
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
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 Server
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
selenium.click("xpath=.//*[@id='menu']/div[4]/div[3]/a");
Thread.sleep(4000); // Wait for page load
selenium.click("xpath=.//*[@id='content']/table/tbody/tr/t
d[2]/input");
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.
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.
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;
61 Raj
S E L E N I U M W E B D R I V E R
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?
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.
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 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.
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
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;
@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");
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
data[1][0] = 30;
data[1][1] = 40;
return Arrays.asList(data);
}
}
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 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>
groupId: Generally groupId refers to domain id. For best practices company
name is used as groupId. It identifies the project uniquely.
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.
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
Reusability of code
Maximum coverage
Recovery scenario
Low cost maintenance
Minimal manual intervention
Easy Reporting
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.
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.
76 Raj
S E L E N I U M W E B D R I V E R
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?
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
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
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
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
Class: Class is a way of binding the data and associated methods in a single unit.
class Room {
int l;// data member (also instance variable)
int w;// data member (also instance variable)
}
}
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
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);
}
Method overloading
83 Raj
S E L E N I U M W E B D R I V E R
Example 1:
class Calc {
void sum(int a, int b) {
System.out.println(a + b);
}
Example 2:
class Room {
void area(int l, int b) {
System.out.println(l * b);
}
Constructor
84 Raj
S E L E N I U M W E B D R I V E R
Types of constructors
default constructor is one which will not take any parameters (no-arg
constructor)
parameterized constructor
Example 1:
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
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
Inheritance
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.
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.
class Account {
public Account() {
System.out.println("opening an account");
}
}
class Customer {
88 Raj
S E L E N I U M W E B D R I V E R
}
}
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.
Runtime polymorphism
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");
}
}
Example:
class Bike {
int speedlimit = 90;
}
90 Raj
S E L E N I U M W E B D R I V E R
91 Raj
S E L E N I U M W E B D R I V E R
Interface
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.
Packages
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.
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.
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
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...");
}
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;
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.*;
96 Raj
S E L E N I U M W E B D R I V E R
The public access modifier is accessible everywhere. It has the widest scope
among all other modifiers.
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 2: An exception is an event that occurs during the execution of a program and
disrupts the normal flow of the program‟s instructions.
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.
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
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");
}
}
101 Raj