0% found this document useful (0 votes)
2K views139 pages

Selenium Suresh V004

This document provides information about an upcoming Selenium training by Mr. Suresh, including his background and experience in Selenium training and testing. It outlines the modules that will be covered in the Selenium training, including Selenium components, WebDriver, frameworks design, and RESTful services. It also discusses the automation testing process used in Mr. Suresh's current project and provides definitions and benefits of key topics like retesting, regression testing, and automated testing. Finally, it covers Selenium history and compares Selenium to other testing tools.

Uploaded by

tester mahesh25
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2K views139 pages

Selenium Suresh V004

This document provides information about an upcoming Selenium training by Mr. Suresh, including his background and experience in Selenium training and testing. It outlines the modules that will be covered in the Selenium training, including Selenium components, WebDriver, frameworks design, and RESTful services. It also discusses the automation testing process used in Mr. Suresh's current project and provides definitions and benefits of key topics like retesting, regression testing, and automated testing. Finally, it covers Selenium history and compares Selenium to other testing tools.

Uploaded by

tester mahesh25
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 139

Selenium Training by Suresh

Selenium Notes By
SURESH

Mr. Suresh Page 1 of 139


Selenium Training by Suresh

Mr. Suresh – Profile


 Currently working as a Consultant with one of the Top MNC and has 11
years of genuine experience in Software Testing.
 Hands-on experience with Selenium since 2009 and has 6 years of in-
house Corporate Training experience.
 Successfully trained 90+ batches on Selenium
 Expert in Selenium Automation using Selenium RC and WebDriver.
Heavy Programming using Java, TestNG and worked with QTP and
Ruby with Watir as well.
 Proficient in Planning, Designing, Building and maintaining complex
automation frameworks (Keyword, Modular, Hybrid and POM).
 Pro-active Team Leader and Manager with strong focus on
documentation and process.
 Rich industry experience as worked with Symphony Services,
Accenture, IGATE and Capgemini.
Specializations:
 Expertise in creating Test Automation Frameworks for open source
automation tools.
 Competence in open source automation APIs like Selenium RC and Web
Driver.
 Proficiency in conducting Classroom, Corporate and Online Training on
Selenium.

Mr. Suresh Page 2 of 139


Selenium Training by Suresh

SELENIUM with PROJECT Training


Module 1 : Selenium Components and Object Identification
Module 2 : Core Java with Examples
Module 3 : WebDriver with Project
Module 4 : Frameworks Designing and Implementation
Module 5 : Framework Integration with Third Party Tools
Module 6 : Fundamentals of RESTFUL services in java

Mr. Suresh Page 3 of 139


Selenium Training by Suresh
Automation Testing Process
In my current project Automation testing process started with three Stages
Stage 1
1. Tool Evaluation
Stage 2
2. Analyzing the test cases
3. Preparing Analysis sheet
4. Estimating Script development time
5. Sending summary sheet for Approval
6. Confirmation
Stage 3
7. Automation folder Structure Preparing
8. Preparing Object Repository
9. Creating re-usable components and functions
10. Creating scripts and enhancing scripts
11. Dry run
12. Final Execution
13. Peer Execution
14. Delivery of scripts
15. Enhancements

Retesting and Regression Testing


What is Retesting?
Retesting of the application to verify whether defects have been fixed or not.
What is Regression testing?
1.It is Re=Execution of some or all the test cases of a testing activity for each build to verify
that changes or fixes made have not introduced new errors
2. Regression testing is done in three situations
i) One is after fixing the bug
ii) Second one is if a new change request will come from client
iii) Third one is when Enviromnent changes
Here we have to verify whether already existing functionality can getting defects (or) not.
What is “Automated Testing”
 Automated Testing is automating the manual testing process currently in use.
 This requires that a formalized “Manual Testing process” currently exists in your
company
Mimimally, such a process includes:
1. Detailed test cases, including predictable “expected results”.(test cases must be
documented)
2. A standalone Test Environment, including a Test Database, such that the test cases are
able to be repeated each time there are modifications made to the applications.
If your current testing process does not include the above points, you are never going to be
able to make any Effective use of an automated test tool.
 The real use and purpose of automated test tools is to automate regression testing
 This means that you must have or must develop a database of detailed test cases that
are repeatable,and this suite of tests is run every time there is a change to the
application to ensure that the change does not produce unintended
consequences(errors)

Mr. Suresh Page 4 of 139


Selenium Training by Suresh
 An “automated test script ” is a program
 Automated Script development, to be effective must be subject to the same rules and
standards that are applied to software development.
 An “automated test Suite” is a database of all detailed Automation test Cases.

Why we go for Automation?


Manual Testing
 Testing an application with human interaction is called ManualTesting.
Problems in Manual Testing
 No Reusability
 More Resources required
 Time consuming
 Budget is high
 Human Errors causes poor quality
What is Automation Testing?
 Testing an application with third party Software help or Automation Tool is called
Automation testing.
(OR)
 Converting manual test cases into Automation Scripts (in form of code ) is called
Automation Tesing
Benefits of Automation Testing
 Fast
 Reliable
 Repeatable
 Reusable
 Comprehensive
 Programmable
Fast: Automation tool runs tests significantly faster than human users.
Reliable: Automation tool can perform the same operations each time,if you repeated
multiple times,so that we can eliminate human erros
Repeatable: We can check hoe application or website reacts after repeated the same
operation with multiple times
Reusable: Autoamtion scripts reusable on diffirent version of the application of websites
even if the user interfaces changes
Comprehensive: In automation testing we can build a suit of tests that covers every feature
in the application or website
Programmable: We can program sophisticated Test that brings out hidden information from
the application.
Automated Functional Testing Tools
Open Source Commercial
Selenium QTP
Sikuli Test Partner
Sahi Test complete
Bad Boy RFT
Ruby Silk
Watir

Mr. Suresh Page 5 of 139


Selenium Training by Suresh
Tool Evaluation
In my current project, Automation tool is evaluated based on below project features:
1. Multiple Browser Support
2. Language support
3. Ease of Use
4. Multiple Operating Systems
5. Ajax Support
6. Web Application support
7. UI tests
8. Scripting
9. Record and play back
10. Object recognition capability
11. Customization of recorded code as per our requirements
12. Synchronization issues
13. Test Suite Creation
14. Maintenance of scripts when features modified
15. Central Object Repository
16. APIs availability
17. Database verification
18. Vendor support
19. Framework Creation
20. Tool Performance
 Based on initial evaluation on above project scenarios, the above information is
captured.
 Selenium and QTP or any other automation tools are finalized after evaluation.
 Clinet /management are finalized SELENIUM tool to automate my Current Project.

SELENIUM QTP
Open source Paid Tool
Works on all OS (Windows, OS
Works only on Windows
X, Linux, Solaris,Mac)
Tests only Web applications Tests web and desktop applications
Works on almost all browsers(IE,
Works on IE
Firefox, Chrome, Safari, Opera)
Code can be made in any one of
languages such as Java, C#, Ruby, VB Script
Python, pearl, php
Object Identification Options : Name ,Id Object Identification Options : Object
, Xpath, CSS, Link text …etc properties, Repository objects
Selenium dose not have such built in
object repository, but object can be HP UFT comes with built in object
managed by using UI element user repository. Object repository development
extension like Inspect option in All and maintenance is quite easy in HP ALM
browsers
IDE sometimes does not record some Recording is a little reliable

Mr. Suresh Page 6 of 139


Selenium Training by Suresh
events
Set of Libraries, around 20MB (Need to
Around 1.5GB
include other supporting software)
Saucelabs.com, Element34 , Commercial
From HP
Support
Selenium History
 In 2004 invented by Jason Huggins and team
 Originally name is JavaScript Functional Tool (JSFT)
 Open source browser based integration framework (Selenium RC )built originally by
Thought Works
 Google, who has been a long time user of Selenium, had a developer named Simon
Stewart who developed WebDriver. This tool circumvented Selenium’s JavaScript
sandbox to allow it to communicate with the Browser and Operating System directly
using native methods
 In 2008, Selenium and WebDriver merged technologies and intellectual intelligence
to provide the best possible test automation framework
 100% JavaScript and HTML Web Testing Tool

What is Selenium?
Selenium is a free (open source) automated testing suite for web applications across different
browsers and platforms. It is quite similar to HP Quick Test Pro (QTP) only that Selenium
focuses on automating web-based applications.
Selenium is not just a single tool but a suite of softwares, each catering to different testing
needs of an organization. It has four components.
Selenium Components
 Selenium IDE (Integrated Development Environment) - Record & Play back
 Selenium RC- 1.0 – Server /Client (Selenium. Start /Selenium. Stop)
 Selenium 2.0/3.0 / Web Driver /Advanced Selenium
 Selenium Grid – To Execute scripts in Multiple Browsers & Systems

Mr. Suresh Page 7 of 139


Selenium Training by Suresh
Selenium IDE
Introduction: The selenium IDE is the tool used to develop your selenium test cases by
using record and play back.
Advantages
 It’s an easy –to-use
 It’s just Firefox plug in and is generally the most efficient way to develop test cases
 Very useful tool for beginners
 Firefox extension which allows record/Play testing paradigm
 Creates the simplest possible locator based on Selene's
 Look at various possible commands in the dropdown
 Records a test at HTML file
 We can export the test as Java /Ruby etc...
Disadvantages
 Selenium-IDE does not directly support:
 Condition statements & Iteration or looping
 Logging and reporting of test results
 Error handling, particularly unexpected errors
 Database testing
 Test case dependency
 Capture screenshots on test failures
 Results Report generations

Selenium–Locators / Object Indentification


What is Locator? -- The 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.
Note1 :
Group of elements are considered as One WebPage
Group of WebPages are considered as One Application
Examples for webelement in page are like -- Text box ,Button ,Drop Down ,Hyperlink
,Check Box
Radio Button …etc
Selenium will identify the objects by using below locators
 By Using “Name “
 By Using “ID “
 By Using “Class Name “
 By Using “TagName “
 By Using “LinkText”
 By Using “Partial LinkText”
 By Using “CssSelector “ (Note : Prefered for IE Browser)
 By Using “XPATH “ (Note : Prefered for Any Browser)

Mr. Suresh Page 8 of 139


Selenium Training by Suresh

*In any of the html code starting with < symbol is considered as HTML TAG name and
which is having = symbol considered as Attributes

Locating element using Name , ID and ClassName


Syntax By using ID
Id = @Id -- Mention the ID property details of that object
Eg: id =txtLoginName

Syntax By Using Name:


name = @name -- Mention the name property details of that object
Eg: name = txtUserName

Syntax By Class Name:


class = @classname -- Mention the class name property details of that object
Eg: class = loginText

Locating element using TagName ,LinkText ,partial LinkText and CSS Selector
Syntax By using TagName
Here we use the actual name of the tag like <a> for anchor and <table> for table. This turns
out to be useful when we would like to get all the elements with a given tag name
Eg: tagname=<a> -- Mention the tagname details of that object
Syntax By using LinkText
linkText is very useful when you want to interact with hyperlinks. The actual text displayed
on the web page for that link is used
Eg: link = linktextdetails --- Mention the linktext details of that object
Syntax By using Partial LinkText
PartialLinkText is also used to interact with hyperlinks and is very similar to linkText
locating strategy. Instead of providing the complete text displayed for the link, this method
does a partial match

Mr. Suresh Page 9 of 139


Selenium Training by Suresh
Eg: partiallinkText = linktextdetails --- Mention the linktext details partially of that object
Syntax By using CSS Selector
CSS (Cascading Style Sheets) is a language for describing the rendering of HTML and
XML documents.
Syntax: css=htmltagname [attribute Type=‘attribute Value’]

Xpath in SELENIUM: What is Xpath – group of nodes


XPath is the language used when locating XML (Extensible Markup Language) nodes. Since
HTML can be thought of as an implementation of XML, we can also use XPath in locating
HTML elements.
Advantage: It can access almost any element, even those without class, name, or id
attributes.
Disadvantage: It is the most complicated method of identifying elements because of too
many different rules and considerations.
Diffirent Types of Xpath in SLEENIUM
1.Absolute Xpath
2.Relative Xpath

Diffirent Ways of Relative Xpath in SLEENIUM


We have different ways to identify the object using Xpath
 Relative Xpath
Relative Xpath begins from the current location and is prefixed with “//”.
Syntax: //htmltagname[@attribute Type=‘attribute Value’]/all nodes info:
 Xpath with attributes
Xpath with attributes will use attributes to identify the objects

Mr. Suresh Page 10 of 139


Selenium Training by Suresh
1.Xpath with single attribute
Syntax: //htmltagname[@attribute Type=‘attribute Value’]
2.Xpath with Multiple attribute
Syntax: //htmltagname[@attributeType=‘attributeValue’][@attributeType=‘attributeValue’]
3.Xpath with text attribute
Syntax: //htmltagname[text()=’text details’]
4.Xpath with Contains
contains() can be used to find an element by specifying any partial value of the attribute.
This function comes handy when attribute value changes dynamically on page reload.
Syntax: //htmltagname[contains(@attributeType,’ attribute value’)]
5.Xpath with Starts with
Starts-with() can be used to find an element by specifying a partial value (prefix) of the
attribute. This function comes handy when attribute value changes dynamically on page
reload.
Syntax: //htmltagname[starts-with(@attributeType, ‘attribute value’)]
Examples for - Different ways of Xpath in Selenium
We have different ways to identify the object using Xpath
 Relative Xpath
Relative Xpath begins from the current location and is prefixed with “//”.
Syntax: //htmltagname[@attribute Type=‘attribute Value’]/all nodes info:

Relative xpath for above HTML code


Eg: //table[@id='Table_01']/tbody/tr[1]/td[2]/table/tbody/tr[2]/td[2]/input

Mr. Suresh Page 11 of 139


Selenium Training by Suresh
 Xpath with attributes
Xpath with attributes will use attributes to identify the objects
1. Xpath with single attribute
Syntax: //htmltagname[@attribute Type=‘attribute Value’]

Eg: //input [@name=’txtUserName’]


2. Xpath with Multiple attribute
Syntax: //htmltagname[@attribute Type=‘attribute Value’][@attribute Type=‘attribute
Value’]
Eg: //input [@class=’loginText’][@name=’txtUserName’]

Tools for Object Indentification in Selenium


1.Chrome Browser – Inspect Option(Right click on any element and select Inspect option)
,OSpy
2.Firefox–InspectElement(Q)-(Right click on any element and select Inspect option),Firebug
,Firepath
3.IE Browser– Developer Tools(Click on Tools and select Developer Tools option)

Mr. Suresh Page 12 of 139


Selenium Training by Suresh
Assignment On - HRMS Project Object Identification
Identify the objects for the screens with help of below html code. -- Login Page :

Username Textbox

Relative Xpath
Xpath with Single attribute
Xpath with Contains
Xpath with Starts-With
Xpath with Multiple
attribute
Password Textbox

Mr. Suresh Page 13 of 139


Selenium Training by Suresh
Relative Xpath
Xpath with Single attribute
Xpath with Contains
Xpath with Starts-With
Xpath with Multiple attribute

Login button

Relative Xpath
Xpath with Single attribute
Xpath with Contains
Xpath with Starts-With
Xpath with Multiple
attribute
Clear button

Mr. Suresh Page 14 of 139


Selenium Training by Suresh
Relative Xpath
Xpath with Single attribute
Xpath with Contains
Xpath with Starts-With
Xpath with Multiple attribute
Company General Info:

Company Name Textbox

Relative Xpath
Xpath with Single attribute
Xpath with Contains
Xpath with Starts-With
Xpath with Multiple attribute

Mr. Suresh Page 15 of 139


Selenium Training by Suresh

Number of Employees

Relative Xpath
Xpath with Single attribute
Xpath with Contains
Xpath with Starts-With
Xpath with Multiple attribute
Phone number

Relative Xpath
Xpath with Single attribute
Xpath with Contains
Xpath with Starts-With
Xpath with Multiple attribute

Mr. Suresh Page 16 of 139


Selenium Training by Suresh
Country

Relative Xpath
Xpath with Single attribute
Xpath with Contains
Xpath with Starts-With
Xpath with Multiple attribute
Company Info Locations

Add button

Relative Xpath
Xpath with Single attribute
Xpath with Contains
Mr. Suresh Page 17 of 139
Selenium Training by Suresh
Xpath with Starts-With
Xpath with Multiple attribute
Delete button

Relative Xpath
Xpath with Single attribute
Xpath with Contains
Xpath with Starts-With
Xpath with Multiple
attribute

Common Interview Questions on Selenium IDE


1. What is Automation Testing

2. What are the benefits of Automation Testing

3. On which Testing phase automation will be started

4. what are the Pre-Requisites to start automation

Mr. Suresh Page 18 of 139


Selenium Training by Suresh

5. Explain Tester Roles and Responsbilities

6. Why should Selenium be selected as a test tool

7. Write Xpath for Gmail Inbox(50) but after some time it will change to Inbox(55)

8. What is Selenium? What are the different Selenium components?

9. What are the different types of locators in Selenium?

10. Explain Tester day to day activities

Mr. Suresh Page 19 of 139


Selenium Training by Suresh

11. Difference between Relative Xpath and Absolute Xpath

12.What are the limitations of Selenium

13.Explain the syntax for Xpath with Contains and Startswith

14.Diffirence between Xpath with Contains and Startswith

15.Why should we hire you

Mr. Suresh Page 20 of 139


Selenium Training by Suresh
Core Java
History of JAVA
JAVA is a distributed technology developed by James Gosling, Patric Naugton, etc.,
at Sun Micro System ((which has been acquired by Oracle Corporation)) 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). The language derives much of its syntax from C and C++, but
it has fewer low-level facilities than either of them.
JAVA released to the market in three categories J2SE (JAVA 2 Standard
Edition)[considered as Core Java], J2EE (JAVA 2 Enterprise Edition) and J2ME (JAVA 2
Micro/Mobile Edition).
Java terminology:
Before we start learning Java, let’s get familiar with common java terms.
Java Development Kit(JDK)
While explaining JVM and bytecode, I have used the term JDK. Let’s discuss about it. As the
name suggests this is complete java development kit that includes JRE (Java Runtime
Environment), compilers and various tools like JavaDoc, Java debugger etc.
In order to create, compile and run Java program you would need JDK installed on your
computer.
Java Runtime Environment(JRE)
JRE is a part of JDK which means that JDK includes JRE. When you have JRE installed on
your system, you can run a java program however you won’t be able to compile it. JRE
includes JVM, browser plugins and applets support. When you only need to run a java
program on your computer, you would only need JRE.
Compiler(javac) converts source code (.java file) to the byte code(.class file). As mentioned
above, JVM executes the bytecode produced by compiler. This byte code can run on any
platform such as Windows, Linux, Mac OS etc. Which means a program that is compiled on
windows can run on Linux and vice-versa. Each operating system has different JVM,
however the output they produce after execution of bytecode is same across all operating
systems. That is why we call java as platform independent language.

Mr. Suresh Page 21 of 139


Selenium Training by Suresh
JAVA Installation Steps
Step 1) Go
to link(http://www.oracle.com/technetwork/java/javase/downloads/index.html). Click on
Download JDK

Step 2) Next, Accept License Agreement


1. Download JDK for your version(32 or 64 bit) of Windows

Step 3) once the download is complete, run the exe. Click Next

Step 4) once install is complete click close

Mr. Suresh Page 22 of 139


Selenium Training by Suresh

Step 5) Set Environment Variable,- PATH = C:\Program Files\Java\jdk1.8.0_31\bin;

Step 6) Restart your PC. Go to command prompt and type javac--If you see a screen like
below' Java is installed.

Eclipse IDE Installation


EclipseIDE: Eclipse is an integrated development environment used in computer
programming, and is the most widely used Java IDE. It contains a base workspace and an
extensible plug-in system for customizing the environment and used to write the Java code.
Step 0: Complete JDK Installation-To use Eclipse, you need to first install Java Development
Kit (JDK).
Step 1: Download Eclipse from http://www.eclipse.org/downloads/eclipse-packages/.
choose the Eclipse IDE for Java EE Developers and click on 32-bit or 64-bit link
Note: Eclipse will be downloaded as Zipfile.
Step 2: Simply extract the downloaded file into a directory of your choice (e.g.,
"d:\myproject").
There is no need to run any installer. Moreover, you can simply delete the entire Eclipse
directory when it is no longer needed (without running any un-installer). You are free to
Mr. Suresh Page 23 of 139
Selenium Training by Suresh
move or rename the directory. You can install (unzip) multiple copies of Eclipse in the same
machine.
Step 3: Since Eclipse IDE does not have any installer, there will be a file inside the Eclipse
folder named eclipse.exe. You can double click on the file to run Eclipse.
Note :( This step is not required, but it’s strongly recommended.) Right-click the Eclipse Icon
and press “Send To” -> “Desktop (Create Shortcut).” Now you will be able to launch Eclipse
from your desktop.

Step 4: Create a workspace folder where you will contain all the program files you create.
You can choose whatever place you want for your workspace, I like to choose my own
workplace location and will place all my projects under it.

Step 5 : Now you will be able to see the welcome screen ,you can close welcome screen and
then start writing the java code

About Java programs, it is very important to keep in mind the following points.
Case Sensitivity - Java is case sensitive which means identifier Hello and hello would have
different meaning in Java.
Class Names - For all class names the first letter should be in Upper Case.
If several words are used to form a name of the class each inner words first letter should be in
Upper Case. Example class MyFirstJavaClass
Method Names - All method names should start with a Lower Case letter.
If several words are used to form the name of the method, then each inner word's first letter
should be in Upper Case. Example public void myMethodName ()
Program File Name - Name of the program file should exactly match the class name.
Example: Assume 'MyFirstJavaProgram' is the class name. Then the file should be saved as
'MyFirstJavaProgram.java'

Mr. Suresh Page 24 of 139


Selenium Training by Suresh
Steps To write First Java Program in Eclipse IDE :
1.Launch Eclipse
2.Create new Java Project(Navigation: FileNewProjectSelect Java Folder Select
Java Project optionClick on Next buttonProvide any Project Name and click on Finish
buttonProject will be created in eclipse as below.)

3.Create new Package (Navigation: Perform Right click on Created project Navigate to
New and click on package optionProvide any package name(eg:examples) and click on
Finish buttonPackage will be created as below)

4.Create new Class(Navigation : perform Right click on Created packageNavigate to New


and click on Class optionProvide any class name (Hello) and click on Finish buttonclass
will be created as below )

5.Create required methods /code


6. Run the program and able to see the output in eclipse console window.
Note : Any JAVA program if we want to develop then that should be developed with
respective class only i.e., without class there is no java program

Class: A class can be defined as a template/ blue print that describe the behaviors/states that
object of its type support. (or) “A class is a way of binding the data and associated methods in
a single unit. (or) A Class is a combination of DataTypes and Data Variables
Syntax for defining a CLASS:
Class <clsname> {
Variable declaration;
Methods definition;
}
Class contains two parts namely variable declaration and method definitions. Variable
Declaration represents what type of data members which we use as a part of the class.
Method definition represents the type of methods which we used as the path of the class to
perform an operation.By making use of the variables, which are declared inside the class?
Every operation in JAVA must be defined with in the class only i.e. outside definition is not
possible.
Note : We have diffirent types of classes for now we need to understand below types
1.Instance classes (Need to create object to access methods from this class)
2.Static class (No need of to create object to access methods from this class ,We can access
the method by using class name )
Mr. Suresh Page 25 of 139
Selenium Training by Suresh
First Program in JAVA – To Print the statement as Welcome to JAVA
public class Hello{
public static void main(String args[]) {
System.out.println ("Welcome to JAVA "); // prints Welcome to JAVA
}
Output : Welcome to JAVA
Description for above program
Public: This is access modifier keyword which tells compiler access to class. Various values
of access modifiers can be public, protected, private or default (no value).
Class: This keyword used to declare class. Name of class (Hello) followed by this keyword.
“public static void main (String [ ] args)”: java program processing starts from the main ()
method which is a mandatory part of every java program.
Its method (Function) named main with string array as argument.
public : Access Modifier
static: static is reserved keyword which means that a method is accessible and usable even
though no objects of the class exist.
void: This keyword declares nothing would be returned from method. Method can return any
primitive or object.
Method content inside curly braces. { }
System.out.println("Welcome to JAVA") : This statement is used to print any information
System: It is name of Java utility class.
out: It is an object which belongs to System class.
println: It is utility method name which is used to send any String to console.

Write a Java program to print stmt as – “My target to get job is 2 months”

Method: A method is a program module that contains a series of statements that carry out a
task.Any class can contain an unlimited number of methods, and each method can be called
an unlimited number of times. The syntax to declare method is given below.
public void methodname(){
//statements to print;
}
Eg: public void m1(){
System.out.println(“Method 1 executed”);
}

Mr. Suresh Page 26 of 139


Selenium Training by Suresh
There are two types of methods-
Builtin / Pre-Defined methods: Defined by the language
User-Defined : Defined by the user

Object - object is an instance of a class.Instance (instance is a mechanism of allocating


sufficient amount of memory space for dataMembers of a class)

Syntax-1 for defining an OBJECT:


<Clsname> objname = new <clsname ()>
Student so = new student ();

Sample program to create Class ,Method and Object


public class Hello {
Public void m1() {
System.out.println ("m1 method executed");
}
public void m2() {
System.out.println ("m2 method executed");
}
public void m3() {
System.out.println ("m3 method executed");
}
public static void main (String args []) {
System.out.println("Welcome to Selenium Training");
Hello m = new Hello();
m.m1 ();//Accessing method by using object
m.m2 ();
m.m3 ();
}
}

Mr. Suresh Page 27 of 139


Selenium Training by Suresh
Create a class and methods to print below stmt by calling methods with object
Class name : SeleniumComponents
Method Name : seleniumIde – PerformRecord and Palyback
Method Name : seleniumWebdriver – To develop Automation Scripts
Method Name : seleniumGrid – To execute Scripts in Multipul Browsers and Systems

Data Types and Variables

Data Types :
Data type defines the values that a variable can take, for example if a variable has int data
type, it can only take integer values. In java we have two categories of data types
1.Primitive Data Types
2.Reference/Object Data Types
Primitive Data Types –Byte ,Short ,int,long,float,double,boolean,char
Reference Data Types:
 Reference variables are created using defined constructors of the classes. They are
used to access objects. These variables are declared to be of a specific type that cannot
be changed. For example, Employee, Puppy etc.
 Class objects and various types of array variables come under reference data type.
 Default value of any reference variable is null.
 A reference variable can be used to refer to any object of the declared type or any
compatible type.
 Example : Animal animal = new Animal("giraffe");
 Java language supports few special escape sequences for String and char literals as
well.
Variables : A variable is a name which is associated with a value that can be changed. For
example when I write int i=10; here variable name is i which is associated with value 10, int
is a data type that represents that this variable can hold integer values.
Mr. Suresh Page 28 of 139
Selenium Training by Suresh
There are three kinds of variables in Java:
In Java, all variables must be declared before they can be used
Local variables – Defined with in the method and able to access with in that method only
Instance variables – Defined outside the method and with in the class
Static/class variables –Need to use the keyword as Static
Variables are nothing but reserved memory locations to store values. This means that
when you create a variable you reserve some space in memory.
Based on the data type of a variable, the operating system allocates memory and decides what
can be stored in the reserved memory. Therefore, by assigning different data types to
variables, you can store integers, decimals, or characters in these variables.

Sample program for - DataTypes , Variables and Static method


public class Dt_Var {
int b=20; //instance variables
static int empid = 101; //static variables
public void m1() {
int a = 10; //local variables
System.out.println("M1 Executed");
System.out.println("Local varible " + a );
}
public void m2() {
System.out.println("M2 Executed");
System.out.println("instance varible " + b);
System.out.println("Static varible " + empid);
}
public void m3() {
System.out.println("M3 Executed");
System.out.println("instance varible " + b);
System.out.println("Static varible " + empid);
}
public static void st() {
System.out.println("Static method executed");
}
public static void main(String args[]){
System.out.println("Main methed executed");
Dt_Var m = new Dt_Var ();
m.m1();//Accessing method by using object
m.m3();
m.m2();
Dv.st();//no need of to create any object.Accessing method by using classname
}
}

Java Access Modifiers : The Java language has a wide variety of modifiers, including the
following:
 Java Access Modifiers & Non Access Modifiers
Java provides a number of access modifiers to set access levels for classes, variables,
Mr. Suresh Page 29 of 139
Selenium Training by Suresh
methods and constructors. The four access levels are:
1. Visible to the package. The default. No modifiers are needed.
2. Visible to the class only (private).
3. Visible to the world (public).
4. Visible to the package and all subclasses (protected).
Java provides a number of non-access modifiers to achieve many other functionality.
 The static modifier for creating class methods and variables
 The final modifier for finalizing the implementations of classes, methods, and
variables.
 The abstract modifier for creating abstract classes and methods.
The synchronized and volatile modifiers, which are used for threads.

Operators :Java provides a rich set of operators to manipulate variables. We can divide all
the Java operators into the following groups:
•Arithmetic Operators(- + * / % ++ --)
•Relational Operators (> < >= <= == !=)
•Bitwise Operators(& | ^ >> >>>)
•Logical Operators (&& || & |! ^)
•Assignment Operators( = , +=)
•Misc Operators (? :)

Conditions (or) Control Flow Statements


When we need to execute a set of statements based on a condition then we need to use
control flow statements. For example, if a number is greater than zero then we want to print
“Positive Number” but if it is less than zero then we want to print “Negative Number”. In this
case we have two print statements in the program, but only one print statement executes at a
time based on the input value. We will see how to write such type of conditions in the java
program using control statements.
we will use four types of control statements in java programs based on the
requirement:
a) if statement
b) if-else statement
c) if-else-if statement
d) nested if statement

The if Statement:
If statement consists a condition, followed by statement or a set of statements as shown
below:
if(condition){
Statement(s);
}
The statement gets executed only when the given condition is true. If the condition is false
then the statements inside if statement body are completely ignored.
Example1:
public class Test {
public static void main(String args[]){
int x = 10;
Mr. Suresh Page 30 of 139
Selenium Training by Suresh
if( x < 20 ){
System.out.print("This is if statement");
}
}
}
This would produce following result:
This is if statement
Example2:Write a program to print Student result status : studentmarks=80

if...else Statement: Syntax :


if(condition) {
Statement(s);
}
else {
Statement(s);
}
The statements inside “if” would execute if the condition is true, and the statements inside
“else” would execute if the condition is false.
Example: Write a program to print Student result status: totalMarks=35
public class ifelsestmt {
public static void main(String[] args) {
int totalMarks=35;
if(totalMarks>=36){
System.out.print("Student Passed");
}
else {
System.out.print("Student failed");
}
}
}
Example: Write a program to print status based on age details: age =10;

Mr. Suresh Page 31 of 139


Selenium Training by Suresh

Example: Write a program to print voter eligibility : age =20;

Example: Write a program to print driving licience eligibility : age =20;

Example: Write a program to check a value is divisible by Zero : a=15;

else if Statement:
if-else-if statement is used when we need to check multiple conditions. In this statement we
have only one “if” and one “else”, however we can have multiple “else if”. It is also known
as if else if ladder. This is how it looks:
if(condition_1) {
//if condition_1 is true execute this
statement(s);
}
else if(condition_2) {
Mr. Suresh Page 32 of 139
Selenium Training by Suresh
//execute this if condition_1 is not met and condition_2 is met
statement(s);
}
else if(condition_3) {
// execute this if condition_1 & condition_2 are not met and condition_3 is met
statement(s);
}
else {
// if none of the condition is true then these statements gets executed
statement(s);
}
Note: The most important point to note here is that in if-else-if statement, as soon as the
condition is met, the corresponding set of statements get executed, rest gets ignored. If none
of the condition is met then the statements inside “else” gets executed.
Example:
public class Test {
public static void main(String args[]){
int x = 30;
if( x = = 10 ){
System.out.print("Value of X is 10");
}else if( x = = 20 ){
System.out.print("Value of X is 20");
}else if( x = = 30 ){
System.out.print("Value of X is 30");
}else{
System.out.print("This is else statement");
}
}
}
Example: Write a program to print Grade details based on student marks: stdmarks=92

Example: Write a program to print status based on age details: age =10;

Mr. Suresh Page 33 of 139


Selenium Training by Suresh

Nested if...else Statement:


When there is an if statement inside another if statement then it is called the nested if
statement.
The structure of nested if looks like this:

if(condition_1) {
Statement1(s);

if(condition_2) {
Statement2(s);
}
}
Statement1 would execute if the condition_1 is true. Statement2 would only execute if both
the conditions( condition_1 and condition_2) are true.
Example:
public class Test {
public static void main(String args[]){
int x = 30; int y = 10;
if( x = = 30 ){
if( y = = 10 ){
System.out.print("X = 30 and Y = 10");
}
}
}
This would produce following result: X = 30 and Y = 10
Example: int age=27; int salary=50000;

Mr. Suresh Page 34 of 139


Selenium Training by Suresh

Loops:
Loops are used to execute a set of statements repeatedly until a particular condition is
satisfied. In Java we have three types of basic loops:
•while Loop
•do...while Loop
•for Loop
As of java 5 the enhanced foreach loop was introduced. This is mainly used for Arrays.

How while Loop works?


In while loop, condition is evaluated first and if it returns true then the statements inside
while loop execute. When condition returns false, the control comes out of loop and jumps to
the next statement after while loop.

Note: The important point to note when using while loop is that we need to use increment or
decrement statement inside while loop so that the loop variable gets changed on each
iteration, and at some point condition returns false. This way we can end the execution of
while loop otherwise the loop would execute indefinitely.
The syntax of a while loop is:
while(condition)
{
//Statements
//increment or decrement
}
Example:
public class Test {
public static void main(String args[]){
int x= 10;
while( x < 15 ){
System.out.println("value of x : " + x );
x++;
}
}
}
This would produce following result:
value of x : 10
value of x : 11
value of x : 12
Mr. Suresh Page 35 of 139
Selenium Training by Suresh
value of x : 13
value of x : 14
Example: write a program to print stmt for 10 times : “Java is very easy”

The do...while Loop:


do-while loop is similar to while loop, however there is a difference between them: In while
loop, condition is evaluated before the execution of loop’s body but in do-while loop
condition is evaluated after the execution of loop’s body.
Syntax:
do{
//Statements
//increment or decrement
}while(condition);
How do-while loop works?
First, the statements inside loop execute and then the condition gets evaluated, if the
condition returns true then the control gets transferred to the “do” else it jumps to the next
statement after do-while.
Example:
public class Test {
public static void main(String args[]){
int x= 10;
do{
System.out.println("value of x : " + x );
x++;
}while( x < =15 );
}
}
This would produce following result:
value of x : 10
value of x : 11
value of x : 12
value of x : 13
value of x : 14
value of x : 15
Example: write a program to print stmt for 10 times : “selenium is very very easy”

Mr. Suresh Page 36 of 139


Selenium Training by Suresh

The for Loop:


A for loop is a repetition control structure that allows you to efficiently write a loop that
needs to execute a specific number of times.A for loop is useful when you know how many
times a task is to be repeated.
Syntax:
for(initialization; condition ; increment/decrement)
{
statement(s);
}

For works as below:


First step: In for loop, initialization happens first and only one time, which means that the
initialization part of for loop only executes once.
Second step: Condition in for loop is evaluated on each iteration, if the condition is true then
the statements inside for loop body gets executed. Once the condition returns false, the
statements in for loop does not execute and the control gets transferred to the next statement
in the program after for loop.
Third step: After every execution of for loop’s body, the increment/decrement part of for
loop executes that updates the loop counter.
Fourth step: After third step, the control jumps to second step and condition is re-evaluated.
Example: public class Test {
public static void main(String args[]){
for(int x = 10; x < 20; x ++){
System.out.println("value of x : " + x );
}
}
Example: write a program to print numbers from 1 to 20 by increment of 2

Mr. Suresh Page 37 of 139


Selenium Training by Suresh
Break and Continue Keywords in JAVA
The break Keyword:
The break statement is usually used in following two scenarios:
a) Use break statement to come out of the loop instantly. Whenever a break statement is
encountered inside a loop, the control directly comes out of loop and the loop gets terminated
for rest of the iterations. It is used along with if statement, whenever used inside loop so that
the loop gets terminated for a particular condition.
b) It is also used in switch case control. Generally all cases in switch case are followed by a
break statement so that whenever the program control jumps to a case, it doesn’t execute
subsequent cases. As soon as a break is encountered in switch-case block, the control comes
out of the switch-case body.
Syntax: The syntax of a break is a single statement inside any loop: break;
Example:
public class Br {
public static void main(String args[]){
for(int i=10; i<=15; i++) {
if(i==13)
break;
System.out.println(i);
}
}
}
Outputshown as below
10
11
12

The continue Keyword:


Continue statement is mostly used inside loops. Whenever it is encountered inside a loop,
control directly jumps to the beginning of the loop for next iteration, skipping the execution
of statements inside loop’s body for the current iteration. This is particularly useful when you
want to continue the loop but do not want the rest of the statements (after continue statement)
in loop body to execute for that particular iteration.
Syntax:
The syntax of continue is a single statement inside any loop: continue;
Example:
public class Cnt {
public static void main(String args[]){
for(int i=10; i<=15; i++) {
if(i==13)
continue;
System.out.println(i);
}
}
}
Outputshown as below
10
Mr. Suresh Page 38 of 139
Selenium Training by Suresh
11
12
14
15

Arrays in Java
Arrays: - Group of similar elements
Java provides a data structure, the array, which stores a fixed-size sequential collection of
elements of the same type. An array is used to store a collection of data, but it is often more
useful to think of an array as a collection of variables of the same type.
Instead of declaring individual variables, such as number0, number1, ..., and number99, you
declare one array variable such as numbers and use numbers[0], numbers[1], and ...,
numbers[99] to represent individual variables.
Syntax : datatype array name = array values
Int myList[] = {5,6,4,5,3---11}
Example: Following statement declares an array variable, myList, creates an array of 10
elements of double type, and assigns its reference to myList.
double[] myList = new double[10];
Following picture represents array myList. Here myList holds ten double values and the
indices are from 0 to 9.

Processing Arrays: When processing array elements, we often use either for loop or foreach
loop because all of the elements in an array are of the same type and the size of the array is
known.
Note: The array elements can be accessed with the help of the index,Accessing the array with
an index greater than or equal to the size of the array leads to NullPointer Exception.
The foreach Loops: For-each is another array traversing technique like for loop, while loop,
do-while loop introduced in Java5. It starts with the keyword for like a normal for-
loop.Instead of declaring and initializing a loop counter variable, you declare a variable that
is the same type as the base type of the array, followed by a colon, which is then followed by
the array name.In the loop body, you can use the loop variable you created rather than using
an indexed array element.It’s commonly used to iterate over an array or a Collections class
(eg, ArrayList)
Syntax: for (type var : array) {
statements using var;
}
Sample Program for Arrays & For Each Loop
public class Foreach1 {
public static void main(String[] args) {
Mr. Suresh Page 39 of 139
Selenium Training by Suresh
int myList[] = {10, 20, 30, 40 ,50,60};
// Print all the array elements
for (int element: myList) {
System.out.println(element);
}
}
}
Example : write a program to print all the elements from below array.
// String data[] ={"selenium","training",”by”,"suresh”};

ArrayList in Java
ArrayList is a part of collection framework and is present in java.util package.ArrayList is
initialized by a size; however the size can increase if collection grows or shrunk if objects are
removed from the collection.
Example:
import java.util.ArrayList;
public class ArrayListExp {
public static void main(String args[]) {
ArrayList<String> subjects = new ArrayList<String>();
subjects.add("Mat");
subjects.add("sci");
subjects.add("eng");
subjects.add("tel");
System.out.println(subjects);
subjects.add(2,"hin");
System.out.println(subjects);
}
}
Example: Create an arrayList with Selenium components details and print the same.

Mr. Suresh Page 40 of 139


Selenium Training by Suresh
Program for taking the inputs from key board (or) accepting the values in run time
(Example: Addition of 2 numbers)
Import java.util.Scanner;
Class AddNumbers {
Public static void main (String args []) {
Int x, y, z;
System.out.println ("Enter two integers to calculate their sum ");
Scanner in = new Scanner (System.in);
x = in.nextInt (); //nextInt is a pre-defined function which is used to accept only integer
values
y = in.nextInt ();
z = x + y;
System.out.println ("Sum of entered integers = "+z);
}
}
Outputshown as below:
Enter two integers to calculate their sum
10
20
Sum of entered integers = 30

Write a java program to perform substract two numbers by accepting the values from
keyboard

Mr. Suresh Page 41 of 139


Selenium Training by Suresh
The switch Statement: Switch case statement is used when we have number of options (or
choices) and we may need to perform a different task for each choice.
Syntax : switch (variable or an integer expression) {
case constant:
//Java code
break;
case constant:
//Java code
break;
default:
//Java code ;
}
Break statement is optional in switch case but you would use it almost every time you deal
with switch case.
break keyword in default block :
The control would itself come out of the switch after default so I didn’t use it, however if you
still want to use the break after default then you can use it, there is no harm in doing that.
Few points about Switch Case
1) Case doesn’t always need to have order 1, 2, 3 and so on. It can have any integer value
after case keyword. Also, case doesn’t need to be in an ascending order always, you can
specify them in any order based on the requirement.
2) You can also use characters in switch case.
import java.util.Scanner;
public class SwitchExp {
public static void main(String args[]) {
Scanner sc= new Scanner(System.in);
System.out.println("1.Add");
System.out.println("2.sub");
System.out.println("3.mul");
System.out.println("4.div");
System.out.println("Enter first number");
int a = sc.nextInt();
System.out.println("Enter second number");
int b = sc.nextInt();
System.out.println("Enter your choice");
int ch = sc.nextInt();
switch(ch){
case 1:
System.out.println(a+b);
break;
case 2:
System.out.println(a-b);
break;
case 3:
System.out.println(a*b);
break;
case 4:
Mr. Suresh Page 42 of 139
Selenium Training by Suresh
System.out.println(a/b);
break;
default:
System.out.println("Invalid choice");
}
}
}

Sample Program: Reverse of the String –


public class StringRev {
public static void main(String[] args)
{
String text = "suresh";
String reverse = "";
for(int i=text.length()-1; i>=0; i--) {
reverse = reverse + text.charAt(i);
}
System.out.println("Reversed string is:" + reverse );
System.out.println("reverse completed");
}
}
Sample program : multiplication table of given number
import java.util.Scanner;
public class Table {
public static void main(String args[]) {
int n, c;
System.out.println("Enter an integer to print it's multiplication table");
Scanner in = new Scanner(System.in);
n = in.nextInt();
System.out.println("Multiplication table of " + n + " is : ");
for (c = 1; c <= 10; c++)
System.out.println(n + "*" + c + " = " + (n*c));
}
}

Inheritance
The process by which one class acquires the properties (data members) and functionalities
(methods) of another class is called inheritance. The aim of inheritance is to provide the
reusability of code so that a class has to write only the unique features and rest of the
common properties and functionalities can be extended from the another class.
Child Class: The class that extends the features of another class is known as child class, sub
class or derived class.
Parent Class: The class whose properties and functionalities are used(inherited) by another
class is known as parent class, super class or Base class.
Note: The biggest advantage of Inheritance is that the code that is already present in base
class need not be rewritten in the child class.This means that the data members(instance
variables) and methods of the parent class can be used in the child class as.
Mr. Suresh Page 43 of 139
Selenium Training by Suresh
Syntax: Inheritance in Java
To inherit a class we use extends keyword. Here class B is child class and class A is parent
class. The class B is inheriting the properties and methods of A class.
class B extends A
{

The following kinds of inheritance are there in java.


 Single level Inheritance
 Multilevel Inheritance
 multiple Inheritance(Java does not support)

Single Inheritance
When a class extends another one class only then we call it a single inheritance. The below
flow diagram shows that class B extends only one class which is A. Here A is a parent class
of B and B would be a child class of A.

Example:
class A {
public void test () {
System.out.println ("Hai...");
System.out.println("parent class");
}
}
public class B extends A {
public static void main (String [] args){
B s= new B ();
s.test ();
}
}
Multilevel Inheritance : Multilevel inheritance refers - where one can inherit from a derived
class, thereby making this derived class the base class for the new class. As you can see in
below flow diagram C is subclass or child class of B and B is a child class of A, Multilevel
inheritance can go up to any number of levels.

Mr. Suresh Page 44 of 139


Selenium Training by Suresh

class A {
int a=10;
int b=20;
public void selIDE(){
System.out.println("IDE");
}

}
class B extends A{
int x=30;
int y=40;
public void selWD(){
System.out.println("WD");
System.out.println(a+b); //accessing from class A
}
}
public class C extends B{
public void selRC(){
System.out.println("RC");
System.out.println(x+y); //accessing from class B
System.out.println(a+b); //accessing from class A
}
public static void main(String args[]){
C obj = new C();
obj.selIDE(); //accessing methods of class A without creating object for class A
obj.selWD(); //accessing methods of class A without creating object for class B
obj.selRC();
}
}

Polymorphism in JAVA :
Polymorphism: It means one name with many forms.
These are 2 types:
 Method Over loading
 Method Over riding
Method Overloading
 Writing two or more methods in the same class in such way that each method has
same name but with different method signatures
Mr. Suresh Page 45 of 139
Selenium Training by Suresh
Method Overriding
 Writing two or more methods in super and sub classes such that the methods have
same name and same signature
Method Overloading (Writing two or more methods in the same class in such way that each
method has same name but with different method signatures)
As we know that a method has its own signature which is known by method's name and the
parameter types. Java has a powerful feature which is known as method overloading. With
the help of this feature we can define two methods of same name with different parameters. It
allows the facility to define that how we perform the same action on different type of
parameter.
Example: public class OverLoad {
public void add(int a,int b){
System.out.println(a+b);
}
public void add(int a,int b ,int c){
System.out.println(a+b+c);
}
public static void main(String args[]){
OverLoad obj = new OverLoad();
obj.add(10, 20);
obj.add(10, 20, 30);
}
}
Overriding (Writing two or more methods in super and sub classes such that the methods
have same name and same signature)
Method overriding in java means a subclass method overriding a super class method. Super
class method should be non-static. Subclass uses extends keyword to extend the super class.
In overriding methods of both subclass and super class possess same signatures. Overriding is
used in modifying the methods of the super class.
Example:
public class OverRide {
public void add(int a,int b){
System.out.println(a+b);
}
}
//Create new class as OverRide1
public class OverRide1 extends OverRide{
public void add(int a,int b){
System.out.println(a-b);
}
public static void main(String args[]){
OverRide1 obj1 = new OverRide1();
obj1.add(10, 20);
OverRide obj = new OverRide();
obj.add(10, 20);
}
}
Mr. Suresh Page 46 of 139
Selenium Training by Suresh
Encapsulation & Abstraction in JAVA
Encapsulation – Data Bind
Encapsulation is a process of binding or wrapping the data and the codes that operates on the
data into a single entity. Eg: class
Example: class Person{
//variable - data
private String name = "Suresh";
private int age = 26;
//method
public void talk() {
System.out.println("Hello ,Iam"+name);
System.out.println("My age is"+age);
} public static void main(String args[]){
Person p = new Person();
p.talk();
}
}
Abstraction: Data Hide
A class that is declared using “abstract” keyword is known as abstract class. It can have
abstract methods (methods without body) as well as concrete methods (regular methods with
body). A normal class (non-abstract class) cannot have abstract methods.
“Data abstraction is a mechanism of retrieving the essential details without dealing with
background details”.
•To use use abstraction we need use abstract keyword in the class
•For abstracts method implementation will be available in other class
•We can’t create any object for abstract class.To get the access for abstract methods will use
inherit those abstract classes.
Example
abstract class Bank {
abstract void credit();
abstract void debit();
}
class HDFC extends Bank{
void credit() {
System.out.println("Amount credit from HDFC");
}
void debit() {
System.out.println("Amount debited from HDFC");
}
}
class ICICI extends Bank{
void credit() {
System.out.println("Amount credit from ICICI");
}
void debit() {
System.out.println("Amount debited from ICICI");
Mr. Suresh Page 47 of 139
Selenium Training by Suresh
}
}
public class TestBank{
public static void main(String args[]) {
HDFC h = new HDFC();
h.credit();
h.debit();
ICICI i = new ICICI();
i.credit();
i.debit();
}
}

Interface in JAVA
Interface : Interface looks like a class but it is not a class. An interface can have methods and
variables just like the class but the methods declared in interface are by default abstract (only
method signature, no body) the variables declared in an interface are public, static & final by
default.
 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 inheritance in Java.
 Interface definition begins with a keyword interface.
 An interface like that of an abstract class cannot be instantiated.
Example :
interface WebDriver{
public void get();
public void close();
}
class FirefoxDriver implements WebDriver{
public void get() {
System.out.println("TO open Application in firefox browser");
}
public void close() {
System.out.println("TO open Application in firefox browser");
}
}
public class ChromeDriver implements WebDriver {
public void get() {
System.out.println("TO open Application in chrome browser");
}
public void close() {
System.out.println("To close Application in chrome browser");
}
public static void main(String args[]) {
//Creating object for ChromeDriver class directly
ChromeDriver driver = new ChromeDriver();
Mr. Suresh Page 48 of 139
Selenium Training by Suresh
driver.get();
driver.close();
//Creating object for WebDriver(interface) indirectly - with the reference of ChromeDriver
class
WebDriver driver2 = new ChromeDriver();
driver2.get();
driver2.close();
//Creating object for FirefoxDriver class directly
FirefoxDriver ff = new FirefoxDriver();
ff.get();
ff.close();
//Creating object for WebDriver(interface) indirectly - with the reference of FirefoxDriver
class
WebDriver f = new FirefoxDriver();
f.get();
f.close();
}
}

Exception Handling in JAVA


What is an exception?
An Exception is an unwanted event that interrupts the normal flow of the program. When an
exception occurs program execution gets terminated. In such cases we get a system generated
error message. The good thing about exceptions is that they can be handled in Java. By
handling the exceptions we can provide a meaningful message to the user about the issue
rather than a system generated message, which may not be understandable to a user.
Why an exception occurs?
There can be several reasons that can cause a program to throw exception. For example:
Opening a non-existing file in your program, Network connection problem, bad input data
provided by user etc.
Exception Hierarchy: All exception classes are subtypes of the java.lang.Exception class.

Example for Try & Catch Block


public class ExcepTest{
public static void main(String args[]) {
try {
int b=10/0;

Mr. Suresh Page 49 of 139


Selenium Training by Suresh
System.out.println(b);
}
catch(Exception e) {
System.out.println( "Exception thrown :" + e);
}
System.out.println("Out of the block");
}
}
Example for Try & Catch & Finally Block
public class Final{
public static void main(String args[]){
int a[] = {10,20,30,40};
try {
System.out.println("Access element three :" + a[2]);
System.out.println("Testing");
}
catch(Exception e) {
System.out.println("Exception thrown123 :" + e);
}
finally {
System.out.println("First element value: " +a[1]);
System.out.println("The finally statement is executed");
}
}
}
Some More Details information on Exception Handling
An exception is a problem that arises during the execution of a program. An exception can
occur for many different reasons, including the following:
•A user has entered invalid data.
•A file that needs to be opened cannot be found.
•A network connection has been lost in the middle of communications, or the JVM has run
out of memory.
Some of these exceptions are caused by user error, others by programmer error, and others by
physical resources that have failed in some manner.
To understand how exception handling works in Java, you need to understand the three
categories of exceptions:
Checked exceptions: A checked exception is an exception that is typically a user error or a
problem that cannot be foreseen by the programmer. For example, if a file is to be opened,
but the file cannot be found, an exception occurs. These exceptions cannot simply be ignored
at the time of compilation.
Runtime exceptions: A runtime exception is an exception that occurs that probably could
have been avoided by the programmer. As opposed to checked exceptions, runtime
exceptions are ignored at the time of compliation.
Errors: These are not exceptions at all, but problems that arise beyond the control of the user
or the programmer. Errors are typically ignored in your code because you can rarely do
anything about an error. For example, if a stack overflow occurs, an error will arise. They are
also ignored at the time of compilation.
Mr. Suresh Page 50 of 139
Selenium Training by Suresh
Exception Hierarchy:
All exception classes are subtypes of the java.lang.Exception class. The exception class is a
subclass of the Throwable class. Other than the exception class there is another subclass
called Error which is derived from the Throwable class.
Errors are not normally trapped form the Java programs. These conditions normally happen
in case of severe failures, which are not handled by the java programs. Errors are generated to
indicate errors generated by the runtime environment. Example: JVM is out of Memory.
Normally programs cannot recover from errors.
The Exception class has two main subclasses: IOException class and RuntimeException
Class.
Catching Exceptions: A method catches an exception using a combination of the try and
catch keywords. A try/catch block is placed around the code that might generate an
exception. Code within a try/catch block is referred to as protected code, and the syntax for
using try/catch looks like the following:
try{
//Protected code
}catch(ExceptionName e1){
//Catch block
}
A catch statement involves declaring the type of exception you are trying to catch. If an
exception occurs in protected code, the catch block (or blocks) that follow the try is checked.
If the type of exception that occurred is listed in a catch block, the exception is passed to the
catch block much as an argument is passed into a method parameter.
Example: The following is an array is declared with 2 elements. Then the code tries to access
the 3rd element of the array which throws an exception.
// File Name : ExcepTest.java
import java.io.*;
public class ExcepTest{
public static void main(String args[]){
try{
int a[] = new int[2];
System.out.println("Access element three :" + a[3]);
}catch(ArrayIndexOutOfBoundsException e){
System.out.println("Exception thrown :" + e);
}
System.out.println("Out of the block");
}
}
This would produce following result:
Exception thrown :java.lang.ArrayIndexOutOfBoundsException: 3
Out of the block
Multiple catch Blocks:A try block can be followed by multiple catch blocks. The syntax for
multiple catch blocks looks like the following:
try{
//Protected code
}catch(ExceptionType1 e1){
//Catch block
Mr. Suresh Page 51 of 139
Selenium Training by Suresh
}catch(ExceptionType2 e2){
//Catch block
}catch(ExceptionType3 e3)
{
//Catch block
}
The previous statements demonstrate three catch blocks, but you can have any number of
them after a single try. If an exception occurs in the protected code, the exception is thrown
to the first catch block in the list. If the data type of the exception thrown matches
ExceptionType1, it gets caught there. If not, the exception passes down to the second catch
statement. This continues until the exception either is caught or falls through all catches, in
which case the current method stops execution and the exception is thrown down to the
previous method on the call stack.
Example: Here is code segment showing how to use multiple try/catch statements.
class ex{
public static void main(String[] args) {
try {
//open the files
System.out.println("open files");
//do some processing
int n = 0;
//System.out.println("n= "+ n);
int a = 45/n;
System.out.println("a= "+ a);
int b[] = {10,20,30};
b[50] = 100;
}
catch (ArithmeticException ae) {
//display the exception details
System.out.println(ae);
//display any message to the user
System.out.println("Please pass data while running this program");
}
catch(ArrayIndexOutOfBoundsException aie) {
//diaplay exception details
aie.printStackTrace();
//display a message to user
System.out.println("please see that the array index is within the range");
}

} }
The throws/throw Keywords: If a method does not handle a checked exception, the method
must declare it using the throws keyword. The throws keyword appears at the end of a
method's signature.
You can throw an exception, either a newly instantiated one or an exception that you just
caught, by using the throw keyword. Try to understand the different in throws and throw
keywords.
Mr. Suresh Page 52 of 139
Selenium Training by Suresh
The following method declares that it throws a Remote Exception:
import java.io.*;
public class className{
public void deposit(double amount) throws RemoteException {
// Method implementation
throw new RemoteException();
}
//Remainder of class definition
}
A method can declare that it throws more than one exception, in which case the exceptions
are declared in a list separated by commas. For example, the following method declares that
it throws a Remote Exception and an InsufficientFundsException:
Import java.io.*;
public class className{
public void withdraw(double amount) throws RemoteException,
InsufficientFundsException {
// Method implementation
}
//Remainder of class definition
}
The finally Keyword The finally keyword is used to create a block of code that follows a try
block. A finally block of code always executes, whether or not an exception has occurred.
Using a finally block allows you to run any cleanup-type statements that you want to execute,
no matter what happens in the protected code.
A finally block appears at the end of the catch blocks and has the following syntax:
try{
//Protected code
}catch(ExceptionType1 e1) {
//Catch block
}catch(ExceptionType2 e2) {
//Catch block
}catch(ExceptionType3 e3) {
//Catch block
}finally {
//The finally block always executes.
}
Example: public class Final{
public static void main(String args[]){
int a[] = new int[2];
try{
System.out.println("Access element three :" + a[3]);
}catch(ArrayIndexOutOfBoundsException e){
System.out.println("Exception thrown :" + e);
}
finally{
a[0] = 6;
System.out.println("First element value: " +a[0]);
Mr. Suresh Page 53 of 139
Selenium Training by Suresh
System.out.println("The finally statement is executed");
}
}
}
This would produce following result:
Exception thrown :java.lang.ArrayIndexOutOfBoundsException: 3
First element value: 6
The finally statement is executed
Note the followings:
•A catch clause cannot exist without a try statement.
•It is not compulsory to have finally clauses whenever a try/catch block is present.
•The try block cannot be present without either catch clause or finally clause.
•Any code cannot be present in between the try, catch, finally blocks.

JAVA Assignment
Write a sample java program to Print the statement as – “ *** I have not failed. I've just
found 10,000 ways that won't work *** ”

Create One Class, three Methods and print below stmt.


Method1 - Failure is the key to success; each mistake teaches us something.
Method2 - Coming together is a beginning; keeping together is progress; working together is
success.
Method3 - In a day, when you don't come across any problems - you can be sure that you are
travelling in a wrong path

Mr. Suresh Page 54 of 139


Selenium Training by Suresh

Create One Class, three static Methods and print below stmt.
Method1 – Daily I will practice selenium for 2 hours.
Method2 – Daily I will sleep only for 6 hours.
Method3 – Daily I will wake up at 6 clock

Write a Java program to find given number is - odd or even

Mr. Suresh Page 55 of 139


Selenium Training by Suresh

Write a program to swap the two numbers

Write a program to print reverse of the number

Print below format using for loop


*
**
***
****
*****

Mr. Suresh Page 56 of 139


Selenium Training by Suresh

Write a program to print the each element from the below array using for each loop
int arr[]={12,13,14,44};
String s1[]={“Suresh”,”selenium”,”project”,”training”}

Write a program to add list of element to array list and print the same- Selenium
,Training ,By ,Suresh.

Write a program to Choose Day of the Week using switch stmt

Mr. Suresh Page 57 of 139


Selenium Training by Suresh

 Write any example for single level and multilevel inheritance


 Write any example for Method Overload and Method Overriding
 Write any example for abstraction
 Write any example for encapsulation
 Write any example for interface
 Write any example for Exception handling

Mr. Suresh Page 58 of 139


Selenium Training by Suresh
Selenium 3 / WebDriver
Introducing Web Driver & Architecture
WebDriver - Introduction
 Web Driver is designed to providing a simpler, more concise programming interface
along with addressing some limitations in the Selenium-RC API.
 Developed to better support dynamic web pages where elements of a page may
change without the page itself being reloaded
 Makes direct calls to the browser using each browser’s native support for automation.

WebDriver is one Interface and its had below implementing classes


Implementing Classes
 ChromeDriver,
 EdgeDriver,
 EventFiringWebDriver,
 FirefoxDriver,
 HtmlUnitDriver,
 InternetExplorerDriver,
 MarionetteDriver,
 OperaDriver, RemoteWebDriver, SafariDriver

Diffirence between SeleniumRC and WebDriver


Selenium RC WebDriver
Workson almost all browsers.Does not work Works on latest versions of almost all
on latest version of Firefox/IE browsers - Firefox, IE(6,7,8), Opera,
Chrome
No Record and run No Record and run
Server is required to start No server required to start
Core engine is JavaScript based Interacts natively with browser application
Its a simple and small API Complex and a bit large API as compared to
RC
Less Object oriented API Purely Object oriented API
Cannot move mouse with it Can move mouse cursor
Full xpaths have to be appended with No need to append 'xpath=\\'
'xapth=\\' syntax
No Listeners Implementation of Listeners is provided
Selenium RC Cannot be used to Test iPhone WebDriver can be used to Test iPhone or
or Android Apps Android Apps
Mr. Suresh Page 59 of 139
Selenium Training by Suresh
General Example for SeleniumRC WebDriver

Design of WebDriver interface:

WebDriver driver = new FirefoxDriver();


driver.get();
FirefoxDriver driver1 = new FirefoxDriver();
driver1.get();
 From the above diagram driver object is related to webdriver interface and driver1
object related to FirefoxDriver class. But both objects can run method bodies in
FirefoxDriver class, because ChromeDriver is Concrete class for WebDriver
interface.
 Because of this webdriver interface facility in feature if any new things need to get
added that will be introduced as one more new Driver class.

Note: Before writing webdriver program makes sure that you added webdriver jar files to
project.
Steps to add Jar files to project
1. Create new java project
2. Right click on created project
3. Select Build path option and click on Configure build path option
4. Click on libraries Tab
Mr. Suresh Page 60 of 139
Selenium Training by Suresh
5. Click on Add external jar file button
6. Browse Webdriver jar files
7. Click on Open button
8. Click on Apply and close button

HRMS – Project Test Cases :

TC-Example for FirefoxDriver(firefox browser)


import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.By;
public class TC_101 {
public static void main(String args[]) throws Exception{
System.setProperty(“webdriver.gecko.driver”,”E:\\geckodriver.exe”);
WebDriver driver = new FirefoxDriver();
//TestCase steps
driver.get("http://127.0.0.1/orangehrm-2.6/login.php");
driver.findElement(By.name("txtUserName")).sendKeys("admin");
driver.findElement(By.xpath("//input[@name='txtPassword']")).sendKeys("admin");
driver.findElement(By.name("Submit")).click();
Thread.sleep(3000);
Mr. Suresh Page 61 of 139
Selenium Training by Suresh
System.out.println("Login completed");
driver.findElement(By.linkText("Logout")).click();
System.out.println("Logout completed");
driver.quit();
}
}

TC-Example for ChromeDriver(chrome browser)


import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class TC_101 {
public static void main(String args[])throws Exception {
System.setProperty(“webdriver.chrome.driver”,”E:\\chromedriver.exe”);
WebDriver driver=new ChromeDriver();
driver.get("http://127.0.0.1/orangehrm-2.6/login.php");
driver.findElement(By.name("txtUserName")).sendKeys("admin");
driver.findElement(By.name("txtPassword")).sendKeys("admin");
driver.findElement(By.name("Submit")).click();
Thread.sleep(2000);
driver.findElement (By.linkText ("Logout"));
driver.close();
}
}

Example to Verify the application title and calling test data by using variables
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.By;
public class TC_Verify {
public static String un = "admin";
public static String pw = "admin";
public static void main(String args[]) throws Exception{
System.setProperty(“webdriver.gecko.driver”,”E:\\geckodriver.exe”);
WebDriver driver = new FirefoxDriver();
//Test Case steps
driver.navigate().to("http://127.0.0.1/orangehrm-2.6/login.php");
if(driver.getTitle().equals("OrangeHRM - New Level of HR Management")) {
System.out.println("Title matched");
}
else {
System.out.println("Title not matched and expected title is "+driver.getTitle());
}
driver.findElement(By.xpath("//input[@name='txtUserName']")).sendKeys(un);
driver.findElement(By.xpath("//input[@name='txtPassword']")).sendKeys(pw);
driver.findElement(By.name("Submit")).click();
Thread.sleep(3000);
Mr. Suresh Page 62 of 139
Selenium Training by Suresh
System.out.println("Login completed");
driver.findElement(By.linkText("Logout")).click();
System.out.println("logout completed");
driver.quit();
}
}

Mouse Over Actions in WebDriver


To perform mouseover, first we identify the element to be hovered in the web page and then
we perform the action of movetoelement using Actions class provided in WebDriver
Syntax : import org.openqa.selenium.interactions.Actions;
WebElement element = driver.findElement(By.linkText("PIM"));
Actions action = new Actions(driver);
action.moveToElement(element).build().perform();
The 'build()' method is used to compile all the list of actions into a single step and ready to be
performed.
// Example to perform mouseover on PIM main menu and click on AddEmployee link
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.interactions.Actions;
public class mainmenu_MouseOver{
public static void main(String args[]) {
System.setProperty(“webdriver.gecko.driver”,”E:\\geckodriver.exe”);
WebDriver driver =new FirefoxDriver();
driver.navigate().to("http://127.0.0.1/orangehrm-2.6/login.php");
driver.manage().window().maximize();
Thread.sleep(3000L);
driver.findElement(By.name("txtUserName")).sendKeys("suresh");
driver.findElement(By.name("txtPassword")).sendKeys("suresh123");
driver.findElement(By.name("Submit")).click();
Thread.sleep(3000);
//mouseover on pim mainmenu
WebElement element = driver.findElement(By.linkText("PIM"));
Actions action = new Actions(driver);
action.moveToElement(element).perform();
Thread.sleep(3000L);
//clicking on addemployee submenu link
driver.findElement(By.linkText("Add Employee")).click();
Thread.sleep(3000);
System.out.println("Clicked on submenu");
driver.quit();
}
}

Mr. Suresh Page 63 of 139


Selenium Training by Suresh
For practice Test case steps:

What is Iframe?
A web page which is embedded in another web page or an HTML document embedded
inside another HTML document is known as a frame.
The IFrame is often used to insert content from another source, such as an advertisement, into
a Web page. The <iframe> tag specifies an inline frame.
How to identify the frame ?
Perform inspect Element and Search with the ‘frame’/ 'iframe', if you can find any tag name
with the ‘frame’/ 'iframe' then it is meaning to say the page consisting an frame/ iframe.
Methods to handle frames
To Enter – driver.switchTo().frame(“framename/frameid/index”)
To Exit - driver.switchTo().defaultContent()

//Example for Frames & VerifyText & Reading the data from Textbox
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import static org.testng.Assert.assertTrue;
public class AddEmp {
public static void main(String[] args) throws InterruptedException {
System.setProperty(“webdriver.gecko.driver”,”E:\\geckodriver.exe”);
WebDriver driver=new FirefoxDriver();
driver.navigate().to("http://127.0.0.1/orangehrm-2.6/login.php");
driver.findElement(By.xpath("//input[@type='text']")).sendKeys("suresh");
driver.findElement(By.xpath("//input[@type='password']")).sendKeys("suresh123");

Mr. Suresh Page 64 of 139


Selenium Training by Suresh
driver.findElement(By.xpath("//input[@type='Submit']")).click();
Thread.sleep(5000L);
//Verifying Text
assertTrue(driver.findElement(By.xpath("//ul[@id='option-
menu']/li")).getText().matches("Welcome suresh"));
//Selecting the frame
driver.switchTo().frame("rightMenu"); //Enter into Frame
//Clicking on Add Button
driver.findElement(By.xpath("//*[@id='standardView']/div[3]/div[1]/input[1]")).click();
Thread.sleep(2000L);
//To retrive the data from empid textbox
String empid=driver.findElement(By.xpath("//form[@id='frmEmp']/div/div/div[2]/input")).
getAttribute("value");
System.out.println(empid);
driver.findElement(By.xpath("//*[@id='txtEmpLastName']")).sendKeys("suresh");
Thread.sleep(2000L);
driver.findElement(By.xpath("//*[@name='txtEmpFirstName']")).sendKeys("selenium");
driver.findElement(By.xpath("//*[@id='btnEdit']")).click();
Thread.sleep(2000L);
System.out.println("New Employee Added");
driver.switchTo().defaultContent(); //Exit from Frame
driver.findElement(By.xpath("//*[@id='option-menu']/li[3]/a")).click();
driver.quit();
}
}

Alerts in WebDriver
What is Alert?
Alert is a small message box which displays on-screen notification to give the user some kind
of information or ask for permission to perform certain kind of operation. It may be also used
for warning purpose.
Here are few alert scenarios
1)Simple Alert --This simple alert displays some information or warning on the screen.

2) Prompt Alert--This Prompt Alert asks some input from the user and selenium webdriver
can enter the text using sendkeys(" text to enter").

Mr. Suresh Page 65 of 139


Selenium Training by Suresh

3) Confirmation Alert--This confirmation alert asks permission to do some type of operation.

Syntax :
import org.openqa.selenium.Alert;
Alert alert = driver.switchTo().alert();
Alert is an interface. below are the methods that are used to handle the alerts
To Click on OK button. - alert.accept();
To click on Cancel button - alert.dismiss()
To get the text which is present on the Alert. - alert.getText();
To pass the text to the prompt popup - alert.sendkeys();
Example for alerts
import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class PopUp {
public static void main(String args[])throws Exception {
System.setProperty(“webdriver.gecko.driver”,”E:\\geckodriver.exe”);
WebDriver driver =new FirefoxDriver ();
driver.get ("http://127.0.0.1/orangehrm-2.6/login.php");
System.out.println (driver.getTitle ());
Mr. Suresh Page 66 of 139
Selenium Training by Suresh
driver.findElement (By.name ("txtUserName")).sendKeys ("suresh");
driver.findElement (By.name ("Submit")).click ();
Thread.sleep (2000L);
Alert a= driver.switchTo ().alert ();
System.out.println (a.getText ());
a.accept ();
driver.findElement (By.name ("txtPassword")).sendKeys ("suresh123");
driver.findElement (By.name ("Submit")).click ();
Thread.sleep (2000);
System.out.println ("Login completed");
driver.findElement (By.linkText ("Logout")).click ();
driver.quit ();
}
}

Mr. Suresh Page 67 of 139


Selenium Training by Suresh
Keyboard Actions – Robot Class
Java.awt.Robot class is used to take the control of mouse and keyboard. Once you get the
control, you can do any type of operation related to mouse and keyboard through your java
code. This class is used generally for test automation.
Eg:
import java.awt.Robot;
import java.awt.event.KeyEvent;
Robot r = new Robot();
To press TAB key from keyboard
r.keyPress(KeyEvent.VK_TAB);
r.keyRelease(KeyEvent.VK_TAB);
To Press ENTER Key from Keyboard
r.keyPress(KeyEvent.VK_ENTER);
r.keyRelease(KeyEvent.VK_ENTER);
//Example to perform Keyboard activities using Robot Class
import java.awt.Robot;
import java.awt.event.KeyEvent;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class TC_Robotclass {
public static void main(String args[]) throws Exception{
//Test case steps
System.setProperty("webdriver.gecko.driver",
"D:\\Suresh_Selenium\\Drivers\\geckodriver.exe");
WebDriver driver = new FirefoxDriver();
driver.get("http://127.0.0.1/orangehrm-2.6/login.php");
System.out.println("Application Opened");
driver.findElement(By.name("txtUserName")).sendKeys("admin");
driver.findElement(By.xpath("//input[@name='txtPassword']")).sendKeys("admin");
//Perform TAB & Enter using KeyBoard actions
Robot r = new Robot();
r.keyPress(KeyEvent.VK_TAB);
r.keyRelease(KeyEvent.VK_TAB);

r.keyPress(KeyEvent.VK_ENTER);
r.keyRelease(KeyEvent.VK_ENTER);
Thread.sleep(3000L);
System.out.println("Login completed");
driver.findElement(By.linkText("Logout")).click();
System.out.println("Logout completed");
driver.quit();
}
}

Mr. Suresh Page 68 of 139


Selenium Training by Suresh
//Example to perform keyboard activities using WebDriver and Auto Complete
Feature
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class AutoComplete{
public static void main(String args[]) throws Exception {
System.setProperty(“webdriver.gecko.driver”,”E:\\geckodriver.exe”);
WebDriver driver = new FirefoxDriver();
driver.navigate().to("https://www.google.co.in");
Thread.sleep(3000);
driver.findElement(By.name("q")).sendKeys("selenium suresh");
Thread.sleep(5000);
driver.findElement(By.name("q")).sendKeys(Keys.ARROW_DOWN);
Thread.sleep(3000);
System.out.println("Firsttime down arrow pressed");
driver.findElement(By.name("q")).sendKeys(Keys.ARROW_DOWN);
Thread.sleep(3000);
System.out.println("Second time down arrow pressed");
driver.findElement(By.name("q")).sendKeys(Keys.ENTER);
Thread.sleep(3000);
System.out.println("clicked on Enter btn");
driver.quit();
}
}

Dropdown and Navigate Methods


WebDriver’s support classes called “Select”, which provides useful methods for interacting
with select options. User can perform operations on a select dropdown and also de-select
operation using the below methods.
import org.openqa.selenium.support.ui.Select;
Select lstbox = new Select(driver.findElement(By.id(“dropdownid")));
Method Name: selectByVisibleText
lstbox.selectByVisibleText(“Text");
Method Name: selectByIndex
lstbox.selectByIndex(index);
Method Name: selectByValue
lstbox.selectByValue(value);
Method Name: deselectByIndex
lstbox.deselectByIndex(index);
Navigate Methods
navigate.back()
navigate.forword()
navigate.to()

Mr. Suresh Page 69 of 139


Selenium Training by Suresh
//Example to select single value & Multipul values from dropdown
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.Select;
public class TC_102_Verify {
public static void main(String[] args) throws InterruptedException {
System.setProperty("webdriver.gecko.driver",
"D:\\Suresh_Selenium\\Drivers\\geckodriver.exe");
WebDriver driver=new FirefoxDriver();
driver.navigate().to("file:///D:/Suresh_Selenium/HtmlFile/dropdownNavigate.html");
//selecting single value from dropdown
Select drpdwn = new Select(driver.findElement(By.name("OptWeb")));
drpdwn.selectByVisibleText("Google");
driver.findElement(By.xpath ("html/body/form/input")).click();
Thread.sleep (5000L);
System.out.println(driver.getTitle());
driver.navigate().back();
Thread.sleep(5000L);
//Selecting multipul Values from dropdown
driver.navigate().to("file:///D:/Suresh_Selenium/HtlFi/multiselectdropdown.html");
Select lstbox = new Select(driver.findElement (By.id("tools")));
lstbox.selectByVisibleText("Selenium IDE");
System.out.println("Selected is - Selenium IDE");
lstbox.selectByIndex(1);
System.out.println("Selected is - Selenium RC");
Thread.sleep(3000L);
driver.quit();
}
}

Mr. Suresh Page 70 of 139


Selenium Training by Suresh

WaitMethods (or) Synchronization


It is a mechanism which involves more than one component to work parallel with Each other.
Thread.sleep()
In this we just specify timeout value only. We will make the tool to wait until certain amount
of time and then proceed further.
Implicit Wait: WebDriver waits for an element if they are not immediately available. So,
WebDriver does not throw NoSuchElementException immediately. This is known as
implicitlyWait()
Syntax : driver.manage.TimeOuts.implicitwait(10,Timeunit.SECONDS);
Here we wait for 10 seconds, after that it gives NoSuchElementException. If the element
present in 5 second then it should not wait for another 10 seconds.
Explicit Wait: Using Explicit Wait, we can tell WebDriver to wait for a certain condition to
occur before proceeding further in the execution. We can use some of the prebuilt
ExpectedConditions to wait for elements to become clickable, visible, invisible, etc.
Syntax : WebDriverWait wait = new WebDriverWait(driver, 10);
wait.until(ExpectedConditions.elementToBeClickable(By.name(“name")));

Mr. Suresh Page 71 of 139


Selenium Training by Suresh
//Example for wait method in webdriver
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class Explicitwait{
public static void main(String[] args) throws InterruptedException {
System.setProperty(“webdriver.gecko.driver”,”E:\\geckodriver.exe”);
WebDriver driver=new FirefoxDriver();
driver.navigate().to("http://127.0.0.1/orangehrm-2.6/login.php");
driver.findElement(By.xpath("//input[@type='text']")).sendKeys("suresh");
driver.findElement(By.xpath("//input[@type='password']")).sendKeys("suresh123");
//Explicit Wait for element to be clickable
WebDriverWait wait = new WebDriverWait(driver, 15);
wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//input[@type='Submit']")))
;
driver.findElement(By.xpath("//input[@type='Submit']")).click();
//Implicit wait
driver.manage().timeouts().implicitlyWait(3, TimeUnit.SECONDS);
System.out.println("Login completed");
driver.findElement(By.xpath("//*[@id='option-menu']/li[3]/a")).click();
driver.quit();
}
}

File upload using WebDriver


//Example to upload an image for AddNewEmployee Test case
WebElement fileInput =
driver.findElement(By.xpath("//input[@type='file'][@name='photofile']"));
fileInput.sendKeys("C:\\Users\\Public\\Pictures\\Sample Pictures\\Desert.jpg");
Thread.sleep(5000);
System.out.println("File uploaded successfully");

Mr. Suresh Page 72 of 139


Selenium Training by Suresh

JavaScript Executer
What are JavaScript Executors?
JavascriptExecutor interface is a part of org.openqa.selenium and implements
java.lang.Object class. JavascriptExecutor presents the capabilities to execute JavaScript
directly within the web-browser. To be able to execute the JavaScript, certain mechanisms in
the form of methods along with a specific set of parameters are provided in its
implementation.

JavaScript Executors
While automating a test scenario, there are certain actions those become an inherent part of
test scripts.
These actions may be:
•Clicking a button, hyperlink etc.
•Typing in a text box
•Scrolling Vertically or Horizontally until the desired object is brought into view
•And many more

Mr. Suresh Page 73 of 139


Selenium Training by Suresh
But what if the selenium commands don’t work?
Yes, it is absolutely possible that the very basic and elementary Selenium Commands don’t
work in certain situations.
That said, to be able to troubleshoot such situation, we shoulder JavaScript executors into the
picture.
Methods
ExecuteScript (String script, args)
As the method name suggests, it executes the JavaScript within the current window, alert,
frame etc (the window that the WebDriver instance is currently focusing on)
ExecuteAsyncScript (String script, args)
As the method name suggests, it executes the JavaScript within the current window, alert,
frame etc (the window that the WebDriver instance is currently focusing on)
The parameters and import statement are common to both the executor methods.
Parameters
Script – the script to be executed
Argument – the parameters that the script requires for its execution (if any)
Import statement
To be able to use JavascriptExecutors in our test scripts, we need to import the package using
the following syntax:
import org.openqa.selenium.JavascriptExecutor;
Sample Code
#1) clicking a web element
/ Locating the web element using id
WebElement element = driver.findElement (By.id ("id of the webelement"));
// Instantiating JavascriptExecutor
JavascriptExecutor js = (JavascriptExecutor) driver;
// clicking the web element
js.executeScript ("arguments [0].click ();", element);
#2) Typing in a Text Box
//Instantiating JavascriptExecutor
JavascriptExecutor js = (JavascriptExecutor) driver;
// Typing the test data into Textbox
js.executeScript("document.getElementById(‘id of the element’).value=’test data’;”);
#3) Scrolling down until the web element is in the view
WebElement element=driver.findElement(By.xpath("//input[contains(@value,'Save')]"));
// Instantiating the javascriptExecutor and scrolling into the view in the single test step
((JavascriptExecutor)driver).executeScript("arguments[0].scrollIntoView(true);",element);
Sample Program
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.By;
public class JavaScriptExe {
public static void main(String args[]) throws Exception{
System.setProperty(“webdriver.gecko.driver”,”E:\\geckodriver.exe”);
WebDriver driver = new FirefoxDriver();
Mr. Suresh Page 74 of 139
Selenium Training by Suresh
//test casse steps
driver.get("http://127.0.0.1/orangehrm-2.6/login.php");
System.out.println(driver.getTitle());
driver.findElement(By.xpath("//input[@name='txtUserName']")).sendKeys("admin");
driver.findElement(By.name("txtPassword")).sendKeys("admin");
//using javascriptExecuter to click on login btn
WebElement element = driver.findElement(By.name("Submit"));
JavascriptExecutor executor = (JavascriptExecutor)driver;
executor.executeScript("arguments[0].click();", element);
Thread.sleep(3000);
System.out.println("Login completed");
// using javascriptExecuter to click on logout
WebElement logout = driver.findElement(By.linkText("Logout"));
JavascriptExecutor executor1 = (JavascriptExecutor)driver;
executor1.executeScript("arguments[0].click();", logout);
System.out.println("Logout completed");
driver.close();
}
}

Windows Handelers :
Get Window Handles. The Get Window Handles command of the WebDriver API returns a
list of all WebWindow s. Each tab or window, depending on whether you are using a tabbed
browser, is associated by a window handle that is used as a reference when switching to the
window
import java.util.ArrayList;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class WindowHandels {
public static void main(String args[]) throws Exception{
System.setProperty("webdriver.gecko.driver",
"D:\\Suresh_Selenium\\Drivers\\geckodriver.exe");
WebDriver driver = new FirefoxDriver();
driver.get("file:///D:/Suresh_Selenium/HtmlFiles/multiplewindows.html");
driver.findElement(By.id("btn1")).click();
Thread.sleep(3000);
driver.findElement(By.id("btn2")).click();
ArrayList<String> wind=new ArrayList<String>(driver.getWindowHandles());
driver.switchTo().window(wind.get(0));
Thread.sleep(3000);
driver.quit(); }
}

Mr. Suresh Page 75 of 139


Selenium Training by Suresh
Example for WebTable /HTML Table:

Now in above html table need to retrieve the row and coloumn count after that retrieve
the data from particular cell and whole webtable
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class Table {
public static void main(String[] args)throws Exception {
System.setProperty(“webdriver.gecko.driver”,”E:\\geckodriver.exe”);
WebDriver driver=new FirefoxDriver ();
driver.get("url");
//Count Details
int row =driver.findElements(By.xpath("//table[@id='idCourse']/tbody/tr")).size();
int col =driver.findElements(By.xpath("//table[@id='idCourse']/tbody/tr[1]/td")).size();
int rowcol =driver.findElements(By.xpath("//table[@id='idCourse']/tbody/tr/td")).size();
System.out.println(row);
System.out.println(col);
System.out.println(rowcol);
//To get Data from particular Cell
String data1 = driver.findElement(By.xpath("//table [@id='idCourse']/tbody/tr
[2]/td[2]")).getText();
System.out.println (data1);
//To get Data from all rows
for (int i=1;i<=row;i++) {
//for (int j=1;j<=col;j++) {
String data = driver.findElement(By.xpath("//table [@id='idCourse']/tbody/tr
["+i+"]")).getText ();
System.out.println(data);
}
}
driver.close();
}
}

Mr. Suresh Page 76 of 139


Selenium Training by Suresh
Examples for Excel Activities
Example for Excel Sheets using JXL.jar file
Reading the single row from the excel sheet
Note: To work with JXL we need to add JXL.jar file to the project
ExcelFileName : 12345.xls
EmpID EmpName EmpSal
101 aaa 10000
102 bbb 20000
103 ccc 15000
import java.io.FileInputStream;
import jxl.*;
public class Excel {
public static void main(String args[])throws Exception{
FileInputStream f1=new FileInputStream ("E:\\Selenium\\ReadExcel.xls");
Workbook w1=Workbook.getWorkbook(f1);
Sheet s1=w1.getSheet("Sheet1");
System.out.println(s1.getName());
int i=2; //reading data from one particular row
String EmpID=s1.getCell(0, i).getContents ();
String EmpName=s1.getCell(1, i).getContents ();
String EmpSal=s1.getCell(2, i).getContents ();
System.out.println(EmpID);
System.out.println(EmpName);
System.out.println(EmpSal); }
}

Reading all the rows in Excel sheet


import java.io.FileInputStream;
import jxl.*;
public class Excelloop {
public static void main(String args[]) throws Exception{
FileInputStream f1=new FileInputStream("E:\\Selenium\\ReadExcel.xls");
Workbook objwb=Workbook.getWorkbook (f1);
Sheet s1=objwb.getSheet(0);
int rows = s1.getRows(); //to get row count
System.out.println(rows);
for (int i=1;i<rows;i++) {
String EmpID=s1.getCell(0, i).getContents ();
String EmpName=s1.getCell(1, i).getContents ();
String EmpSal=s1.getCell(2, i).getContents ();
System.out.println(EmpID);
System.out.println(EmpName);
System.out.println(EmpSal); }
}
}
Mr. Suresh Page 77 of 139
Selenium Training by Suresh
Example for Excel Sheets using POI.jar file
Reading the data from the excel sheet and writing the data in particular cell
Note: To Work with POI we need to add below POI.jar files to the project.

Excel File name: 123.xlsx


EmpNo EmpName
101 Hari
102 Naveen/Test123 2ndRow,1stcol
103 suresh
import java.io.FileInputStream;
import java.io.FileOutputStream;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class WriteExcelData {
public static void main(String args[]) throws Exception{
FileInputStream fis = new FileInputStream("D:\\Suresh_Selenium\\WriteData.xlsx");
XSSFWorkbook workbook = new XSSFWorkbook(fis);
XSSFSheet sheet = workbook.getSheet("test");
System.out.println(sheet.getSheetName());
System.out.println(sheet.getLastRowNum());
System.out.println("Before updating Cell Data "+sheet.getRow(2).getCell(1));
// Write the data to excel file
XSSFCell cell = sheet.getRow(2).getCell(1);
cell.setCellValue("Test123");
fis.close();
FileOutputStream fileOut=new FileOutputStream("D:\\Suresh_Selenium\\WriteData.xlsx");
workbook.write(fileOut);
System.out.println("Updated data after write is done " + cell.getStringCellValue());
fileOut.close();
}
}

Mr. Suresh Page 78 of 139


Selenium Training by Suresh
Working with Data Base : We have 3 types of databases
 File Data Base –eg:foxpro ,ms-access
 Remote data base-SQL ,Oracle
 index data base-Internet DB
Drivers: It s a technology, this driver has 3 components
 Connection & Staments(commands) & Results sets
 By using connection we can connect to the data source and we open database
 Create stmt for executing queries
 Commands are DML commands
 By using results set we can get data from tables.
How to create DSN: Open Control Pane Administrative Toolsdata Sourcesclick on
ADDSelect a driver (“msAccessDriver (*.mdb,*.accdb)click on finishgive
dataSourceName(dsn1)click on select for databasebrowse create databaseclick on OK
click on ok
Reading the data from MS Access database , Note: Create a dataase table in ms-access
as below.
TableName : EmpTable

import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.Statement;
import java.sql.ResultSet;
class Database{
public static void main(String args[]) {
try {
Connection con=DriverManager.getConnection ("jdbc: odbc: dsn1");
Statement st=con.createStatement ();
Thread.sleep (3000);
ResultSet rs=st.executeQuery ("select * from emptable");
while (rs.next()) {
System.out.println (rs.getString (2) +"\t"+rs.getString (3) +rs.getString (4) +"\t"+rs.getString
(5));
}
rs.close ();
st.close ();
con.close ();
}
catch (Exception e) {
System.out.println ("Error:"+e);
}
}
}
Mr. Suresh Page 79 of 139
Selenium Training by Suresh

1. Diffirence between get() & navigate.to() method

2. Diffirence between close() & quit() method

3. Write a syntax to type the data in Textbox

4. Write a syntax to perform click activity in Webdriver

5. Write a syntax to verify the Title in webdriver

6. Write a code to execute the programs in Chrome/IE browsers

7. Write a code to Verify Text in webdriver using Assert stmt

8. Explain Frames in WebDriver

9. Write a code to retrieve the data from TextBox

10. Write a code to Handle Alerts in WebDriver

Mr. Suresh Page 80 of 139


Selenium Training by Suresh

11. Explain Wait methods in Webdriver

12. How to Perfrom Click action with out using Click method

13. Diffirence between close() and quit() methods

14. What are the Technical challenges you faced while working with Selenium
Automation

15. List the common errors you faced while working with Selenium

Mr. Suresh Page 81 of 139


Selenium Training by Suresh

16. Write a code to perform MoverOver

17. Write a code to Select single value & Multipul values from dropdown

18. Write a code to read the data from Excel

19. Write a code to get Row count & Coloum count from WebTable & Write a code TO
retrive data from particular cell

Mr. Suresh Page 82 of 139


Selenium Training by Suresh

20. Write a code to Click on Yes/OK btn in Alert.

Automation Frameworks
What an Automation Framework is?
A test automation framework is a set of assumptions, concepts and tools that provide support
for automated software testing. The main advantage of such a framework is the low cost for
maintenance. If there is change to any test case then only the test case file needs to be
updated and the Driver Script and Startup script will remain the same. Ideally, there is no
need to update the scripts in case of changes to the application.
Utility of Test Automation Framework
 Provides an Outline of overall Test Structure
 Ensures Consistency of Testing
 Minimizes the Amount of Code for Development - thereby Less Maintenance
 Maximizes Reusability
 Reduces Exposure of Non-Technical Testers to Code
 Enables Test Automation using Data
How Many Types of Automation Frameworks are there?
Generally there are 4 Types:
 Data Driven Automation Framework
 Keyword Driven Automation Framework
 Modular Automation Framework
 Hybrid Automation Framework
Modular Framework
Modular Framework is the approach where all the test cases are first analyzed to find out the
reusable flows. Then while scripting, all these reusable flows are created as functions and
stored in external files and called in the test scripts wherever required.
 Enables creation of Small, Independent Scripts representing
 Modules & Functions of the Application under Test (AUT)
 Test Library Architecture Framework:
 Enables creation of Library Files representing Modules & Functions of the

Mr. Suresh Page 83 of 139


Selenium Training by Suresh
Application under Test (AUT)
 Objects defined by parameterized code (i.e., regular expressions)
 Custom functions used to enhance workflow capabilities

Advantages of Modular Framework


•Test Scripts can be created in relatively less time as the reusable functions need to be created
only once.
• Effort required to create test cases is also lesser due to code reuse.
•If there are any changes in the reusable functions, the changes need to be done in only a
single place. Hence script maintenance is easier.
Disadvantages of Modular Framework
•Since data is still hardcoded in the script, the same test case cannot be run for multiple data
values without changing data after each run.
•Additional time is spent in analyzing the test cases to identify with reusable flows.
•Good programming knowledge is required to create and maintain function libraries.
Packages- Steps to Design the Modular FrameWork from the scratch.
A package is a group of classes.If we create on package in eclipse it will be considered as one
folder in your eclipse workspace.

Design the modular framework in eclipse as below.

Write the below code in each and every file as mentioned.

Mr. Suresh Page 84 of 139


Selenium Training by Suresh

Project Suresh_Modular_Framework
Package com.hrms.LIB
general.java Maintains all the reusable fundtions related
to your project.
Eg:
openBrowser()
closeBrowser()
login()
logout()
addemp()
delemp()
etc….
global.java Maintains all the varibles & objects related
your project
Eg:
WebDriver driver,
application url,
UserName,
Password,
etc …
==========Objects==========
txt_UserName = "txtUserName"
btn_Login = "Submit"
link_logout = "Logout"
etc…
Package com.hrms.testscripts All the actual test cases need to written in
this package only
TC_HRMS_101
TC_HRMS_102
TC_HRMS_103
=========create com.hrms.LIB package and in that create global.java file=========
package com.hrms.lib;
import org.openqa.selenium.WebDriver;
public class Global {
//===================Varibles info======================
public WebDriver driver;
public String url = "http://127.0.0.1/orangehrm-2.6/login.php";
public String un = "admin";
public String pw = "admin";
//=======================Objects=====================
public String txt_loginname = "txtUserName";
public String txt_password = "txtPassword";
public String btn_login = "Submit";
public String link_logout = "Logout";
Mr. Suresh Page 85 of 139
Selenium Training by Suresh
}
===========create general.java file in same package=========
package com.hrms.lib;
import org.openqa.selenium.By;
import org.openqa.selenium.firefox.FirefoxDriver;
public class general extends Global {
public void openapplication(){
System.setProperty(“webdriver.gecko.driver”,”E:\\geckodriver.exe”);
driver = new FirefoxDriver();
driver.navigate().to(url); }
public void closebrowser(){
driver.quit();
}
public void login() throws Exception{
driver.findElement(By.name(txt_loginname)).sendKeys(un);
driver.findElement(By.name(txt_password)).sendKeys(pw);
driver.findElement(By.name(btn_login)).click();
Thread.sleep(3000);
}
public void logout(){
driver.findElement(By.linkText(link_logout)).click(); }
public void addemp(){
System.out.println("adding new emp"); }
public void delmp(){
System.out.println("delete emp"); }
}
=======create all automation test scripts under the package of –
com.hrms.testscripts=======
package com.hrms.testscripts;
import com.hrms.lib.*;
public class TC_hrms_101 {
public static void main(String args[]) throws Exception{
general g = new general();
//test case steps
g.openapplication();
g.login();
g.addemp();
g.delmp();
g.logout();
g.closebrowser();
}
}

Mr. Suresh Page 86 of 139


Selenium Training by Suresh
Automate Below Test cases based on FrameWork:

Mr. Suresh Page 87 of 139


Selenium Training by Suresh

Crate a testsuite (By using xml) to execute end to end flow and then run above 3 test test
cases.
1.TC_101_VerifyLogin
2.TC_102_AddNewEmp
3.TC_103_DelEmp
Note: Create automation scripts for below scenarios.(Company Location Test cases)
1.TC_101_VerifyLogin
2.TC_102_Add New Company Location
3.TC_103_Search For newly Added company Location
4.TC_104_Delete company Location
Note: Create automation scripts for below scenarios.(Company Property Test cases)
1.TC_101_VerifyLogin
2.TC_102_Add New Company property
3.TC_103_Delete company property

Mr. Suresh Page 88 of 139


Selenium Training by Suresh
TestNG (http://testng.org)
Introduction
TestNG is a testing framework that overcomes the limitations of another popular testing
framework called JUnit. The "NG" means "Next Generation". Most Selenium users use this
more than JUnit because of its advantages. There are so many features of TestNG, but we
will only focus on the most important ones that we can use in Selenium.
Advantages of TestNG over JUnit
 There are three major advantages of TestNG over JUnit:
 Annotations are easier to understand
 Test cases can be grouped more easily
 Parallel testing is possible
Annotations in TestNG are lines of code that can control how the method below them will be
executed. They are always preceded by the @ symbol.
Writing a test is typically a three-step process:
 Write the business logic of your test and insert TestNG annotations in your code.
 Add the information about your test (e.g. the class name, the groups you wish to run,
etc...) in a testng.xml file or in build.xml.
 Run TestNG
Some Information on TestNG as follows:
 A suite is represented by one XML file. It can contain one or more tests and is defined
by the <suite> tag.
 A test is represented by <test> and can contain one or more TestNG classes.
 A TestNG class is a Java class that contains at least one TestNG annotation. It is
represented by the <class> tag and can contain one or more test methods.
 A test method is a Java method annotated by @Test in your source.
A TestNG test can be configured by @BeforeXXX and @AfterXXX annotations which
allows to perform some Java logic before and after a certain point, these points being either
of the items listed above.

Below are the List of TestNG Annotations


Configuration information for a TestNG class:

@BeforeSuite: The annotated method will be run before all tests in


@BeforeSuite
this suite have run.
@AfterSuite
@AfterSuite: The annotated method will be run after all tests in
@BeforeTest
this suite have run.
@AfterTest
@BeforeTest: The annotated method will be run before any test
@BeforeGroups
method belonging to the classes inside the <test> tag is run.
@AfterGroups
@AfterTest: The annotated method will be run after all the test
@BeforeClass
methods belonging to the classes inside the <test> tag have run.
@AfterClass
@BeforeGroups: The list of groups that this configuration method
@BeforeMethod
will run before. This method is guaranteed to run shortly before the
@AfterMethod
first test method that belongs to any of these groups is invoked.
@AfterGroups: The list of groups that this configuration method
will run after. This method is guaranteed to run shortly after the last

Mr. Suresh Page 89 of 139


Selenium Training by Suresh
test method that belongs to any of these groups is invoked.
@BeforeClass: The annotated method will be run before the first
test method in the current class is invoked.
@AfterClass: The annotated method will be run after all the test
methods in the current class have been run.
@BeforeMethod: The annotated method will be run before each
test method.
@AfterMethod: The annotated method will be run after each test
method.
For before methods (beforeSuite, beforeTest, beforeTestClass and
beforeTestMethod, but not beforeGroups): If set to true, this
configuration method will be run regardless of what groups it
alwaysRun belongs to.
For after methods (afterSuite, afterClass, ...): If set to true, this
configuration method will be run even if one or more methods
invoked previously failed or was skipped.
dependsOnGroups The list of groups this method depends on.
dependsOnMethods The list of methods this method depends on.
enabled Whether methods on this class/method are enabled.
groups The list of groups this class/method belongs to.
If true, this method will belong to groups specified in the @Test
inheritGroups
annotation at the class level.
Marks a method as supplying data for a test method. The
annotated method must return an Object[][] where each
Object[] can be assigned the parameter list of the test method.
@DataProvider
The @Test method that wants to receive data from this
DataProvider needs to use a dataProvider name equals to the
name of this annotation.
The name of this data provider. If it's not supplied, the name of this
name
data provider will automatically be set to the name of the method.
If set to true, tests generated using this data provider are run in
parallel
parallel. Default value is false.
Marks a method as a factory that returns objects that will be
@Factory used by TestNG as Test classes. The method must return
Object[].
@Listeners Defines listeners on a test class.
value An array of classes that extend org.testng.ITestNGListener.
@Parameters Describes how to pass parameters to a @Test method.
value The list of variables used to fill the parameters of this method.
@Test Marks a class or a method as part of the test.
Mr. Suresh Page 90 of 139
Selenium Training by Suresh
If set to true, this test method will always be run even if it depends
alwaysRun
on a method that failed.
dataProvider The name of the data provider for this test method.
The class where to look for the data provider. If not specified, the
data provider will be looked on the class of the current test method
dataProviderClass
or one of its base classes. If this attribute is specified, the data
provider method needs to be static on the specified class.
dependsOnGroups The list of groups this method depends on.
dependsOnMethods The list of methods this method depends on.
description The description for this method.
enabled Whether methods on this class/method are enabled.
The list of exceptions that a test method is expected to throw. If no
expectedExceptions exception or a different than one on this list is thrown, this test will
be marked a failure.
groups The list of groups this class/method belongs to.
invocationCount The number of times this method should be invoked.
The maximum number of milliseconds this test should take for the
invocationTimeOut cumulated time of all the invocationcounts. This attribute will be
ignored if invocationCount is not specified.
The priority for this test method. Lower priorities will be scheduled
priority
first.
successPercentage The percentage of success expected from this method
If set to true, all the methods on this test class are guaranteed to run
in the same thread, even if the tests are currently being run with
singleThreaded parallel="methods". This attribute can only be used at the class
level and it will be ignored if used at the method level. Note: this
attribute used to be called sequential (now deprecated).
timeOut The maximum number of milliseconds this test should take.
The size of the thread pool for this method. The method will be
threadPoolSize invoked from multiple threads as specified by invocationCount.
Note: this attribute is ignored if invocationCount is not specified

Installing TestNG in Eclipse


Step 1
 Launch Eclipse.
 On the menu bar, click Help.
 Choose the "Install New Software..." option.

Mr. Suresh Page 91 of 139


Selenium Training by Suresh

Step 2
In the Install dialog box, click the Add button

Step 3
1.In "Name", type TestNG.
2.In "Location", type http://beust.com/eclipse.
3.Click OK

Step 4
 Notice that "TestNG - http://beust.com/eclipse" was populated onto the "Work with:"
textbox.
 Check the "TestNG" check box as shown below, then click Next.
 Note: In the latest Eclipse (Kepler) you don't have a checkbox for TestNG, instead you
click on question mark (help) icon which will open up the form, and you can select all
and installation will continue as for the remaining instructions. Thanks Jana for the tip!

Step 5
 Click next again on the succeeding dialog box until you reach the License Agreement
dialog.
 Click "I accept the terms of the license agreement" then click Finish.

Mr. Suresh Page 92 of 139


Selenium Training by Suresh

Step 6
Wait for the installation to finish

If you encounter a Security warning, just click OK

Step 7
When Eclipse prompts you for a restart, just click Yes.

Step 8
After the restart, verify if TestNG was indeed successfully installed. Click Window >
Preferences and see if TestNG is included on the Preferences list.

Mr. Suresh Page 93 of 139


Selenium Training by Suresh

OR
Installation:
 Select help menu option in eclipse
 Select eclipse market place option
 Search for TestNG plugin
 Click on install btutton
 Click on Next
 Accept license
 Click on finish btn
 Restart eclipse
Step 2: download and Add Testng .Jar file to project
 Go to TestNG.org site
 Click on downloads
 Click on “You can download the current release version of TestNG here”.
 Add the .jar files to the project
Example:.
import org.testng.annotations.Test;
public class TC_TestNG {
@Test
public void login(){
System.out.println("login completed");
}
@Test(dependsOnmethods="login")
public void logout(){
System.out.println("Logout completed");
}
}
Note: in above example logout method will get executed only in case of login method got
passed other it will skip the logout method

Mr. Suresh Page 94 of 139


Selenium Training by Suresh
Example for TestNG annotations
import org.testng.annotations.AfterClass;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
public class ExampleForTestNgAnnotations {
@BeforeClass / @BeforeMethod
public void login(){
System.out.println("login completed");
}
@AfterClass / @AfterMethod
public void logout(){
System.out.println("logout completed");
}
@Test(priority=2)
public void addemp() {
System.out.println("Adding new emp");
}
@Test(priority=1)
public void delemp() {
System.out.println("delete emp");
}
}
Output for @BeforeClass & @AfterClass :Note- @BeforeClass & @AfterClass will
executed only one time for the whole program
login completed
delete emp
Adding new emp
logout completed
Output for @BeforeMethod & @AfterMethod:Note-@BeforeMethod & @AfterMethod
will executed for every @Test method

login completed
delete emp
logout completed
login completed
Adding new emp
logout completed

Example for - Webdriver with Testng


import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.Reporter;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
Mr. Suresh Page 95 of 139
Selenium Training by Suresh
import org.testng.annotations.Test;
public class WebDriverTestng {
private WebDriver driver;
@BeforeClass
public void Startup(){
System.setProperty(“webdriver.gecko.driver”,”E:\\geckodriver.exe”);
driver = new FirefoxDriver();
}
@Test (description="OrangeHRM Login")
public void Login() throws Exception{
Reporter.log("Test case steps");
driver.get("http://127.0.0.1/orangehrm-2.6/login.php");
Reporter.log("1.Application opened");
driver.findElement(By.name("txtUserName")).sendKeys("suresh");
Reporter.log("2.typing user name");
driver.findElement(By.name("txtPassword")).sendKeys("suresh123");
Reporter.log("3.Typing password");
driver.findElement(By.name("Submit")).click();
Thread.sleep(3000);
Reporter.log("4.login completed");
driver.findElement(By.linkText("Logout")).click();
}
@AfterClass
public void teardown(){
driver.quit();
}
}

TestNG Sample Report

Mr. Suresh Page 96 of 139


Selenium Training by Suresh
Example for – Excel + Webdriver +TestNG
Reading the username and password from excelsheet and inputing these values in application
using webdriver program and generating the Report with TestNG.
LoginExcel.xls
UserName Password
admin admin
import java.io.FileInputStream;
import jxl.Sheet;
import jxl.Workbook;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.Reporter;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
public class TC_Excel_WD_TestNG {
public WebDriver driver;
@BeforeClass
public void Startup(){
System.setProperty(“webdriver.gecko.driver”,”E:\\geckodriver.exe”);
driver = new FirefoxDriver();
}
@AfterClass
public void teardown(){
driver.quit();
}
@Test
public void login() throws Exception{
//Reading username and password from excel and assigning to variables
FileInputStream f1 = new FileInputStream("E:\\Selenium\\LoginExcel.xls");
Workbook w = Workbook.getWorkbook(f1);
Sheet s = w.getSheet(0);
String un = s.getCell(0,1).getContents();
String pw = s.getCell(1,1).getContents();
//Typing username and password from Excel file
driver.navigate().to("http://127.0.0.1/orangehrm-2.6/login.php");
driver.findElement(By.name("txtUserName")).sendKeys(un);
driver.findElement(By.name("txtPassword")).sendKeys(pw);
driver.findElement(By.name("Submit")).click();
Thread.sleep(3000);
System.out.println("Login completed");
Reporter.log("Login completed");
driver.findElement(By.linkText("Logout")).click();
Reporter.log("Logout completed");

Mr. Suresh Page 97 of 139


Selenium Training by Suresh
}
}
Example for - Taking screensot on failure in webDriver
Note: Before writing the this program download and Add commons.io.jar file to project for
the purpose of getting access for FileUtils class
import java.io.File;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.By;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.interactions.Actions;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
public class CapScreenShot{
WebDriver driver;
@BeforeMethod
public void setUp() {
System.setProperty("webdriver.gecko.driver","D:\\Suresh\\Drivers\\geckodriver.exe");
driver=new FirefoxDriver();
}
@AfterMethod
public void tearDown() {
driver.quit();
}
@Test
public void screenshot() throws Exception {
try {
driver.navigate().to("http://127.0.0.1/orangehrm-2.6/login.php");
driver.findElement(By.name("txtUserName")).sendKeys("suresh");
driver.findElement(By.name("txtPassword")).sendKeys("suresh123");
driver.findElement(By.name("Submit")).click();
Thread.sleep(3000);
WebElement element = driver.findElement(By.linkText("PIM"));
Actions action = new Actions(driver);
action.moveToElement(element).perform();
Thread.sleep(3000L);
driver.findElement(By.linkText("Add Employee123")).click();
Thread.sleep(4000);
System.out.println("Clicked on submenu");
}
catch(Exception e) {
File f1 = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(f1, new File("g:\\TestResults.png"));
Mr. Suresh Page 98 of 139
Selenium Training by Suresh
}
driver.quit();
}
}

Example for - Drag and Drop in WebDriver


import static org.testng.Assert.assertEquals;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.interactions.Actions;
import org.testng.annotations.*;
public class DragandDrop {
WebDriver driver;
@Test
public void testDragnDrop() throws Exception {
driver.manage().window().maximize();
driver.get("http://jqueryui.com/droppable/");
Thread.sleep(10000L);
assertEquals("Droppable | jQuery UI",driver.getTitle());
driver.switchTo().frame(0);
Actions a=new Actions(driver);
a.dragAndDrop(driver.findElement(By.id("draggable")),
driver.findElement(By.id("droppable"))).build().perform();
Thread.sleep(6000L);
}
@BeforeMethod
public void setUp() {
System.setProperty("webdriver.gecko.driver",
"D:\\Suresh_Selenium\\Drivers\\geckodriver.exe");
driver=new FirefoxDriver();
}
@AfterMethod
public void tearDown() {
driver.quit();
}

}
Before Executing the program

Mr. Suresh Page 99 of 139


Selenium Training by Suresh

After Executing the program

Example for - Running testsuites or groups using WebDriver with TestNG


Some times will have requiremt like need to run only sanity test scripts or regression test
scripts or only functional test scripts.
Then we can control all these test scripts execution with the help of XML file.
Now in below example we are executing only sanity and regression test cases and ignoring
the functional test cases.
==================== TC_5130==================
import org.testng.annotations.Test;
public class TC_5130 {
@Test(groups="Regression",priority=1)
public void meth1() {
System.out.println("This is meth1() in TC_5130");
}
@Test(groups="Sanity",priority=1)
public void meth2() {
System.out.println("This is meth2() in TC_5130");
}
@Test(groups="Regression",priority=2)
public void meth3() {
System.out.println("This is meth3() in TC_5130");
}
@Test(groups="Sanity",priority=2)
public void meth4() {
System.out.println("This is meth4() in TC_5130"); }
}
==================== TC_5131==================
import org.testng.annotations.Test;
public class TC_5131{
@Test(groups="Regression")
public void meth1() {
System.out.println("This is meth1() in TC_5131");
}
@Test(groups="Regression")
public void meth2() {
System.out.println("This is meth2() in TC_5131");
Mr. Suresh Page 100 of 139
Selenium Training by Suresh
}
@Test(groups="Sanity")
public void meth3() {
System.out.println("This is meth3() in TC_5131");
}
@Test(groups="Functional")
public void meth4() {
System.out.println("This is meth4() in TC_5131"); }
}
=====================grouprun.xml===============
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" >
<suite name="GroupRun" verbose="1" >
<test name="GroupRun">
<groups>
<run>
<include name="Regression"/>
<include name="Sanity"/>
<exclude name="Functional"/>
</run>
</groups>
<classes>
<class name="com.hrms.groups.TC_5130"/>
<class name="com.hrms.groups.TC_5131"/>
</classes>
</test>
</suite>

Parallel Execution : Running the testcases with multipul browsers using WebDriver
with TestNG
This program will open the two browsers - one is Chrome and another is Firefox and it will
execute the test scrips parallel.
============= TC_101 =============
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.testng.Reporter;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Parameters;
import org.testng.annotations.Test;
public class TC_101 {
WebDriver driver;
@Test
public void openFF() throws Exception {

Mr. Suresh Page 101 of 139


Selenium Training by Suresh
driver.navigate().to("http://127.0.0.1/orangehrm-2.6/login.php");
Reporter.log("Opened HRMS application in Firefox Browser");
Thread.sleep(5000L);
}
@Parameters({"browser"})
@BeforeMethod
public void setUp(String browser) {
if(browser.equals("Firefox")) {
System.setProperty("webdriver.gecko.driver",
"D:\\Suresh_Selenium\\Drivers\\geckodriver.exe");
driver=new FirefoxDriver();
}
else if(browser.equals("IE")) {
System.setProperty("webdriver.ie.driver","E:\\Selenium\\WebDriver\\chromedriver_
win32\\IEDriverServer.exe");
driver=new InternetExplorerDriver();
}
else if(browser.equals("Chrome")) {
System.setProperty("webdriver.chrome.driver",
"D:\\Suresh_Selenium\\Drivers\\chromedriver.exe");
driver=new ChromeDriver();
}
}
@AfterMethod
public void tearDown() {
driver.quit();
}
}
============= TC_102 =============
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.testng.Reporter;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Parameters;
import org.testng.annotations.Test;
public class TC_102 {
WebDriver driver;
@Test
public void openChrome() throws Exception {
driver.navigate().to("http://www.google.com");
Thread.sleep(20000);
Reporter.log("Opened google page in Chrome Browser");
Thread.sleep(20000);
}
Mr. Suresh Page 102 of 139
Selenium Training by Suresh
@Parameters({"browser"})
@BeforeMethod
public void setUp(String browser) {
if(browser.equals("Firefox")) {
System.setProperty("webdriver.gecko.driver",
"D:\\Suresh_Selenium\\Drivers\\geckodriver.exe");
driver=new FirefoxDriver(); }
else if(browser.equals("IE")) {
System.setProperty("webdriver.ie.driver","E:\\Selenium\\IEDriverServer.exe");
driver=new InternetExplorerDriver(); }
else if(browser.equals("Chrome")) {
System.setProperty("webdriver.chrome.driver",
"D:\\Suresh_Selenium\\Drivers\\chromedriver.exe");
driver=new ChromeDriver(); }
}
@AfterMethod
public void tearDown() {
driver.quit();
}
}
======browser.xml============
<?xml version="1.0" encoding="UTF-8"?>
<suite name="parallel Suites" parallel="tests">
<test name="Test in GC">
<parameter name="browser" value="Chrome"/>
<classes>
<class name="com.hrms.parallel.TC_102"/>
</classes>
</test>
<test name="Test in FF">
<parameter name="browser" value="Firefox"/>
<classes>
<class name="com.hrms.parallel.TC_101"/>
</classes>
</test>
</suite>

Hybrid Framework

Hybrid Framework is a framework that is created by combining different features of any of


the frameworks. Based upon your requirements, you can combine the features of any of the
frameworks to come up with your own version of Hybrid Framework.
 It is a Combination of the Three Types of Frameworks described before
 It has an Ability of Evolving Itself Over a Passage of Time and Over Many Projects
Advantages
 The main advantage of this approach is that you can use the best features from all the
types of frameworks to create your own.
Mr. Suresh Page 103 of 139
Selenium Training by Suresh
Disadvantages
 The framework is highly complex and needs very good programming expertise and
experience to build a Hybrid Framework from scratch.

Design Project structure as below in Eclipse:


(WebDriver + TestNG+TestSuite+Log4j+Jenkins+Github)

Note: While working with Selenium we had an option to implement Log4j also .In below
will discuss in detail to implement Log4j with our Framework.
Log4j-Logger
Selenium with Logs (Log4j)
Sometimes logging is considered to be an overhead upon the existing script creation
mechanism but experts considers it to be one of the best practices if used in the accurate
proportion because of the following advantages:
Advantages of Logging in Selenium Scripts:
 Grants a complete understanding of test suites execution
 Log messages can be stored in external files for post execution scrutiny
 Logs are an exceptional assistant in debugging the program execution issues and
failures
 Logs can also be reviewed to ascertain the application’s health by the stakeholders
Log4j – A Java based Logging API
Moving on to the technical details about logging, let us discuss the origin of the API that we
would be using throughout the log4j to generate logs. Log4j was a result of collaborative
efforts of people at Secure Electronic Marketplace for Europe to develop a utility that would
help us generating logs and hence the log4j came into limelight in the year 1996. Log4j is an
open source tool and licensed under IBM Public License.
There are three main components that constitute the implementation of log4j. These
Mr. Suresh Page 104 of 139
Selenium Training by Suresh
components represent the details about the log level, formats of the log message in which
they would be rendered and their saving mechanisms.
Constituents of Log4j
1. Loggers
2. Appenders
3. Layouts
#1) Loggers
The following steps need to done in order to implement loggers in the project.
Step 1: Creating an instance of Logger class
Step 2: Defining the log level
Logger Class – It is a java based utility that has got all the generic methods already
implemented so that we are enabled to use log4j.
Log levels – Log levels are popularly known as printing methods. These are used for printing
the log messages. There are primarily five kinds of log levels.
 error()
 warn()
 info()
 debug()
 log()
Thus, to be able to generate logs, all we need to do is to call any of the printing method over
the logger instance. We will have a broader look into it during the implementation phase.
#2) Appenders
Now that we know how to generate these logs, the next thing that should pop up into our
minds is that where do I get to view the logs? The answer to this question lies in the
definition of “Appenders”.
Appenders are consistently used to specify the data source/medium where the logs should be
generated. The scope of data sources stretches from various external mediums like console,
GUI, text files etc.
#3) Layouts
At times, user wishes certain information to be pre – pended or appended with each log
statement. For example I wish to a print a timestamp along with my log statement. Thus, such
requirements can be accomplished by “Layouts”.
Layouts are a utility that allows the user to opt for a desired format in which the logs would
be rendered. Appenders and Layout have a tight coupling between them. Thus, we are
required to map each of the appender with a specific layout.
Take a note that user is leveraged to define multiple appenders, each mapped with a distinct
layout

Follow below Steps to Implement Log4j in our TestNG framework


1.Create one New Package as com.utility
2.Create one New Class with Class Name as Log.java
3.Create info() method in Log.java
4.Download Log4j.jar (http://logging.apache.org/) file and add log4j.jar file to our Project
5.Create one new Xml file and Name as log4j.xml
6.Copy the required the xml code to log4j.xml
7.Call Log.info() method in required functions on General.java file
8.Finally call and configure log4j.xml in Each and every TestCase
Mr. Suresh Page 105 of 139
Selenium Training by Suresh
Note: Make sure your project is working fine upto test suite and then implement log4j by
adding below code.

Copy below code to Log.java


package com.utility;
import org.apache.log4j.Logger;
public class Log {
//Initialize Log4j logs
private static Logger Log = Logger.getLogger(Log.class.getName());
// Need to create these methods, so that they can be called
public static void info(String message) {
Log.info(message); }
}
-------------------------------------------------------------------------------------------------------------
Copy below code to Log4j.xml
<?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="Append" value="true" />
<param name="File" value="logfile.log"/>
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%d %-5p [%c{1}] %m %n" />
</layout>
</appender>
<root>
<level value="INFO"/>
<appender-ref ref="fileAppender"/>
</root>
</log4j:configuration>
-------------------------------------------------------------------------------------------------------------
Adding Log.info() method in General.java class
public void openapplication(){
Log.info("*******started execution***********");
System.setProperty(“webdriver.gecko.driver”,”E:\\geckodriver.exe”);
driver = new FirefoxDriver();
driver.navigate().to(url);
Log.info("Application Opened Successfully");
System.out.println(driver.getTitle()); }
public void closeapplication(){
driver.quit();
Log.info("Application close successfully");
Log.info("*******End execution***********"); }
-------------------------------------------------------------------------------------------------------------
call and configure log4j.xml in Each and every TestCase
package com.hrms.testscripts;
Mr. Suresh Page 106 of 139
Selenium Training by Suresh
import org.apache.log4j.xml.DOMConfigurator;
import org.testng.annotations.Test;
import com.hrms.lib.*;
import com.utility.Log;
public class TC504 {
@Test
public void login() throws Exception{
DOMConfigurator.configure("log4j.xml");
general g = new general();
g.openapplication();
g.login();
g.logout();
g.closeapplication(); }
}
-------------------------------------------------------------------------------------------------------------
Now execute the test case, once execution had completed its need be generate logfile as
below.

Jenkins
Jenkins - History
 2005 - Hudson was first release by Kohsuke Kawaguchi of Sun Microsystems
 2010 – Oracle bought Sun Microsystems
o Due to a naming dispute, Hudson was renamed to Jenkins
Oracle continued development of Hudson (as a branch of the original)
About Jenkins
 Jenkins is an open source tool written in Java.
 Jenkins is CI (Continuous Integration) tool which will help you to run test in easy
manner.
 Jenkins is a self-contained, open source automation server which can be used to
automate all sorts of tasks related to building, testing, and delivering or deploying
software.
Steps to configure Jenkins with Selenium
1.Generate batch file
2.Download Jenkins .exe file and Install the same
3.Configure pre-defined settings(JDK path and Email Configuration)
4.Create a job Schedule
Steps to Generate bacth file
Create lib folder in project root directory

Mr. Suresh Page 107 of 139


Selenium Training by Suresh

Copy all the required jar file to run the project in to created lib folder

Create new notepad file and prove the code as below

Save the file as run.bat ,by then batch file will be created

Mr. Suresh Page 108 of 139


Selenium Training by Suresh

Perform double click on run.bat , by that you should be able to see that scripts are running.
Once scripts are running then we can confirm batch file created successfully.

Steps to Install Jenkins


Download Jenkins from website - https://jenkins-ci.org/

Download to your local system and just u can double click on .exe file it will automatically
get installed

Once installation is completed open any browser and type http://localhost:8080/ then u will
be able to see Jenkins home page as below .By this you can confirm that Jenkins had installed
successfully

Mr. Suresh Page 109 of 139


Selenium Training by Suresh

Configure pre-defined settings(JDK path and Email Configuration)


In Jenkins HomePage click on Manage Jenkins option

Now click on configure system option

Now, set the JDK path. – Click on JDK installation button.

Provide JDK Name as JAVA_HOME and JAVA_HOME (JDK path installed in your system)
,make sure you Uncheck the install automatically check box

Mr. Suresh Page 110 of 139


Selenium Training by Suresh

Next configure E-mail notification details

Next click on SAVE and APPLY button

Create a job Schedule – To Execute Selenium TestScripts with Jenkins


In Jenkins HomePage click on New Item
- Select FreeStyle Project, as selected in the image
- Provide any job a name by writing it in Item Name text box
- Now, click on OK

Click on Advanced button


Mr. Suresh Page 111 of 139
Selenium Training by Suresh

Click on use custom workspace checkbox and give your Selenium script project workspace
path – (provide path including java project name)

Then go to Build and Select – Execute Windows batch command option from the drop-down
box.

Provide the batch file name which you created in project workspace

To run build automatically provide schedule details by clicking on Build periodically check
box opion[This setting is optional]

Mr. Suresh Page 112 of 139


Selenium Training by Suresh
Select E-mail notification option from Post-build Actions option(Note : selecting this option
is Optional)

Now click on Apply button after that click on save button.

Then goto homepage - created job will be shown

To execute the script from Jenkins(manually) now click on created job and select BuildNow
option by that it will execute the program will provide the results

Now you will be able to see build is executing and status shown as below

Mr. Suresh Page 113 of 139


Selenium Training by Suresh

Click on build which u excuted to see the execution log information and then click on
Console output option, then it will shows the execution log information

Git HUB(https://github.com/)
Github is a repository on web, which support all the feature of revision control and source
code management
Steps to Integreate GitHub with Selenium Project in Eclipse:
Create an account in github with your valid email and other information.
Login to github account and create new repository

Mr. Suresh Page 114 of 139


Selenium Training by Suresh

Specify the name of the repository, description and click on create repository.

Copy new generated URL of your repository.

Now open Eclipse and Select project which we want to upload on github.
Perform right click on project and Go to team section and Select share project.

Mr. Suresh Page 115 of 139


Selenium Training by Suresh

Select checkbox and click on Create Repository button

Click on Finish button


Perform right click on created project.
Navigate to Team option and click on Commit option

Select the required files to upload from Unstaged Changes box and click on + symbol, by
Mr. Suresh Page 116 of 139
Selenium Training by Suresh
that those files will be moved to Staged Chnages box.

Provide commit message ,author and committer details and click on commit button

Perform right click on project and navigate to Team Remote Push


Provide your Git url whih you created with valid login details

Mr. Suresh Page 117 of 139


Selenium Training by Suresh
Click on Next button and then click on Add all branches Spec button

Click on Force Update checkbox and then click on Finish button

Once we are getting this window we completed to push the code to git reposity.
Mr. Suresh Page 118 of 139
Selenium Training by Suresh
To confirm we can goto git repository and check either code is moved to repository or not

Note: if required we can download this code into another team member system and then we
can make required modifications.

POM - PageObjectModel
Why POM --- The main advantage of Page Object Model is that if the UI changes for any
page, it don’t require us to change any tests, we just need to change only the code within the
page objects (Only at one place). Many other tools which are using selenium are following
the page object model.
What is POM?
 Page Object Model is a design pattern to create Object Repository for web UI
elements.
 Under this model, for each web page in the application there should be corresponding
page class.
 This Page class will find the WebElements of that web page and also contains Page
methods which perform operations on those WebElements.
 Name of these methods should be given as per the task they are performing
Advantages of POM :
1. Page Object Patten says operations and flows in the UI should be separated from
verification. This concept makes our code cleaner and easy to understand.
2. Second benefit is the object repository is independent of testcases, so we can use the
same object repository for a different purpose with different tools. For example, we
can integrate POM with TestNG/JUnit for functional testing and at the same time with
JBehave/Cucumber for acceptance testing.
3. Code becomes less and optimized because of the reusable page methods in the POM
classes.
4. Methods get more realistic names which can be easily mapped with the operation
happening in UI.
Mr. Suresh Page 119 of 139
Selenium Training by Suresh
Try with POM framework as below structure –

Apache-MAVEN
MAVEN INTRODUCTION
Apache Maven, an open source build framework that can be used to build projects and it
provides developers a complete build life-cycle framework.
Originally Maven was designed to simplify building processes in Jakarta Turbine project.
The Main Objectives of Maven are:
•It follows the best practices and standards which helps new developers coming into a project
•It provides quality information of the project like test reports, dependency list etc.
•It provides a uniform build system with its project object Model.
Maven is a project management tool, provides concept of a project object model (POM) file
to manage project’s build, dependency and documentation. The most powerful feature is
able to download the project dependency libraries automatically
Let see how to configure eclipse with maven for selenium: (assuming eclipse is already there
or you can go to http://www.eclipse.org/downloads/packages/release/juno/sr2)
 Launch the Eclipse IDE.
 Create a new project by selecting File |New | Other from Eclipse Main Menu.
 On the New dialog, select Maven |Maven Project as shown in the following
screenshot:

Mr. Suresh Page 120 of 139


Selenium Training by Suresh

 Next, the New Maven Project dialog will be displayed. Select the Create a
simple project (skip archetype selection) check-box and set everything to default and
click on the Next button as shown in the following screenshot:

 On the New Maven Project dialog box, enter base package name (like
com.myproject.app) in Group Id and project name (like myproject) in Artifact Id
textboxes. You can also add a name and description. Set everything to default and
click on the Finish button as shown in the following screenshot:

Mr. Suresh Page 121 of 139


Selenium Training by Suresh
 Eclipse will create the myproject project with a structure (in Package Explorer)
similar to the one shown in the following screenshot:

 Right-click on JRE System Library [J2SE-1.5] and select the Properties option
from the menu.
 On the Properties for JRE System Library [J2SE-1.5] dialog box, make sure
Workspace default JRE (jre7) is selected. If this option is not selected by default,
select this option.
Note: The JRE version might change based on the Java version installed on your machine.
 Click on the OK button to save the change as shown in the following screenshot:

 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.
 Add the WebDriver and testng 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>com.myproject.app</groupId>
<artifactId>myproject</artifactId>
<version>0.0.1-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>3.12.0</version>
</dependency>
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>6.8.0</version>
Mr. Suresh Page 122 of 139
Selenium Training by Suresh
<scope>test</scope>
</dependency>
</dependencies>
</project>

Cucumber
What are the benefits?
1. It is helpful to involve business stakeholders who can't easily read code
2. Cucumber focuses on end-user experience
3. Style of writing tests allow for easier reuse of code in the tests
4. Quick and easy set up and execution
5. Efficient tool for testing
Introduction
Cucumber introduces the notion of “features” which describe the behavior you wish to test.
The Feature is then broken down into a number of different “scenarios” which comprise the
test you wish to execute which will subsequently validate the feature. Each scenario is further
broken down into a number of “steps” which describe the execution path of each scenario.
Typically, these follow a strict “given-when-then” format which aids consistency and
provides a clear Template for writing acceptance tests.
Testing with Cucumber
Cucumber is a testing framework that helps to bridge the gap between software developers
and business managers. Tests are written in plain language based on the behavior-driven
development (BDD) style of Given, When, Then, which any layperson can understand. Test
cases are then placed into feature files that cover one or more test scenarios. Cucumber
interprets the tests into the specified programming language and uses Selenium to drive the
test cases in a browser. Our tests are translated into Java code.
The Given, When, Then syntax is designed to be intuitive. Consider the syntax elements:
 Given provides context for the test scenario about to be executed, such as the point in
your application that the test occurs as well as any prerequisite data.
 When specifies the set of actions that triggers the test, such as user or subsystem actions.
 Then specifies the expected result of the test.

Steps to implement Selenium with Cucumber


1. Getting started - Open Eclipse and create a new Maven project

Mr. Suresh Page 123 of 139


Selenium Training by Suresh
2. Add Maven dependencies
In your pom.xml, add the following dependencies:
<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>com.trivadis</groupId>
<artifactId>cucumber-bdd</artifactId>
<version>0.0.1-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>info.cukes</groupId>
<artifactId>cucumber-picocontainer</artifactId>
<version>1.1.5</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>info.cukes</groupId>
<artifactId>cucumber-junit</artifactId>
<version>1.1.5</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>
3. Create a feature “hrms.feature” file. This file contain below scenario.
@LoginTest
Feature: Testing HRMS application
Scenario: Verify Login
Given Open HRMS application
When Typing User name and Password
Then Login page should be shown
4. Now need to create step definition file for above scenario and implement webdriver
automation code. So Create a java file “TC_501.java” and write below code:
package com.example;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import cucumber.api.java.en.Given;
import cucumber.api.java.en.Then;
import cucumber.api.java.en.When;
Mr. Suresh Page 124 of 139
Selenium Training by Suresh
public class TC_501{
public WebDriver driver;
@Given("^Open HRMS application$")
public void openbrowser(){
System.setProperty(“webdriver.gecko.driver”,”E:\\geckodriver.exe”);
driver = new FirefoxDriver();
driver.navigate().to("http://www.google.com/");
}
@When("^Typing User name and Password$")
public void login(){
System.out.println("Typing User name and Password");
}
@Then("^Login page should be shown$")
public void closebrowser(){
System.out.println("Login page should be shown");
}
}
5.Now create “TestRun.java” which defines cucumber-jvm configuration and write
below code
package com.example;
import org.junit.runner.RunWith;
import cucumber.api.junit.Cucumber;
@RunWith(Cucumber.class)
@Cucumber.Options(format={"pretty","html:target/cucumber-html-
report"},tags={"@LoginTest"})
public class TestRun
{

}
6. Now you can exeute the program by using two option one is feature file and another one is
TestRun
Executing by Feature File - Rightclick on hrms.feature file and Select Run as Cucumbe
feature. Results log need to shown as below

Executing by TestRun File - Rightclick on TestRun file and Select Run as JUnitTest.
Results shown in the path(C:\Training1\Cumber_HRMS\target\cucumber-html-report) as
below.

Mr. Suresh Page 125 of 139


Selenium Training by Suresh

Project structure shown as below.

Sikuli Automation Tool


Introduction
Sikuli is a tool to automate graphical user interfaces (GUI) using “Visual Image Match”
method. In Sikuli, all the web elements should be taken as an image and stored inside the
project. Sikuli will trigger GUI interactions based on the image visual match, the image
which we have passed as the parameter along with all methods.
Sikuli can be very much useful to automate flash objects (which do not have ID or name). It
can be useful in the situation, where we have a stable GUI (i.e. GUI components not
changing).
Even Window based applications can also be automated using Sikuli. Sikuli provides very
friendly Sikuli-script.jar, which can be easily used together with Selenium WebDriver. We
can even automate Adobe Video/Audio player, Flash Games on website using Sikuli. With
simple API, it makes coding easier.
Practical Uses
1. Sikuli can be used to automate Flash Objects / Flash Websites.
2. It can be useful to automate Window based application. We can automate what we are
seeing on the screen.
3. It provides, simple API. i.e. all methods can be accessed using screen class object.
4. It can be easily integrated with Selenium and all other tools.

Mr. Suresh Page 126 of 139


Selenium Training by Suresh
5. Using Sikuli we can automate desktop applications.
6. Most of the automation testing tools will not support flash object automation (E.g.
Selenium). Sikuli provides extensive support to automate flash objects.
7. It uses powerful “Visual Match” mechanism to automate desktop & flash objects.
Benefits
 Open source Tool.
 One of the biggest advantages of Sikuli is that, it can easily automate Flash objects.
 It makes easy to automate windows application.
 When you’re testing an application under development and you don’t know the
ID/name of the elements, then you can go with Sikuli. It will check the appearance of
the image and if match found, it will interact with the image accordingly.
Prerequisites:
Before getting started, we need to download and install the following software:
 Any screenshot capturing tool (E.g. DuckCapture, or qSnap or Snipping Tool)
 JDK
 Eclipse (detailed steps here to install JDK and Eclipse)
Steps to Create Sikuli Java Project:
Step #1: Sikuli Download – Download Sikuli from here
(http://www.sikuli.org/download.html).
Step #2: Extract the zip file which you’ve downloaded. It will contain sikuli-script.jar file.
Save this extracted file in your local file system.
Step #3: Open Eclipse.
Step #4: Create a java project File -> New -> Java Project
Step #5:
1. Right Click on the project
2. Go to Build path -> Configure Build Path
3. Switch to Libraries tab
4. Click “Add External Jars” button and Add Sikuli-Script.jar in the Build path.
5. Click “Ok”

Sikuli-script.jar will be added to your project build path. You’re done. Now you can start
writing Sikuli scripts inside this project.

Mr. Suresh Page 127 of 139


Selenium Training by Suresh
Example for - SIKULI + SELENIUM WEBDRIVER
import org.junit.Test;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.sikuli.script.App;
import org.sikuli.script.FindFailed;
import org.sikuli.script.Pattern;
import org.sikuli.script.Screen;
public class sikuliFirstTest {
@Test
public void functionName() throws FindFailed {
// Create a new instance of the Firefox driver
System.setProperty(“webdriver.gecko.driver”,”E:\\geckodriver.exe”);
WebDriver driver = new FirefoxDriver();
// And now use this to visit Google
driver.get("http://www.google.com");
//Create and initialize an instance of Screen object
Screen screen = new Screen();
//Add image path
Pattern image = new Pattern("C:\\searchButton.png");
//Wait 10ms for image
screen.wait(image, 10);
//Click on the image
screen.click(image);
}
}

Example for - TC_adding new emp –Clicking on browse button and selecting an file to
upload an image using WebDriver with Sikuli
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.sikuli.script.Pattern;
import org.sikuli.script.Screen;
public class WinPopup {
public static void main(String[] args) throws InterruptedException {
System.setProperty(“webdriver.gecko.driver”,”E:\\geckodriver.exe”);
WebDriver driver=new FirefoxDriver();
driver.navigate().to("http://127.0.0.1/orangehrm-2.6/login.php");
driver.findElement(By.xpath("//input[@type='text']")).sendKeys("admin");
driver.findElement(By.xpath("//input[@type='password']")).sendKeys("admin");
driver.findElement(By.xpath("//input[@type='Submit']")).click();
Thread.sleep(5000L);
//Selecting the frame
driver.switchTo().frame("rightMenu");

Mr. Suresh Page 128 of 139


Selenium Training by Suresh
//Clicking on Add Button
driver.findElement(By.xpath("//*[@id='standardView']/div[3]/div[1]/input[1]")).click();
driver.manage().timeouts().implicitlyWait(2, TimeUnit.SECONDS);
driver.findElement(By.xpath("//*[@id='txtEmpLastName']")).sendKeys("aaa");
driver.findElement(By.xpath("//*[@name='txtEmpFirstName']")).sendKeys("bbb");
try {
//Create and initialize an instance of Screen object
Screen screen = new Screen();
//Add image path
Pattern browse = new Pattern("C:\\Images\\Browse.png");
Pattern pictures = new Pattern("C:\\images\\pictures.png");
Pattern samplepictures = new Pattern("C:\\images\\samplepictures.png");
Pattern Desertimage = new Pattern("C:\\images\\Desertimage.png");
Pattern Openbtn = new Pattern("C:\\images\\Openbtn.png");
//Wait 10ms for image
screen.wait(browse, 10);
//Click on the image
screen.click(browse);
screen.wait(pictures, 10);
screen.click(pictures);
screen.wait(samplepictures, 10);
screen.click(samplepictures);
screen.wait(Desertimage, 10);
screen.click(Desertimage);
screen.wait(Openbtn, 10);
screen.click(Openbtn);
}
catch(Exception e) {
System.out.println(e);
}
driver.findElement(By.xpath("//*[@id='btnEdit']")).click();
Thread.sleep(2000L);
System.out.println("New Employee Added");
driver.switchTo().defaultContent();
driver.findElement(By.xpath("//*[@id='option-menu']/li[3]/a")).click();
driver.quit();
}
}

Mr. Suresh Page 129 of 139


Selenium Training by Suresh
Selenium GRID
What is need of Selenium Grid?
Selenium Grid– A distributed test execution environment to speed up the execution of a test
pass.
Here are few problems with such a setup:
1. What if you want to execute your test cases for different Operating Systems?
2. How to run your test cases in different version of same browser?
3. How to run your test cases for multiple browsers?
4. Why a scenario should wait for execution of other test cases even if it does not depend
upon any test cases?
All these problems are addressed in Selenium GRID.
How we can overcome to these problems
Basically Grid architecture is based on master slave architecture. Master machine distributes
test cases to different slave machines.
There are 2 versions of Grid available. Selenium Grid 2.0 is the latest from Selenium.
Selenium 1.0 was the earlier version. Most of the Selenium experts prefer using Selenium
Grid 2.0 as it is packed with new features. Selenium Grid 2.0 supports both Selenium RC and
Selenium WebDriver scripts.
Benefits of Selenium Grid:
1. Selenium Grid gives the flexibility to distribute your test cases for execution.
2. Reduces batch processing time.
3. Can perform multi browser testing.
4. Can perform multi OS testing.
Basic terminology of Selenium Grid:
Hub: Hub is central point to the entire GRID Architecture which receives all requests. There
is only one hub in the selenium grid. Hub distributes the test cases across each node.
Node: There can be multiple nodes in Grid. Tests will run in nodes. Each node communicates
with the Hub and performs test assigned to it.

Install Selenium GRID


Step 1: Download Selenium Server jar file from Selenium’s official website which is
formerly known as Selenium RC Server and save it at any location on the local disk.
URL of selenium HQ: http://www.seleniumhq.org/download/
Step 2: Open command prompt and navigate to folder where the server is located. Run the
server by using below command
java -jar selenium-server-standalone-3.12.0.jar -role hub
http://localhost:4444/grid/console --- To check the node status
The hub will use the port 4444 by default. This port can be changed by passing the different
port number in command prompt provided the port is open and has not been assigned a task.
Status can be checked by using the web interface:
Mr. Suresh Page 130 of 139
Selenium Training by Suresh
Step 3: Go to the other machine where you intend to setup Nodes. Open the command
prompt and and navigate to folder where the server is located and then run the below line.
java -jar selenium-server-standalone-3.12.0.jar -role node -hub
http://localhost:4444/grid/register -port 5556
{OR}
java -Dwebdriver.gecko.driver= D:\Suresh_Selenium\Drivers\geckodriver.exe -jar
selenium-server-standalone-3.12.0.jar -role node -hub
http://localhost:4444/grid/register -port 5556
Note : Once hub and node started successfully then you can start the executing webdriver
program.

Sample program for Grid


import java.net.MalformedURLException;
import java.net.URL;
import org.openqa.selenium.By;
import org.openqa.selenium.Platform;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;
public class Gr {
public static void main(String[] args) throws Exception {
DesiredCapabilities caps = DesiredCapabilities.firefox();
//caps.setVersion("20");
caps.setPlatform(Platform.WINDOWS);
URL urlHub = null;
try {
urlHub = new URL("http://localhost:5556/wd/hub");
}
catch (MalformedURLException e) {
e.printStackTrace();
}
RemoteWebDriver driver = new RemoteWebDriver(urlHub, caps);
driver.navigate().to("http://127.0.0.1/orangehrm-2.6/login.php");
//driver.navigate().to("http://www.google.com/");
Thread.sleep(2000);
System.out.println(driver.getTitle());
System.out.println("Application opned");
driver.findElement(By.name("txtUserName")).sendKeys("admin");
driver.findElement(By.xpath("//input[@name='txtPassword']")).sendKeys("admin");
driver.findElement(By.name("Submit")).click();
Thread.sleep(3000);
System.out.println("Login completed");
driver.findElement(By.linkText("Logout")).click();
System.out.println("Logout completed");
driver.close();
}
}
Mr. Suresh Page 131 of 139
Selenium Training by Suresh
Some other examples - For Instance if you want to use only IE you can start the node by
using below command:
java -jar selenium-server-standalone-2.41.0.jar -role webdriver -hub
http://localhost:4444/grid/register -port 5556 -browser browserName=iexplore
Verify the browser Type along with other details in GRID Console by clicking on view
config.

Similarly for Firefox:


java -jar selenium-server-standalone-2.41.0.jar -role webdriver -hub
http://localhost:4444/grid/register -port 5556 -browser browserName=firefox

For Chrome:
java -jar selenium-server-standalone-2.41.0.jar -role webdriver -hub
http://localhost:4444/grid/register -port 5556 -browser browserName=chrome

There are few scenarios where you may need browser from each type i.e.: IE, Chrome and
Firefox.
For instance you may need to use 1 IE and 1 Firefox and 1 Chrome browser
java -jar selenium-server-standalone-2.41.0.jar -role webdriver -hub
http://localhost:4444/grid/register -port 5556 -browser browserName=iexplore
-browser browserName=firefox -browser browserName=chrome

Mr. Suresh Page 132 of 139


Selenium Training by Suresh

Grid Program Example – for WebDriver with TestNG


Prerequisite: Create Hub and nodes as explained earlier and TestNG should be configured in
eclipse.
public class GridExample {
@Test
public void mailTest() throws MalformedURLException{
DesiredCapabilities dr=null;
if(browserType.equals("firefox")){
dr=DesiredCapabilities.firefox();
dr.setBrowserName("firefox");
dr.setPlatform(Platform.WINDOWS);
}else{
dr=DesiredCapabilities.internetExplorer();
dr.setBrowserName("iexplore");
dr.setPlatform(Platform.WINDOWS);
}
RemoteWebDriver driver=new RemoteWebDriver(new
URL("http://localhost:4444/wd/hub"),dr);
driver.navigate().to("http://gmail.com");
driver.findElement(By.xpath("//input[@id='Email']")) .sendKeys("username");
driver.findElement(By.xpath("//input[@id='Passwd']")) .sendKeys("password");
driver.close();
}
As in the example you have to use RemoteWebDriver if you are using GRID and you have to
provide capabilities to the browser. You have to set the browser and platform as above.
In this example I have used platform as WINDOWS. You can use any platform as per your
requirement.
Version of browser can also be set by using dr.setVersion(“version”)

Serially Execution in multiple browsers


For Instance you need to run this test serially in multiple browsers you have to configure your
testng.xml .Below is the testng.xml suite for above test to run your test serially.
<?xml version="1.0" encoding="UTF-8"?>
<suite name="GRID SAMPLE TEST" thread-count="2">
<test name="GRID TEST WITH SERIAL EXECTION WITH BROWSER IE">
<parameter name ="browserType" value="IE"/>
<classes>

Mr. Suresh Page 133 of 139


Selenium Training by Suresh
<class name ="GridExample"/>
</classes>
</test>
<test name="GRID TEST WITH SERIAL EXECTION WITH BROWSER FF ">
<parameter name ="browserType" value="firefox"/>
<classes>
<class name ="GridExample"/>
</classes>
</test>
</suite>
To run the test parallel, you have to change your testng.xml like below.
<?xml version="1.0" encoding="UTF-8"?>
<suite name="GRID SAMPLE TEST" parllel="tests" thread-count="3">
<test name="GRID TEST WITH SERIAL EXECTION WITH BROWSER FF">
<parameter name ="browserType" value="firefox"/>
<classes>
<class name ="GridExample"/>
</classes>
</test>
<test name="GRID TEST WITH SERIAL EXECTION WITH BROWSER IE">
<parameter name ="browserType" value="IE"/>
<classes>
<class name ="GridExample"/>
</classes>
</test>
</suite>
Here in the testng.xml you have to specify parameter asparllel=“tests” and thread-count=“3”
describes the maximum number of threads to be executed in parallel.

WHAT IS WEB SERVICE?


A Web Service is a way to establish communication between two data sources over world
wide web (WWW), irrespective of their architecture, technology, and behavior. The
exchange of information takes place through XML or JSON files.
WHAT IS THE PROTOCOL USED IN WEB SERVICES?
Generally, the exchanges of information take place over HTTP or HTTPS protocol at the
application layer between two computers. One computer sends the request and other responds
with XML or JSON data.
Here there are no dependencies on OS, application or the programming languages. One
application which is built on .Net language may request data from another application which
is built on Java. All the data transfer would take place either in XML or JSON format.

Mr. Suresh Page 134 of 139


Selenium Training by Suresh

FEATURES OF WEB SERVICES


 Services will be available on the internet, intranet, VPN or cloud
 It is platform independent services and OS and programming independent as well
 This basically uses standard XML message
 This service is triggered with simple URL available over the internet
WHAT ARE THE COMPONENTS OF WEB SERVICES?
The basics of the following components are XML data parsing and communication using
HTTP or HTTPS protocol.
 SOAP (Simple Object Access Protocol)
 WSDL (Web Services Description Language)
 UDDI (Universal Description, Discovery, and Integration)
 REST (Representational State Transfer)

RESTful API Response Codes


Status Code Description
200 OK Successful.
201 Created Created.
400 Bad Request Bad input parameter. Error message should indicate which one and
why.
401 Unauthorized The client passed in the invalid Auth token. Client should refresh
the token and then try again.
403 Forbidden * Customer does not exist. * Application not registered. *
Application try to access to properties not belong to an App. *
Mr. Suresh Page 135 of 139
Selenium Training by Suresh
Application try to trash/purge root node. * Application try to
update content Properties. * Operation is blocked (for third-party
apps). * Customer account over quota.
404 Not Found Resource not found.
405 Method Not The resource does not support the specified HTTP verb.
Allowed
409 Conflict Conflict.
411 Length Required The Content-Length header was not specified.
412 Precondition Precondition failed.
Failed
429 Too Many Too many request for rate limiting.
Requests
500 Internal Server Servers are not working as expected. The request is probably valid
Error but needs to be requested again later.
503 Service Service Unavailable.
Unavailable

HTTP methods
Commonly used in REST based architecture.
GET − Provides a read only access to a resource.
POST − Used to create a new resource.
DELETE − Used to remove a resource.
PUT − Used to update existing resource or create a new resource.
Sample program to run api :
Note: Download and add rest assured jars to the respective project.

package Test;

import io.restassured.RestAssured;
import io.restassured.response.Response;

public class WebServ {

public static void main(String args[]) {


System.out.println("***Started******");
//Sending the request and getting the response from the server
Response rep =
RestAssured.get("http://samples.openweathermap.org/data/2.5/weather?q=London,uk&ap
pid=b6907d289e10d714a6e88b30761fae22");
int code = rep.statusCode();
System.out.println(code);
//Printing response time
System.out.println(rep.getTime());
Mr. Suresh Page 136 of 139
Selenium Training by Suresh
//printing the details in JSON format
Response repst =
RestAssured.get("http://samples.openweathermap.org/data/2.5/weather?q=London,uk&ap
pid=b6907d289e10d714a6e88b30761fae22");
String data = repst.asString();
System.out.println(data);
System.out.println("***Completed*****");
}
}

Selenium Interview Questions


1. Difference between Absolute path & Relative path.
2. Tell me some TestNG Annotations.
3. What are desiredcapabilities?
4. Difference between Selenium RC and Selenium Web driver.
5. Difference between Web driver listener and TestNG Listener.
6. Describe your framework.
7. Which is the best way to locate an element?
8. Why we refer Firefox driver to the web driver inheritance.
9. What are the features of TestNG?
10. What is the difference between thread.Sleep() and selenium. Set Speed ("2000")?
11. In what situation selenium finding element get fails?
12. What is the difference between "GET" and "NAVIGATE" to open a web page in
13. Please tell me the difference b/w implicitly Wait and Explicit wait.
14. How we can retrieve the dynamically changing Ids?
15. What is the difference between driver.Close() and driver.Quit () method?
16. How to scroll web element?--not browser—
17. What is the basic use of Firefox profiles and how can we use them using selenium?
18. How to put text in Facebook search box using selenium web driver.
23. What is Error Collector in TestNG? What is its use?
19. How can we get the font size, font color, font type used for a particular text on a web
page using Selenium web driver?
20. How to run tests in multiple browser parallel? Is there any other option other than
selenium grid?
21. How to prepare Customized html Report using TestNG in hybrid framework.
22. “What’s the hierarchy of TestNG annotations? Explain me about annotation hierarchy &
execution order?
23. Is it possible to test web services using selenium?
24. How to refresh a page without using context click?
25. Can u send a code for printing in selenium?
26. How to find broken images in a page using Selenium Web driver.
27. How to handle Ajax popup window?
28. How to handle auto complete box in web driver?
Mr. Suresh Page 137 of 139
Selenium Training by Suresh
29. How to get the name of browser using Web Driver?
30. How to handle colors in web driver?
31. How to pass parameters from testng.xml into test case.
32. How to get text from captcha image??
33. Is there a way to click hidden LINK in web driver?
34. What Class Extends Web Driver?
35. What are the APIs that support Web Driver?
36. How to disable cookies in browser.
37. What is Selenese?
38. Differences between QTP and selenium.
39. What is the MOST challenging test problem in my career in Automation?
40. “Suppose developer changed the existing image to new image with same xpath. Is test
case pass or fail?"
41. How does u handle dynamic elements without using xpath (with example?)
42. What are the different types of driver implementation?
43. Code for Opening Firefox browser?
44. Which repository you have used to store the test scripts?
45. How to work with dropdown in web driver?
46. How to work with dynamic web table?
47. Detail about TestNG Test Output folder.
48. In frame if no frame Id as well as no frame name then which attribute I should consider
throughout our script.
49. What is object repository?
50. TestNG vs. Junit?
51. What is the difference between @before method and @beforeclass.
52. Can we run group of test cases using TestNG?
53. What are the different assertions in SIDE?
54. How to store a value which is text box using web driver?
55. How to handle alerts and confirmation boxes. Confirmation boxes and Alerts are handled
in same way in selenium.
56. How to mouse hover on an element?
57. How to switch between the windows?
58. How to switch between frames?
59. Difference between the selenium1.0 and selenium 2.0?
60. Difference between find element () and findelements ()?
61. How to take the screen shots in selenium
62. What is the default time for selenium Ide and webdriver?
63. Write down scenarios which we can't automate?
64. In TestNG I have some test's Test1-Test2-Test3-Test4-Test5I want to run my
execution order is Test5-Test1-Test3-Test2-Test4.How do you set the execution order can
you explain for that?
65. Differences between jxl and ApachePOI.
66. What is default port no?
Mr. Suresh Page 138 of 139
Selenium Training by Suresh
67. Does Selenium support https protocols?
68. Majorly asked test scenario with framework in Interviews?
69. Difference between assert and verify in seleniumIDE
70.Explain the pupose & advantages of Robot class
71. Name 5 different exceptions you had in selenium web driver and mention what
instance you got it and how do you resolve it?
72. How do you manage the code versions in your project?
73. How to know all the methods supported in web driver and its syntax.
74. How do you create html test report from your test script?
75. Can you explain Selenium Mobile Automation?
76. What mobile devices it may Support?
77. What is the difference between single and double slash in Xpath?
78. What are the test types supported by Selenium?
79. In what all case we have to go for “JavaScript executor”.
80. Explain your roles and responsibilities in current project.

Mr. Suresh Page 139 of 139

You might also like