Selenium With Java

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 205

Selenium Automation with CI/CD

Tools using Java

26/11/2019

Arman Khandelwal
Software Developer in Test
[email protected]

1|P a g e
TABLE OF CONTENTS

Chapter 1..............................................................................................................................................................................................6
Introduction to Core Java.....................................................................................................................................................................6
What is an Object.............................................................................................................................................................................6
What is Class.....................................................................................................................................................................................7
Methods in Class...............................................................................................................................................................................7
Constructors in Java..........................................................................................................................................................................9
Static Keyword................................................................................................................................................................................11
Inheritance in Java..........................................................................................................................................................................13
Polymorphism in Java.....................................................................................................................................................................14
Method Overloading in Java......................................................................................................................................................14
Method Overriding in Java.........................................................................................................................................................16
Super keyword in java................................................................................................................................................................17
Final Keyword in Java.................................................................................................................................................................17
Encapsulation in Java......................................................................................................................................................................19
Access Modifier..........................................................................................................................................................................20
Abstraction in Java..........................................................................................................................................................................21
Abstract class..............................................................................................................................................................................21
Interface.....................................................................................................................................................................................22
Control Statements.........................................................................................................................................................................24
If-else statement........................................................................................................................................................................24
Switch Statement.......................................................................................................................................................................26
For Loop......................................................................................................................................................................................27
While Loop.................................................................................................................................................................................28
do-while Loop.............................................................................................................................................................................29
Exception Handling in Java.............................................................................................................................................................30
try block......................................................................................................................................................................................31
catch block.................................................................................................................................................................................31
Multi-catch block........................................................................................................................................................................32
Nested try block.........................................................................................................................................................................33
finally block................................................................................................................................................................................34
throw keyword...........................................................................................................................................................................35
throws keyword.........................................................................................................................................................................35
File Handling in Java.......................................................................................................................................................................37
Create a File................................................................................................................................................................................38
Get File Information...................................................................................................................................................................39
Write to a File.............................................................................................................................................................................39
Read from a File.........................................................................................................................................................................40

2|P a g e
Collections framework in Java........................................................................................................................................................41
ArrayList class.............................................................................................................................................................................43
LinkedList class...........................................................................................................................................................................45
List Interface...............................................................................................................................................................................47
HashSet class..............................................................................................................................................................................48
LinkedHashSet class...................................................................................................................................................................48
TreeSet class...............................................................................................................................................................................49
Map Interface.............................................................................................................................................................................50
HashMap class............................................................................................................................................................................50
LinkedHashMap class.................................................................................................................................................................51
TreeMap class............................................................................................................................................................................52
Hashtable class...........................................................................................................................................................................52
Chapter 2............................................................................................................................................................................................54
Getting started with Selenium WebDriver Basics.............................................................................................................................54
Introduction and features of Selenium..........................................................................................................................................54
Selenium WebDriver Architecture Simplified................................................................................................................................54
Importance of Locators identifiers in Selenium.............................................................................................................................54
Identifying locators (id, name, linkText, PartialLinkText) with developer tool..........................................................................55
Identifying locators (ClassName, TagName) with developer tool.............................................................................................55
Generating customized CSS from html attributes.....................................................................................................................56
Identifying Xpath........................................................................................................................................................................57
Handling Mouse Interactions.........................................................................................................................................................60
DesiredCapabilities in Selenium WebDriver...................................................................................................................................62
Handling Multiple Windows...........................................................................................................................................................62
How to handle frames....................................................................................................................................................................63
Handling Drop-Downs Mechanism.................................................................................................................................................67
Static dropdowns with Select WebDriver API............................................................................................................................67
Looping UI Dropdown................................................................................................................................................................68
Dynamic Dropdown....................................................................................................................................................................69
Auto Suggestive Dropdowns......................................................................................................................................................70
Handling Java Alerts........................................................................................................................................................................71
Handling Dynamic Web Tables.......................................................................................................................................................72
Handling Checkbox.........................................................................................................................................................................76
Synchronization in Selenium (Waits)..............................................................................................................................................77
Implicit wait................................................................................................................................................................................77
Explicit Wait................................................................................................................................................................................77
Fluent Wait.................................................................................................................................................................................78
How to take Screenshots................................................................................................................................................................79
Handling Calendar UI......................................................................................................................................................................80
3|P a g e
Chapter 3............................................................................................................................................................................................81
Advanced Techniques of Selenium WebDriver.................................................................................................................................81
Introduction to Maven...................................................................................................................................................................81
Installing and configuring Maven...............................................................................................................................................81
Terminologies of Maven............................................................................................................................................................81
What is POM.xml file in maven..................................................................................................................................................82
Build phases in Maven...............................................................................................................................................................82
What is maven plugins...............................................................................................................................................................84
Introduction to TestNG Testing framework...................................................................................................................................84
Annotations in TestNG...............................................................................................................................................................85
How to execute TestNG tests.....................................................................................................................................................88
How to Ignore or disabled tests.................................................................................................................................................88
Grouping of tests........................................................................................................................................................................90
Dependency of tests...................................................................................................................................................................91
Test Priority................................................................................................................................................................................93
Parametrization in tests.............................................................................................................................................................97
Listeners in TestNG..................................................................................................................................................................100
Data Driven using different file formats.......................................................................................................................................105
Read and Write Data from Excel File using Apache POI..........................................................................................................105
Passing data to DataProvider from Excel Sheet.......................................................................................................................108
Read data to DataProvider from JSON File..............................................................................................................................113
Read data from properties file.................................................................................................................................................116
Database Connection using JDBC.................................................................................................................................................119
Converting JDBC Results into Java Object with POJO classes..................................................................................................119
Jackson API to convert Java objects into JSON file formats.....................................................................................................121
Parse JSON file into Java Object to send the data through getter methods...........................................................................123
Reports Generation with Extent Report and TestNG...................................................................................................................123
Headless Browser testing using HTMLUnitDriver........................................................................................................................127
Cross Browser Testing with Selenium Grid..................................................................................................................................127
Introduction to Grid.................................................................................................................................................................127
Selenium Grid Architecture......................................................................................................................................................128
How to Set Up Selenium Grid? Using Command Line.............................................................................................................128
Designing Test Scripts That Can Run on the Grid.....................................................................................................................130
Integration of Jenkins with Selenium...........................................................................................................................................132
File Uploading using AutoIt..........................................................................................................................................................133
What is AutoIt..........................................................................................................................................................................133
Recording of AutoIT Script.......................................................................................................................................................135
Upload file in Selenium using AutoIt........................................................................................................................................135
File Uploading using Sikuli............................................................................................................................................................140
4|P a g e
What is Sikuli............................................................................................................................................................................140
Why to use Sikuli......................................................................................................................................................................141
Steps to download and get the sikuli jar..................................................................................................................................141
Chapter 4..........................................................................................................................................................................................144
Different Types Frameworks in Selenium WebDriver....................................................................................................................144
What is test framework in Selenium............................................................................................................................................144
Data Driven Test Framework........................................................................................................................................................144
Keyword Driven Test Framework.................................................................................................................................................145
Behavior Driven Development (BDD) Test Framework................................................................................................................146
Page Object Model (POM) & Page Factory..................................................................................................................................149
Chapter 5..........................................................................................................................................................................................151
Introduction to CI and CD tools.......................................................................................................................................................151
Introduction to Docker.................................................................................................................................................................151
What is Docker and How it helps in Automation?...................................................................................................................151
How to install Docker into Machines with Prerequisites needed?..........................................................................................152
Understand working with DockerHub.....................................................................................................................................155
Implementation of Docker to Automate tests.........................................................................................................................155
Docker compose file in creating Nodes and Hub.....................................................................................................................156
Integrate Docker tests with Maven and Jenkins......................................................................................................................157
Introduction to Jenkins Pipelines.................................................................................................................................................157
What are Jenkins Pipelines?.....................................................................................................................................................157
Jenkin Pipeline View Plugin to chain the Jobs..........................................................................................................................158
Groovy script Syntax to build pipeline.....................................................................................................................................161
Importance of “JenkinsFile” and its Keywords for Pipeline building.......................................................................................162
Chapter 6..........................................................................................................................................................................................165
Git Commands and its uses – Version Control System...................................................................................................................165
Introduction to Git........................................................................................................................................................................165
Creating Git Config and Repositories...........................................................................................................................................168
How to resolve Merge Conflicts with Git?....................................................................................................................................170
Chapter 7..........................................................................................................................................................................................172
Agile Scrum Methodology................................................................................................................................................................172
What is Agile Software Development?.........................................................................................................................................172
Different Ceremonies in Agile......................................................................................................................................................172
What is Story Point in Agile? How to Estimate a User Story?......................................................................................................174
What Is Velocity in Agile Scrum Methodology.............................................................................................................................175

CHAPTER 1
5|P a g e
INTRODUCTION TO CORE JAVA
WHAT IS AN OBJECT

In Object-Oriented programming techniques, we design a program using objects and classes. An entity that has state and
Behavior is known as an object.

An object has the below characteristics:

1. State: Represents the data (value) of an object.


2. Behavior: Represents the Behavior (functionality) of an object.

Create Object

In Java, an object is created from a class.

package corejava;

public class ClassDemo


{
// Create Method
public void methodDemo()
{
System.out.println("Method Example");
}

public static void main(String[] args)


{
// Create Object of Class
ClassDemo objClassDemo = new ClassDemo();

// Call Non Static Method


objClassDemo.methodDemo();
}

Create Multiple Objects

We can create multiple objects of one class

package corejava;

public class ClassDemo


{
// Create Method
public void methodDemo()
{
System.out.println("Method Without Parameters");

6|P a g e
}

// Create Method with Parameters


public void methodWithParam(String name, int age)
{
System.out.println("First Name : "+name+" is : "+age+" years old");
}

public static void main(String[] args)


{
// Create Object of Class
ClassDemo objClassDemo = new ClassDemo();

// Create Second Method of Class


ClassDemo obj2ClassDemo = new ClassDemo();

// Call Non Static Method


objClassDemo.methodDemo();

// Call Method with Parameters


objClassDemo.methodWithParam("Arman Khandelwal", 29);
obj2ClassDemo.methodWithParam("Arman Khandelwal", 29);
}
}

WHAT IS CLASS

A class is a group of objects which have common properties. It is a template from which objects are created.

A class in Java can contain:

 Fields
 Methods
 Constructors
 Blocks
 Nested class and interface

METHODS IN CLASS

In Java, a method is like a function which is used to expose the Behavior of an object. A method is a block of code which only
runs when it is called. We can pass data, known as parameters, into a method. Methods are used to perform certain actions.

Why we use methods because we will reuse the code i.e. define the code once and use it many times.

Create a Method

A method must be declared within a class. It is defined with the name of the method, followed by parentheses (). Java provides
some pre-defined methods, such as System.out.println(), but we can also create our own methods to perform certain
actions.

7|P a g e
Call a Method

To call a method in Java, write the method's name followed by two parentheses () and a semicolon;

 Call Method directly without object creation, to do so we need to create the static method because static method
belongs to the Class not to the object.

package corejava;

public class ClassDemo


{
public static void main(String[] args)
{
System.out.println("First Section of KT - Core Java!!!");
// Call Static Method
methodDemo();
}

// Create Method
public static void methodDemo()
{
System.out.println("Method Example");
}
}

Output:

 Call method with the help of object

package corejava;

public class ClassDemo


{
// Create Method
public void methodDemo()
{
System.out.println("Method Example");
}

public static void main(String[] args)


{
// Create Object of Class
ClassDemo objClassDemo = new ClassDemo();
8|P a g e
// Call Non Static Method
objClassDemo.methodDemo();
}
}

Output:

Parameters and Arguments in Method

Information can be passed to methods as parameter. Parameters act as variables inside the method. Parameters are specified
after the method name, inside the parentheses. We can add as many parameters as we want, just separate them with a comma.

package corejava;

public class ClassDemo


{
// Create Method
public void methodDemo()
{
System.out.println("Method Without Parameters");
}

// Create Method with Parameters


public void methodWithParam(String name, int age)
{
System.out.println("First Name : "+name+" is : "+age+" years old");
}

public static void main(String[] args)


{
// Create Object of Class
ClassDemo objClassDemo = new ClassDemo();

// Call Non Static Method


objClassDemo.methodDemo();

// Call Method with Parameters


objClassDemo.methodWithParam("Arman Khandelwal", 29);
}
}

9|P a g e
Output:

CONSTRUCTORS IN JAVA

In Java, a constructor is a block of codes similar to the method. It is called when an instance of the class is created. At the time of
calling constructor, memory for the object is allocated in the memory. It is a special type of method which is used to initialize the
object. Every time an object is created using the new() keyword, at least one constructor is called.

It calls a default constructor if there is no constructor available in the class. In such case, Java compiler provides a default
constructor by default.

Rules for Creating the Java Constructor

There are three rules defined for the constructor.

1. Constructor name must be the same as its class name


2. A Constructor must have no explicit return type i.e. void etc.
3. A Java constructor cannot be abstract, static, final, and synchronized

Note: We can use access modifiers while declaring a constructor. It controls the object creation. In other words, we can have
private, protected, public or default constructor in Java.

There are two types of constructors in Java

1. no-arg constructor or we say default constructor


2. Parameterized constructor.

Note: It is called constructor because it constructs the values at the time of object creation. It is not necessary to write a
constructor for a class. It is because java compiler creates a default constructor if our class doesn't have any.

Default Constructor

A constructor is called "Default Constructor" when it doesn't have any parameter.

package corejava;

public class ConstructorEx


{
// Create Default Constructor
ConstructorEx()
{
System.out.println("Default Constructor Example");
}

public static void main(String[] args)


{
ConstructorEx objConstructorEx = new ConstructorEx();
}

10 | P a g e
}

Output:

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

Why Java Compiler creates default constructor automatically, what is the purpose for the same?

The default constructor is used to provide the default values to the object like 0, null, etc. depending on the type.

package corejava;

public class ConstructorEx


{
int age;
String name;

// Create Method
public void details()
{
System.out.println("Name : "+name+" and age : "+age);
}

public static void main(String[] args)


{
ConstructorEx objConstructorEx = new ConstructorEx();
objConstructorEx.details();
}
}

Output:

We are not creating any constructor so compiler provides us a default constructor. Here 0 and null values are provided by
default constructor.

Java Parameterized Constructor

A constructor which has a specific number of parameters is called a parameterized constructor.

What is the reason why we parameterised constructor?

11 | P a g e
The parameterized constructor is used to provide different values to distinct objects. However, we can provide the same values
also.

package corejava;

public class ConstructorEx


{
int age;
String name;

// Create Default Constructor


ConstructorEx(String name, int age)
{
this.name = name;
this.age = age;
}

// Create Method
public void details()
{
System.out.println("Name : "+name+" and age : "+age);
}

public static void main(String[] args)


{
ConstructorEx objConstructorEx = new ConstructorEx("Arman Khandelwal", 29);
objConstructorEx.details();
}
}

Output:

Difference between constructor and method in Java

Constructor Method

12 | P a g e
A constructor is used to initialize the state of an object. A method is used to expose the Behavior of an object.
A constructor must not have a return type. A method must have a return type.
The constructor is invoked implicitly. The method is invoked explicitly.

The Java compiler provides a default constructor if we


The method is not provided by the compiler in any case.
don't have any constructor in a class.

The constructor name must be same as the class name. The method name may or may not be same as the class name.

Does constructor return any value?

Yes, it is the current class instance, we cannot use return type yet it returns a value.

Can constructor perform other tasks instead of initialization?

Yes, like object creation, starting a thread, calling a method, etc. We can perform any operation in the constructor as we
perform in the method.

STATIC KEYWORD

The static keyword in Java is used for memory management mainly. We can apply java static keyword with variables, methods,
blocks and nested class. The static keyword belongs to the class than an instance of the class.

The static can be:

 Variable (also known as a class variable)


 Method (also known as a class method)
 Block
 Nested class

Static variable

If we declare any variable as static, it is known as a static variable. The static variable can use to refer to the common property of
all objects, which is not used unique for each object. For example, the company name of employees etc.

The static variable gets memory only once in the class area at the time of class loading.

What is the problem without static variable?

Suppose there are 500 employees in the organization, now all instance data members will get memory each time when the
object is created. All employees have its unique employee ID, so instance data member is good in such case.

Here, "company name" refers to the common property of all objects. If we make it static, this field will get the memory only
once.

package corejava;

public class ConstructorEx


{
int empID;
String name;
int age;
static String companyName = "TCS";

13 | P a g e
// Constructor with one more parameter
ConstructorEx(String name, int age, int empID)
{
this.name = name;
this.age = age;
this.empID = empID;
}

// Create Method
public void details()
{
System.out.println(name+" is "+age+" years old having employee ID "+empID+" from
"+companyName);
}

public static void main(String[] args)


{
ConstructorEx objConstructorEx = new ConstructorEx("Arman Khandelwal", 29,
1689012);

objConstructorEx.details();
}
}

Output:

Static method

If we apply static keyword with any method, it is known as static method.

 A static method belongs to the class rather than the object of a class.
 A static method can be invoked without the need for creating an instance of a class.
 A static method can access static data member and can change the value of it.

Restrictions for the static method

There are two main restrictions for the static method. They are:

1. The static method cannot use non static data member or call non-static method directly.
2. this and super cannot be used in static context.

Why is the Java main method static?

14 | P a g e
It is because the object is not required to call a static method. If it were a non-static method, JVM creates an object first then call
main() method that will lead the problem of extra memory allocation.

INHERITANCE IN JAVA

Inheritance in Java is a mechanism in which one object acquires all the properties and behaviours of a parent object. It is an
important part of OOPs (Object Oriented programming system).

The idea behind inheritance in Java is that we can create new classes that are built upon existing classes. When we inherit from
an existing class, we can reuse methods and fields of the parent class. Moreover, we can add new methods and fields in our
current class also.

Inheritance also known as a parent-child relationship.

The extends keyword indicates that we are making a new class that derives from an existing class. The meaning of " extends" is
to increase the functionality. In the terminology of Java, a class which is inherited is called a parent or superclass, and the new
class is called child or subclass.

Types of inheritance in Java

On the basis of class, there can be three types of inheritance in Java. In java programming, multiple and hybrid inheritance is
supported through interface only

 Single
 Multilevel
 Hierarchical

Note: Multiple inheritance is not supported in Java through class. When one class inherits multiple classes, it is known as
multiple inheritance.

package corejava;

public class ParentInheritanceEx


{
void empDetails()
{
System.out.println("In ParentSingleInheritanceEx Class");
}
}

class SubInheritanceEx extends ParentInheritanceEx


{
public static void main(String[] args)
{
SubInheritanceEx objSubInheritanceEx = new SubInheritanceEx();
objSubInheritanceEx.empDetails();
}
}

Output:

15 | P a g e
Why multiple inheritance is not supported in java?

To reduce the complexity and simplify the language, multiple inheritance is not supported in java.

Consider a scenario where A, B, and C are three classes. The C class inherits A and B classes. If A and B classes have the same
method and we call it from child class object, there will be ambiguity to call the method of A or B class.

Since compile-time errors are better than runtime errors, Java renders compile-time error if we inherit 2 classes. So whether we
have same method or different, there will be compile time error.

POLYMORPHISM IN JAVA

Polymorphism in java is a concept by which we can perform a single action by different ways. Polymorphism is derived from 2
Greek words: poly and morphs. The word "poly" means many and "morphs" means forms. So polymorphism means many
forms.

There are two types of polymorphism in java: compile time polymorphism and runtime polymorphism. We can perform
polymorphism in java by method overloading and method overriding.

If we overload static method in java, it is the example of compile time polymorphism.

METHOD OVERLOADING IN JAVA


If a class has multiple methods having same name but different in parameters, it is known as Method Overloading.

If we have to perform only one operation, having same name of the methods increases the readability of the program.

Suppose we have to perform addition of the given numbers but there can be any number of arguments, if we write the method
such as a(int,int) for two parameters, and b(int,int,int) for three parameters then it may be difficult for us as well as other
programmers to understand the Behavior of the method because its name differs.

So, we perform method overloading to figure out the program quickly.

Different ways to overload the method

There are two ways to overload the method in java

1. By changing number of arguments


2. By changing the data type

Note: In java, Method Overloading is not possible by changing the return type of the method only.

Why Method Overloading is not possible by changing the return type of method only

In java, method overloading is not possible by changing the return type of the method only because of ambiguity.

Method overloading by changing number of arguments

In this example, we have created two methods, first add() method performs addition of two numbers and second add method
performs addition of three numbers

package corejava;

16 | P a g e
public class MethodOverloadingEx
{
int add(int num1, int num2)
{
return num1+num2;
}

int add(int num1, int num2, int num3)


{
return num1+num2+num3;
}
public static void main(String[] args)
{
MethodOverloadingEx objMethodOverloadingEx = new MethodOverloadingEx();
System.out.println("Method with 2 parameters : "+objMethodOverloadingEx.add(5,
3));
System.out.println("Method with 3 parameters : "+objMethodOverloadingEx.add(5, 3,
2));
}
}

Method overloading by changing data type of arguments

In this example, we have created two methods that differs in data type. The first add method receives two integer arguments
and second add method receives two double arguments.

package corejava;

public class MethodOverloadingEx


{
int add(int num1, int num2)
{
return num1+num2;
}
double add(double num1, double num2)
{
return num1+num2;
}
public static void main(String[] args)
{
MethodOverloadingEx objMethodOverloadingEx = new MethodOverloadingEx();
System.out.println("Method with 2 parameters : "+objMethodOverloadingEx.add(5,
3));
System.out.println("Method with 3 parameters : "+objMethodOverloadingEx.add(5.3,
3.2));
}
}

17 | P a g e
Output:

METHOD OVERRIDING IN JAVA


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

Usage of Java Method Overriding

 Method overriding is used to provide the specific implementation of a method which is already provided by its
superclass.
 Method overriding is used for runtime polymorphism

Rules for Java Method Overriding

 The method must have the same name as in the parent class
 The method must have the same parameter as in the parent class.
 There must be an inheritance.

package corejava;

class MethodOverridingEx
{
int operation(int num1, int num2)
{
return num1+num2;
}
}
class SubClassMethodOverridingEx extends MethodOverridingEx
{
int operation(int num1, int num2)
{
return num1-num2;
}
public static void main(String[] args)
{
// Creating the Object of Sub Class
SubClassMethodOverridingEx objSubClassMethodOverridingEx = new
SubClassMethodOverridingEx();

// Calling Sub Class Method


System.out.println("Sub Class Operation Result :
"+objSubClassMethodOverridingEx.operation(5, 3));

18 | P a g e
// Creating the Object of Parent Class
MethodOverridingEx objMethodOverridingEx = new MethodOverridingEx();

// Calling Parent Class Method


System.out.println("Parent Class Operation Result :
"+objMethodOverridingEx.operation(5, 3));
}
}

Output:

Can we override static method? No, a static method cannot be overridden. Why can we not override static method? It is
because the static method is bound with class whereas instance method is bound with an object. Static belongs to the class area,
and an instance belongs to the heap area.

Difference between method Overloading and Method Overriding in java

S. No. Method Overloading Method Overriding


Method overriding is used to provide the specific
Method overloading is used to increase the readability
1 implementation of the method that is already provided
of the program.
by its super class.
Method overriding occurs in two classes that have
2 Method overloading is performed within class.
inheritance
In case of method overloading, parameter must be In case of method overriding, parameter must be same.
3
different.
Method overloading is the example of compile time Method overriding is the example of run time
4
polymorphism. polymorphism.
In java, method overloading can't be performed by
changing return type of the method only. Return type Return type must be same or covariant in method
5
can be same or different in method overloading. But overriding.
you must have to change the parameter.

SUPER KEYWORD IN JAVA


The super keyword in java is a reference variable which is used to refer immediate parent class object.

Whenever we create the instance of subclass, an instance of parent class is created implicitly which is referred by super
reference variable.

Usage of java super Keyword

1. super can be used to refer immediate parent class instance variable.


2. super can be used to invoke immediate parent class method.
3. super() can be used to invoke immediate parent class constructor.

19 | P a g e
FINAL KEYWORD IN JAVA
The final keyword in java is used to restrict the user. The java final keyword can be used in many contexts. Final can be:

1. Variable
2. Method
3. class

The final keyword can be applied with the variables; a final variable that have no value it is called blank final variable or
uninitialized final variable. It can be initialized in the constructor only. The blank final variable can be static also which will be
initialized in the static block only. We will have detailed learning of these.

Java final variable

If we make any variable as final, we cannot change the value of final variable (It will be constant).

package corejava;

public class FinalEx


{
// final variable acts as Constant
final String companyName = "TCS";

public void details()


{
// We are not able to change the value of final variable
// It shows compiler Time Error
companyName = "XYZ";
System.out.println();
}

public static void main(String[] args)


{
FinalEx objFinalEx = new FinalEx();
objFinalEx.details();
}
}

Java final method


If we make any method as final, we cannot override it.

package corejava;

class FinalEx
{
// final method
final void details()
{

20 | P a g e
System.out.println("In final method");
}
}

class SubFinalEx extends FinalEx


{
// Compile Time Error
void details()
{
System.out.println("In final method");
}
public static void main(String[] args)
{
FinalEx objFinalEx = new FinalEx();
objFinalEx.details();
}
}

Java final class

If we make any class as final, we cannot extend it.

package corejava;

// Create final class


final class FinalEx
{

class SubFinalEx extends FinalEx


{
// Compile Time Error
void details()
{
System.out.println("In final Class");
}
public static void main(String[] args)
{
FinalEx objFinalEx = new FinalEx();
objFinalEx.details();
}
}

ENCAPSULATION IN JAVA

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

Advantage of Encapsulation in java

 By providing only a setter or getter method, we can make the class read-only or write-only. In other words, we can skip
the getter or setter methods.
 It provides us the control over the data. Suppose we want to set the value of id which should be greater than 100 only,
we can write the logic inside the setter method. We can write the logic not to store the negative numbers in the setter
methods.
 It is a way to achieve data hiding in Java because other class will not be able to access the data through the private data
members.
 The encapsulate class is easy to test. So, it is better for unit testing.

Example of encapsulation that has only one field with its setter and getter methods.

package corejava;

public class EncapsulationEx


{
// Private data member
private String name;

// getter method for name


public String getName()
{
return name;
}

// setter method for name


public void setName(String name)
{
this.name = name;
}
}

Class to test the encapsulated methods

package corejava;

public class EncapsulationTest


{
public static void main(String[] args)
{
// Create Object of Encapsulation Class
EncapsulationEx objEncapsulationEx = new EncapsulationEx();

22 | P a g e
// Setting value in the name method
objEncapsulationEx.setName("Arman Khandelwal");

// getting the value of the name method


System.out.println(objEncapsulationEx.getName());
}
}

Output:

ACCESS MODIFIER
There are two types of modifiers in Java: access modifiers and non-access modifiers.

The access modifiers in Java specifies the accessibility or scope of a field, method, constructor, or class. We can change the
access level of fields, constructors, methods, and class by applying the access modifier on it.

There are four types of Java access modifiers:

1. Private: The access level of a private modifier is only within the class. It cannot be accessed from outside the class.
2. Default: The access level of a default modifier is only within the package. It cannot be accessed from outside the
package. If we do not specify any access level, it will be the default.
3. Protected: The access level of a protected modifier is within the package and outside the package through child class. If
we do not make the child class, it cannot be accessed from outside the package.
4. Public: The access level of a public modifier is everywhere. It can be accessed from within the class, outside the class,
within the package and outside the package.

Understanding Java Access Modifiers

Access Outside package by


Within Class Within package Outside package
Modifier subclass only
Private Yes No No No
Default Yes Yes No No
Protected Yes Yes Yes No
Public Yes Yes Yes Yes

Private Access Modifier

The private access modifier is accessible only within the class.

23 | P a g e
For example, we have created two classes A and B. A class contains private data member and private method. We are accessing
these private members from outside the class, so there is a compile-time error.

Default Access Modifier

If we don't use any modifier, it is treated as default by default. The default modifier is accessible only within package. It cannot
be accessed from outside the package. It provides more accessibility than private. But, it is more restrictive than protected, and
public.

For example, we have created two packages package1 and package2. We are accessing the A class from outside its package i.e.
package1, since A class is not public, so it cannot be accessed from outside the package.

Protected Access Modifier

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

It provides more accessibility than the default modifier.

For example, we have created the two packages package1 and package2. The A class of package1 is public, so can be accessed
from outside the package. But method of this package is declared as protected, so it can be accessed from outside the class only
through inheritance.

Public Access Modifier

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

ABSTRACTION IN JAVA

Abstraction is a process of hiding the implementation details and showing only functionality to the user. Another way, it shows
only essential things to the user and hides the internal details, for example, sending SMS where we type the text and send the
message. We don't know the internal processing about the message delivery.

Abstraction lets us focus on what the object does instead of how it does it.

Ways to achieve Abstraction

There are two ways to achieve abstraction in java

1. Abstract class (0 to 100%)


2. Interface (100%)

ABSTRACT CLASS
A class which is declared as abstract is known as an abstract class. It can have abstract and non-abstract methods. It needs to be
extended and its method implemented. It cannot be instantiated.

Points to Remember

 An abstract class must be declared with an abstract keyword.


 It can have abstract and non-abstract methods.
 It cannot be instantiated.
 It can have constructors and static methods also.
 It can have final methods which will force the subclass not to change the body of the method.

Abstract Method in Java

A method which is declared as abstract and does not have implementation is known as an abstract method.

24 | P a g e
package corejava;

abstract class AbstractEx


{
// Method with Body in Abstract Class
int operation(int num1, int num2)
{
return num1+num2;
}

// Abstract method
abstract void abstractMethod();
}

class SubAbstractEx extends AbstractEx


{
@Override
void abstractMethod()
{
System.out.println("In abstractMethod");
}
}

class AbstractExTest
{
public static void main(String[] args)
{
AbstractEx objAbstractEx = new SubAbstractEx();
System.out.println(objAbstractEx.operation(4, 5));
}
}

Output:

Rules in Abstract Class

 If there is an abstract method in a class, that class must be abstract.


 If we are extending an abstract class that has an abstract method, we must either provide the implementation of the
method or make this class abstract.

25 | P a g e
INTERFACE
An interface in java is a blueprint of a class. It has static constants and abstract methods. The interface in Java is a mechanism to
achieve abstraction. There can be only abstract methods in the Java interface, not method body. It is used to achieve abstraction
and multiple inheritance in Java.

In other words, we can say that interfaces can have abstract methods and variables. It cannot have a method body. It cannot be
instantiated just like the abstract class.

Since Java 8, we can have default and static methods in an interface. Since Java 9, we can have private methods in an interface.

Why use Java interface?

There are below reasons to use interface. They are given below.

 It is used to achieve abstraction.


 By interface, we can support the functionality of multiple inheritance.

How to declare an interface?

An interface is declared by using the interface keyword. It provides total abstraction; means all the methods in an interface are
declared with the empty body, and all the fields are public, static and final by default. A class that implements an interface must
implement all the methods declared in the interface.

The relationship between classes and interfaces

A class extends another class, an interface extends another interface, but a class implements an interface.

package corejava;

interface InterfaceEx
{
// Method in Interface
void interfaceMethod();
}

class InterfaceExClass implements InterfaceEx


{
// Define Interface Method
public void interfaceMethod()
{
System.out.println("In InterfaceExClass");
}

public static void main(String[] args)


{
InterfaceExClass objInterfaceExClass = new InterfaceExClass();
objInterfaceExClass.interfaceMethod();
}
}

Output:

26 | P a g e
Multiple inheritance in Java by interface

If a class implements multiple interfaces, or an interface extends multiple interfaces, it is known as multiple inheritance.

package corejava;

interface InterfaceEx
{
// Method in Interface
void methodInterfaceEx();
}

interface InterfaceEx1
{
void methodInterfaceEx1();
}

class InterfaceExClass implements InterfaceEx, InterfaceEx1


{
@Override
public void methodInterfaceEx1()
{
System.out.println("Implementing from InterfaceEx1 interface");
}

@Override
public void methodInterfaceEx()
{
System.out.println("Implementing from InterfaceEx interface");
}

public static void main(String[] args)


{
InterfaceExClass objInterfaceExClass = new InterfaceExClass();
objInterfaceExClass.methodInterfaceEx();
objInterfaceExClass.methodInterfaceEx1();
}
}

27 | P a g e
Output:

Multiple inheritance is not supported through class in java, but it is possible by an interface, why?

Multiple inheritance is not supported in the case of class because of ambiguity. However, it is supported in case of an interface
because there is no ambiguity. It is because its implementation is provided by the implementation class.

What is marker or tagged interface?

An interface which has no member is known as a marker or tagged interface, for example, Serializable, Cloneable, Remote, etc.
They are used to provide some essential information to the JVM so that JVM may perform some useful operation.

Difference between abstract class and interface

Abstract class and interface both are used to achieve abstraction where we can declare the abstract methods. Abstract class and
interface both can't be instantiated. But there are many differences between abstract class and interface that are given below.

S. No. Abstract Class Interface

Abstract class can have abstract and non-abstract Interface can have only abstract methods. Since Java 8, it
1
methods. can have default and static methods also.
2 Abstract class doesn't support multiple inheritance. Interface supports multiple inheritance.
Abstract class can have final, non-final, static and Interface has only static and final variables.
3
non-static variables.
Abstract class can provide the implementation of Interface can't provide the implementation of abstract
4
interface. class.
The abstract keyword is used to declare abstract The interface keyword is used to declare interface.
5
class.
An abstract class can extend another Java class and An interface can extend another Java interface only.
6
implement multiple Java interfaces.
An abstract class can be extended using keyword An interface can be implemented using keyword
7
"extends". "implements".
A Java abstract class can have class members like Members of a Java interface are public by default.
8
private, protected, etc.
Example: Example:
public abstract class AbstractClass public interface InterfaceEx
{ {
9
public abstract void void interfaceMethod();
abstractMethod(); }
}

CONTROL STATEMENTS

IF-ELSE STATEMENT
If Statement

28 | P a g e
The Java if statement tests the condition. It executes the if block if condition is true.

package corejava;

public class IfExample


{
public static void main(String[] args)
{
int age = 20;

if(age>18)
{
System.out.println("Age is greater than 18");
}
}
}

Output:

if-else Statement

The Java if-else statement also tests the condition. It executes the if block if condition is true otherwise else block is executed.

package corejava;

public class IfExample


{
public static void main(String[] args)
{
int age = 20;

if(age<18)
{
System.out.println("Age is greater than 18");
}
else
System.out.println("Age is more than 18");
}
}

Output:

29 | P a g e
if-else-if ladder Statement

The if-else-if ladder statement executes one condition from multiple statements.

package corejava;

public class IfElseEx


{
public static void main(String[] args)
{
int number = -10;

if(number>0)
{
System.out.println("Number is Positive");
}
else if(number<0)
{
System.out.println("Number is Negative");
}
else
System.out.println("Zero");
}
}

Output:

SWITCH STATEMENT
The Java switch statement executes one statement from multiple conditions. It is like if-else-if ladder statement. The switch
statement works with byte, short, int, long, enum types, String and some wrapper types like Byte, Short, Int, and Long. Since
Java 7, we can use strings in the switch statement.

In other words, the switch statement tests the equality of a variable against multiple values.

Points to Remember

 There can be one or N number of case values for a switch expression.


 The case value must be of switch expression type only. The case value must be literal or constant. It doesn't allow
variables.
 The case values must be unique. In case of duplicate value, it renders compile-time error.

30 | P a g e
 The Java switch expression must be of byte, short, int, long (with its Wrapper type), enums and string.
 Each case statement can have a break statement which is optional. When control reaches to the break statement, it
jumps the control after the switch expression. If a break statement is not found, it executes the next case.
 The case value can have a default label which is optional.

This is how it works:

 The switch expression is evaluated once.


 The value of the expression is compared with the values of each case.
 If there is a match, the associated block of code is executed.
 The break and default keywords are optional.

package corejava;

public class SwitchExample


{
public static void main(String[] args)
{
//Declaring a variable for Switch
int number = 3;

// Switch expression
switch(number)
{
// Case Statements
case 1: System.out.println("1");
break;

case 2: System.out.println("2");
break;

case 3: System.out.println("3");
break;

case 4: System.out.println("4");
break;

// Default Statement
default: System.out.println("No Number Matched");
}
}
}

Output:

31 | P a g e
FOR LOOP
The Java for loop is used to iterate a part of the program several times. If the number of iteration is fixed, it is recommended to
use for loop.

It consists of three parts:

1. Initialization: It is the initial condition which is executed once when the loop starts. Here, we can initialize the variable,
or we can use an already initialized variable. It is an optional condition.
2. Condition: It is the second condition which is executed each time to test the condition of the loop. It continues
execution until the condition is false. It must return Boolean value either true or false. It is an optional condition.
3. Increment/Decrement: It increments or decrements the variable value. It is an optional condition.

package corejava;

public class ForExample


{
public static void main(String[] args)
{
for(int i=1;i<=10;i++)
{
System.out.println(i);
}
}
}

Output:

Java for-each Loop

The for-each loop is used to traverse array or collection in java. It is easier to use than simple for loop because we don't need to
increment value and use subscript notation. It works on elements basis not index. It returns element one by one in the defined
variable.

package corejava;

public class ForEachExample

32 | P a g e
{
public static void main(String[] args)
{
// Declaring an array
int arr[] = {1,2,3,4,5};

//Printing array values


for(int i:arr)
{
System.out.println(i);
}
}
}

Output:

WHILE LOOP
The Java while loop is used to iterate a part of the program several times. If the number of iteration is not fixed, it is
recommended to use while loop.

package corejava;

public class WhileExample


{
public static void main(String[] args)
{
int i = 1;
while(i<=10)
{
System.out.println(i);
i++;
}
}
}

33 | P a g e
Output:

DO-WHILE LOOP
The Java do-while loop is used to iterate a part of the program several times. If the number of iteration is not fixed and we must
have to execute the loop at least once, it is recommended to use do-while loop.

The Java do-while loop is executed at least once because condition is checked after loop body.

package corejava;

public class DoWhileExample


{
public static void main(String[] args)
{
int i = 1;
do
{
System.out.println(i);
i++;
}
while(i<=10);
}
}

Output:

34 | P a g e
EXCEPTION HANDLING IN JAVA

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

What is exception handling?

Exception Handling is a mechanism to handle runtime errors such as ClassNotFound, IO, SQL, Remote etc.

Advantage of Exception Handling

The core advantage of exception handling is to maintain the normal flow of the application. Exception normally disrupts the
normal flow of the application that is why we use exception handling. Let's take a scenario:

Suppose there is 10 statements in our program and there occurs an exception at statement 5, rest of the code will not be
executed i.e. statement 6 to 10 will not run. If we perform exception handling, rest of the statement will be executed. That is
why we use exception handling in java.

Types of Exception

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

 Checked Exception
 Unchecked Exception
 Error

Difference between checked and unchecked exceptions

1. Checked Exception

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

2. Unchecked Exception

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

3. Error

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

Exception Keywords

35 | P a g e
There are 5 keywords which are used in handling exceptions in Java.

Keyword Description
The "try" keyword is used to specify a block where we should place exception code. The try block must be
try
followed by either catch or finally. It means, we can't use try block alone.
The "catch" block is used to handle the exception. It must be preceded by try block which means we can't use
catch
catch block alone. It can be followed by finally block later.
The "finally" block is used to execute the important code of the program. It is executed whether an exception
finally
is handled or not.
throw The "throw" keyword is used to throw an exception.
The "throws" keyword is used to declare exceptions. It doesn't throw an exception. It specifies that there may
throws
occur an exception in the method. It is always used with method signature.

package corejava;

public class ExceptionHandlingEx


{
public static void main(String[] args)
{
// Code that have exception
try
{
int number = 100/0;
}
catch(ArithmeticException e)
{
System.out.println("Error Message is :"+e);
}

// Rest Code without Exception


System.out.println("Outside of Exception Code!!!");
}
}

Output:

TRY BLOCK
try block is used to enclose the code that might throw an exception. It must be used within the method.

If an exception occurs at the particular statement of try block, the rest of the block code will not execute. So, it is recommended
not to keeping the code in try block that will not throw an exception.

36 | P a g e
Java try block must be followed by either catch or finally block.

CATCH BLOCK
catch block is used to handle the Exception by declaring the type of exception within the parameter. The declared exception
must be the parent class exception (i.e., Exception) or the generated exception type. However, the good approach is to declare
the generated type of exception.

The catch block must be used after the try block only. We can use multiple catch block with a single try block.

Internal working of java try-catch block

The JVM firstly checks whether the exception is handled or not. If exception is not handled, JVM provides a default exception
handler that performs the following tasks:

 Prints out exception description.


 Prints the stack trace (Hierarchy of methods where the exception occurred).
 Causes the program to terminate.

But if exception is handled by the application programmer, normal flow of the application is maintained i.e. rest of the code is
executed.

MULTI-CATCH BLOCK
A try block can be followed by one or more catch blocks. Each catch block must contain a different exception handler. So, if we
have to perform different tasks at the occurrence of different exceptions, use java multi-catch block.

Points to remember

 At a time only one exception occurs and at a time only one catch block is executed.
 All catch blocks must be ordered from most specific to most general, i.e. catch for ArithmeticException must come
before catch for Exception.

37 | P a g e
package corejava;

public class MultipleCatchBlock


{
public static void main(String[] args)
{
try
{
int arr[] = new int[5];
arr[5] = 30/0;
}
catch(ArithmeticException e)
{
System.out.println("Arithmetic Exception occurs");
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("ArrayIndexOutOfBoundsException Exception occurs");
}
catch(Exception e)
{
System.out.println("Exception occurs");
}
System.out.println("Outside of the Exception Code!!!");
}
}

Output:

NESTED TRY BLOCK


The try block within a try block is known as nested try block in java.

Why use nested try block

Sometimes a situation may arise where a part of a block may cause one error and the entire block itself may cause another
error. In such cases, exception handlers have to be nested.

38 | P a g e
package corejava;

public class NestedTryExample


{
public static void main(String[] args)
{
// Outer Try Block
try
{
// Nested Try Block 1
try
{
int number = 10/0;
}
catch(ArithmeticException e)
{
System.out.println("ArithmeticException Exception"+e);
}

// Nested Try Block 2


try
{

}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("ArrayIndexOutOfBoundsException Exception"+e);
}
}
catch(Exception e)
{
System.out.println("Outer Try Block");
}
}
}

Output:

39 | P a g e
FINALLY BLOCK
Java finally block is a block that is used to execute important code such as closing connection, stream etc. finally block is always
executed whether exception is handled or not, it follows try or catch block.

Why use java finally

Finally block in java can be used to put "clean-up" code such as closing a file, closing connection etc.

package corejava;

public class ExceptionHandlingEx


{
public static void main(String[] args)
{
// Put Code that have exception in Try - Catch Block
try
{
int number = 100/0;
}
catch(ArithmeticException e)
{
System.out.println("Error Message is :"+e);
}

// finally block
finally
{
System.out.println("Finally Block is always Executed");
}
}
}

Output:

Note

 For each try block there can be zero or more catch blocks, but only one finally block.
 The finally block will not be executed if program exits (either by calling System.exit() or by causing a fatal error that
causes the process to abort).

THROW KEYWORD
The Java throw keyword is used to explicitly throw an exception. We can throw either checked or uncheked exception in java by
throw keyword. The throw keyword is mainly used to throw custom exception.

40 | P a g e
For example, we have created the validate method that takes integer value as a parameter. If the age is less than 18, we are
throwing the ArithmeticException otherwise print a message welcome to vote.

package corejava;

public class ThrowExample


{
public void validate(int age)
{
if(age<18)
{
throw new ArithmeticException("Age is not Valid");
}
else
System.out.println("Welcome to Vote");
}

public static void main(String[] args)


{
ThrowExample objThrowExample = new ThrowExample();
objThrowExample.validate(16);
}
}

Output:

THROWS KEYWORD
The Java throws keyword is used to declare an exception. It gives an information to the programmer that there may occur an
exception so it is better for the programmer to provide the exception handling code so that normal flow can be maintained.

Exception Handling is mainly used to handle the checked exceptions. If there occurs any unchecked exception such as
NullPointerException, it is programmers fault that he is not performing check-up before the code being used.

Advantage of Java throws keyword

Now Checked Exception can be propagated (forwarded in call stack). It provides information to the caller of the method about
the exception.

Rule: If we are calling a method that declares an exception, we must either have caught or declare the exception.

There are two cases:

41 | P a g e
1. Case1: We caught the exception i.e. handle the exception using try/catch.
2. Case2: We declare the exception i.e. specifying throws with the method.

Case1: We caught the exception using try/catch block

public class ExceptionHandlingEx


{
public static void main(String[] args)
{
// Put Code that have exception in Try - Catch Block
try
{
int number = 100/0;
}
catch(ArithmeticException e)
{
System.out.println("Error Message is :"+e);
}

// finally block
finally
{
System.out.println("Finally Block is always Executed");
}
}
}

Output:

Case2: We declare the exception using throw keyword

 In case we declare the exception, if exception does not occur, the code will be executed fine.
 In case we declare the exception if exception occurs, an exception will be thrown at runtime because throws does not
handle the exception.

package corejava;

import java.io.IOException;

42 | P a g e
public class ThrowsKeywordEx
{
// Declare IOException
void methodEx() throws IOException
{
int number = 100/0;
System.out.println("In methodEx :"+number);
}
}
class ThrowsKeywordExTest
{
public static void main(String[] args) throws IOException
{
ThrowsKeywordEx objThrowsKeywordEx = new ThrowsKeywordEx();
objThrowsKeywordEx.methodEx();
}
}

Output:

Difference between throw and throws in Java

S. No. throw throws


Java throw keyword is used to explicitly throw an
1 Java throws keyword is used to declare an exception.
exception.
Checked exception cannot be propagated using
2 Checked exception can be propagated with throws.
throw only.
3 Throw is followed by an instance. Throws is followed by class.
4 Throw is used within the method. Throws is used with the method signature.
We can declare multiple exceptions e.g.
5 We cannot throw multiple exceptions. public void method()throws IOException,
SQLException.

FILE HANDLING IN JAVA

File handling in Java implies reading from and writing data to a file. The File class from the java.io package, allows us to work
with different formats of files. In order to use the File class, we need to create an object of the class and specify the filename or
directory name.

File Handling is necessary to perform various tasks on a file, such as read, write, etc.

43 | P a g e
Java uses the concept of a stream to make I/O operations on a file. So let’s now understand what is a Stream in Java.

What is a Stream?

In Java, Stream is a sequence of data which can be of two types.

1. Byte Stream

This mainly incorporates with byte data. When an input is provided and executed with byte data, then it is called the
file handling process with a byte stream.

2. Character Stream

Character Stream is a stream which incorporates with characters. Processing of input data with character is called the
file handling process with a character stream.

Java File Methods

Below table depicts the various methods that are used for performing operations on Java files.

Method Type Description

canRead() Boolean It tests whether the file is readable or not


canWrite() Boolean It tests whether the file is writable or not
createNewFile() Boolean This method creates an empty file
delete() Boolean Deletes a file
exists() Boolean It tests whether the file exists
getName() String Returns the name of the file
getAbsolutePath() String Returns the absolute pathname of the file
length() Long Returns the size of the file in bytes
list() String[] Returns an array of the files in the directory
mkdir() Boolean Creates a directory

File Operations

Basically, we can perform four operations on a file. They are as follows:

1. Create a File
2. Get File Information
3. Write to a file
4. Read from a file

CREATE A FILE
To create a file, we can use the createNewFile() method. This method returns true if the file was successfully created, and
false if the file already exists.

Let’s see an example of how to create a file in Java.

package filehandling;

import java.io.File;
import java.io.IOException;
44 | P a g e
public class CreateFileExample
{
public static void main(String[] args)
{
try
{
// Creating an Object of a file
File file = new File("E:\\Armaan Khandelwal\\NewFile.txt");
if(file.createNewFile())
{
System.out.println("File Created Successfully :"+file.getName());
}
else
System.out.println("File already exists.");
}
catch(IOException e)
{
System.out.println("Error Occured.");
e.printStackTrace();
}
}
}

Output:

GET FILE INFORMATION


To get file information using various methods with the help of below example code

package filehandling;

import java.io.File;

public class FileInformation


{

45 | P a g e
public static void main(String[] args)
{
// Creating the Object of a File
File file = new File("E:\\Armaan Khandelwal\\NewFile.txt");
if(file.exists())
{
// Returning the file Name
System.out.println("File Name : "+file.getName());

// Returning the file Path


System.out.println("File Path : "+file.getAbsolutePath());

// Check File is writable or not


System.out.println("Writable : "+file.canWrite());

// Check File is Readable or not


System.out.println("Readable : "+file.canRead());

// Size of the file


System.out.println("File size in bytes :"+file.length());
}
else
System.out.println("File not exists.");
}
}

Output:

WRITE TO A FILE
We have used the FileWriter class together with its write() method to write some text into the file.

package filehandling;

import java.io.FileWriter;
import java.io.IOException;

46 | P a g e
public class WriteToFile
{
public static void main(String[] args)
{
try
{
FileWriter writer = new FileWriter("E:\\Armaan Khandelwal\\NewFile.txt");

// Write content to file


writer.write("Java Programming");

// Close writer
writer.close();
System.out.println("File write successfully!!!");
}
catch(IOException e)
{
System.out.println("File not exists.");
e.printStackTrace();
}
}
}

Output:

47 | P a g e
When we run the file, the above text, “Java Programming” will be entered in the file that we have created. we can cross check it
by opening the file in the specified location.

READ FROM A FILE


We have used the Scanner class to read the contents of the text file.

package filehandling;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class ReadFile


{
public static void main(String[] args)
{
try
{
File file = new File("E:\\Armaan Khandelwal\\NewFile.txt");
Scanner reader = new Scanner(file);

while(reader.hasNextLine())
{
String data = reader.nextLine();
System.out.println(data);
}
reader.close();
}
catch(FileNotFoundException e)
{
System.out.println("File not exists.");
e.printStackTrace();
}
}
}

Output:

48 | P a g e
COLLECTIONS FRAMEWORK IN JAVA

Collections in java is a framework that provides an architecture to store and manipulate the group of objects.

All the operations that we perform on a data such as searching, sorting, insertion, manipulation, deletion etc. can be performed
by Java Collections.

Java Collection simply means a single unit of objects. Java Collection framework provides many interfaces (Set, List, Queue,
Deque etc.) and classes (ArrayList, Vector, LinkedList, PriorityQueue, HashSet, LinkedHashSet, TreeSet etc.)

What is Collection in java?

Collection represents a single unit of objects i.e. a group.

What is framework in java?

 Provides readymade architecture.


 Represents set of classes and interface.

What is Collection Framework?

Collection framework represents a unified architecture for storing and manipulating group of objects. It has:

1. Interfaces and its implementations i.e. classes


2. Algorithm

Hierarchy of Collection Framework

Let us see the hierarchy of collection framework. The java.util package contains all the classes and interfaces for Collection
framework.

49 | P a g e
ARRAYLIST CLASS
Java ArrayList class uses a dynamic array for storing the elements i.e. the size of the list is increased dynamically if the elements
are added more than the initial size. Though it may be slower than standard arrays but it can be helpful in programs where lots
of manipulation in the array is needed.

It inherits AbstractList class and implements List interface.

We all know that arrays are an important structure in Java which can be used to store static data. But, what if our data needs to
be stored dynamically? In order to do this, Java offers a special collection framework called Java ArrayList that is specifically
meant to store dynamic data.

The important points about Java ArrayList class are:

 ArrayList class can contain duplicate elements.


 ArrayList class maintains insertion order.
 ArrayList class is non synchronized.

50 | P a g e
 ArrayList allows random access because array works at the index basis.
 In Java ArrayList class, manipulation is slow because a lot of shifting needs to be occurred if any element is removed
from the array list.

ArrayList Methods

 void add(int index, Object element): This method is used to insert a specific element at a specific position
index in a list.
 Object remove(int index): This method removes the first occurrence of the specified element from this list if it
is present. If the list does not contain the element, it is unchanged.
 int size(): It returns the number of elements in this list i.e. the size of the list.
 Object clone(): This method returns a shallow copy of this ArrayList. i.e. it clones the entire ArrayList.
 Object[] to Array(): It is used to return an array containing all of the elements in the list in correct order.
 Void clear(); This method is used to remove all the elements from any list.
 int indexOf(Object O): This method returns the index of the first occurrence of the specified element in this list,
or -1 if this list does not contain the element.

package collectionsframework;

import java.util.ArrayList;

public class ListInterfaceExample


{
public static void main(String[] args)
{
// Implementing List Interface with ArrayList Class
ArrayList<String> list = new ArrayList<>();

// add method
list.add("ABC");
list.add("XYZ");
list.add("123");

// size of list
int sizeOfList = list.size();
System.out.println("Size of the list : "+sizeOfList);

// Clone the entire ArrayList


Object cloneList = list.clone();
System.out.println("Elements in the Cloned list : "+cloneList);

// Convert ArrayList to Array


Object[] objArray = list.toArray();
System.out.println("ArrayList converted to Array:");
for(int i=0;i<objArray.length;i++)
{
System.out.println(objArray[i]);

51 | P a g e
}

System.out.println("ArrayList before removing an Element:");


for(String value:list)
{
System.out.println(value);
}

// Find element using indexOf()


int indexOfElement = list.indexOf(2);
System.out.println("Element at 2 index : "+indexOfElement);

// remove method
list.remove("XYZ");

System.out.println("ArrayList after removing an Element:");


for(String value:list)
{
System.out.println(value);
}

// Clear ArrayList
list.clear();
System.out.println("ArrayList after Clearing : "+list);
}
}

Output:

Java Non-generic Vs Generic Collection

Java collection framework was non-generic before JDK 1.5. Since 1.5, it is generic.

52 | P a g e
Java new generic collection allows us to have only one type of object in collection. Now it is type safe so typecasting is not
required at run time.

In generic collection, we specify the type in angular braces. Now ArrayList is forced to have only specified type of objects in it. If
we try to add another type of object, it gives compile time error.

LINKEDLIST CLASS
Java LinkedList class uses doubly linked list to store the elements. It provides a linked-list data structure. It inherits the
AbstractList class and implements List and Deque interfaces.

The important points about Java LinkedList are:

 LinkedList class can contain duplicate elements.


 LinkedList class maintains insertion order.
 LinkedList class is non synchronized.
 In LinkedList class, manipulation is fast because no shifting needs to be occurred.
 LinkedList class can be used as list, stack or queue.

LinkedList Methods

 add(E e): This method adds elements to the linked list one after the other
 add(int index, E element): This method adds the specified element at the specified position in this list
 addFirst(E e): This method adds the specified element at the beginning of this list
 addLast(E e): This method adds the specified element to the end of this list
 get(int index): This method returns the element at the specified position in this list
 set(int index, E element): This method replaces the element at the specified position in this list with the
specified element
 remove(int index): This method removes the element at the specified position in this list
 removeFirst(): This method removes and returns the first element from this list
 removeLast(): This method removes and returns the last element from this list

package collectionsframework;

import java.util.LinkedList;

public class LinkedListExample


{
public static void main(String[] args)
{
// Declaring LinkedList
LinkedList<String> list = new LinkedList<>();

// add items to linkedlist


list.add("Java");
list.add("Python");
list.add("C++");
list.add("C#");
System.out.println("The Elements in LinkedList are : "+list);

53 | P a g e
// Add items at specified position
list.add(2, "JavaScript");
list.add(3, "TypeScript");
System.out.println("The Elements in LinkedList after editing : "+list);

// Add first and last items in the list


list.addFirst("First Language");
list.addLast("Last Language");
System.out.println("The Elements in LinkedList after updating : "+list);

// Get and Set Items in the list


Object firstValue = list.get(0);
System.out.println("First Value in the List : "+firstValue);
list.set(0, "Java 10");
System.out.println("The Elements in LinkedList after updating first item :
"+list);

// Remove Items
list.remove(1);
System.out.println("The Elements in LinkedList after removing item : "+list);

// Iterating the List


System.out.println("List displaying using for each loop:");
for(String value:list)
{
System.out.println(value);
}
}
}

Output:

54 | P a g e
Difference between ArrayList and LinkedList

ArrayList and LinkedList both implements List interface and maintains insertion order. Both are non-synchronized classes.

But there are many differences between ArrayList and LinkedList classes that are given below.

ArrayList LinkedList

ArrayList internally uses dynamic array to store the elements. LinkedList internally uses doubly linked list to store the
elements.

Manipulation with ArrayList is slow because it internally uses Manipulation with LinkedList is faster than ArrayList because
array. If any element is removed from the array, all the bits it uses doubly linked list so no bit shifting is required in
are shifted in memory. memory.

ArrayList class can act as a list only because it implements List LinkedList class can act as a list and queue both because it
only. implements List and Deque interfaces.

ArrayList is better for storing and accessing data. LinkedList is better for manipulating data.

LIST INTERFACE
List Interface is the sub interface of Collection. It contains methods to insert and delete elements in index basis. It is a factory of
ListIterator interface.

package collectionsframework;

import java.util.ArrayList;
import java.util.List;

public class ListInterfaceExample


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

55 | P a g e
// Implementing List Interface with ArrayList Class
List<String> list = new ArrayList<>();
list.add("ABC");
list.add("XYZ");
list.add("123");

for(String value:list)
{
System.out.println(value);
}
}
}

Output:

HASHSET CLASS
Java HashSet class is used to create a collection that uses a hash table for storage. It inherits the AbstractSet class and
implements Set interface.

The important points about Java HashSet class are:

 HashSet stores the elements by using a mechanism called hashing.


 HashSet contains unique elements only.
 HashSet allows null value.
 HashSet class is non synchronized.
 HashSet doesn't maintain the insertion order. Here, elements are inserted on the basis of their hashcode.
 HashSet is the best approach for search operations.

Difference between List and Set

List can contain duplicate elements whereas Set contains unique elements only.

LINKEDHASHSET CLASS
LinkedHashSet class is a Hash table and Linked list implementation of the set interface. It inherits HashSet class and implements
Set interface.

A Set is a collection which does not allow any duplicate elements. The most commonly used implementations of the set
interface are HashSet, TreeSet and LinkedHashSet.

The important points about Java LinkedHashSet class are:

 Contains unique elements only like HashSet.


 Provides all optional set operations, and permits null elements.
 Maintains insertion order.

56 | P a g e
When we traverse through a LinkedHashSet via an iterating agent, the elements will be returned back in the same order as they
were inserted.

package collectionsframework;

import java.util.LinkedHashSet;

public class LinkedHashSetEx


{
public static void main(String[] args)
{
LinkedHashSet <String> hs = new LinkedHashSet<>();

// Adding elements to the LinkedHashSet


hs.add("Java");

// Duplicate Element
hs.add("Java");
hs.add("Python");

// Duplicate Element
hs.add("Python");

hs.add("C#");
hs.add("JavaScript");

// Display LinkedHashSet elements


System.out.println("Elements in LinkedHashSet : "+hs);

// Remove
hs.remove("JavaScript");
System.out.println("Elements in LinkedHashSet After Removing : "+hs);
}
}

Output:

As we can see, the order remains unchanged and the duplicate elements is not displayed. It is only displayed unique values.

57 | P a g e
TREESET CLASS
Java TreeSet class implements the Set interface that uses a tree for storage. It inherits AbstractSet class and implements
NavigableSet interface. The objects of TreeSet class are stored in ascending order.

The important points about Java TreeSet class are:

 Contains unique elements only like HashSet.


 Access and retrieval times are quiet fast.
 Doesn't allow null element.
 TreeSet class is non synchronized.
 Maintains ascending order.

package collectionsframework;

import java.util.TreeSet;

public class TreeSetExample


{
public static void main(String[] args)
{
// Declaring TreeSet
TreeSet<String> ts=new TreeSet<String>();
ts.add("D");
ts.add("A");
ts.add("C");
ts.add("B");
ts.add("E");

System.out.println("The Elements in TreeSet are : "+ts);


}
}

Output:

MAP INTERFACE
A map contains values on the basis of key i.e. key and value pair. Each key and value pair is known as an entry. Map contains
only unique keys.

Map is useful if we have to search, update or delete elements on the basis of key.

A Map doesn't allow duplicate keys, but we can have duplicate values. HashMap and LinkedHashMap allow null keys and values,
but TreeMap doesn't allow any null key or value.

58 | P a g e
HASHMAP CLASS
Java HashMap class implements the map interface by using a HashTable. It inherits AbstractMap class and implements Map
interface.

It’s named as HashMap because it uses a technique called Hashing. Hashing is a process of converting a larger String to a
smaller one by keeping the value of the String as constant. The resulting compressed value helps in indexing and faster
searches.

The important points about Java HashMap class are:

 A HashMap contains values based on the key.


 It contains only unique elements.
 It may have one null key and multiple null values.
 It maintains no order.

package collectionsframework;

import java.util.HashMap;
import java.util.Map;

public class HashMapExample


{
public static void main(String[] args)
{
Map<Integer, String> map = new HashMap<>();
map.put(1, "Java");
map.put(2, "Python");
map.put(3, "C#");
map.put(4, "JavaScript");
map.put(5, "TypeScript");

for(Map.Entry m:map.entrySet())
{
System.out.println(m.getKey()+ " : "+m.getValue());
}
}
}

59 | P a g e
Output:

Difference between HashSet and HashMap

HashSet contains only values whereas HashMap contains entry (key and value).

LINKEDHASHMAP CLASS
Java LinkedHashMap class is Hash table and Linked list implementation of the Map interface, with predictable iteration order. It
inherits HashMap class and implements the Map interface.

The important points about Java LinkedHashMap class are:

 A LinkedHashMap contains values based on the key.


 It contains only unique elements.
 It may have one null key and multiple null values.
 It is same as HashMap instead maintains insertion order.

package collectionsframework;

import java.util.LinkedHashMap;

public class LinkedHashMapEx


{
public static void main(String[] args)
{
// Declaring LinkedHashMap
LinkedHashMap<Integer, String> map = new LinkedHashMap<>();
map.put(1, "Java");
map.put(2, "Python");
map.put(3, "C#");
map.put(4, "JavaScript");
map.put(5, "TypeScript");

// Fetching Keys
System.out.println("Keys : "+map.keySet());

// Fetching Values
System.out.println("Values : "+map.values());

// Fetching Keys and values


System.out.println("Key and Values : "+map.entrySet());

60 | P a g e
}
}
Output:

TREEMAP CLASS
Java TreeMap class implements the Map interface by using a tree. It provides an efficient means of storing key/value pairs in
sorted order.

The important points about Java TreeMap class are:

 A TreeMap contains values based on the key. It implements the NavigableMap interface and extends AbstractMap
class.
 It contains only unique elements.
 It cannot have null key but can have multiple null values.
 It is same as HashMap instead maintains ascending order.

What is difference between HashMap and TreeMap?

HashMap TreeMap

HashMap can contain one null key. TreeMap can not contain any null key.

HashMap maintains no order. TreeMap maintains ascending order.

HASHTABLE CLASS
Java Hashtable class implements a Hashtable, which maps keys to values. It inherits Dictionary class and implements the Map
interface.

The important points about Java Hashtable class are:

 A Hashtable is an array of list. Each list is known as a bucket. The position of bucket is identified by calling the
hashcode() method. A Hashtable contains values based on the key.
 It contains only unique elements.
 It may have not have any null key or value.
 It is synchronized.

Difference between HashMap and Hashtable

HashMap and Hashtable both are used to store data in key and value form. Both are using hashing technique to store unique
keys.

61 | P a g e
But there are many differences between HashMap and Hashtable classes that are given below.

HashMap Hashtable

HashMap is non synchronized. It is not-thread safe and can't Hashtable is synchronized. It is thread-safe and can be shared
be shared between many threads without proper with many threads.
synchronization code.

HashMap allows one null key and multiple null values. Hashtable doesn't allow any null key or value.

HashMap is a new class introduced in JDK 1.2. Hashtable is a legacy class.

HashMap is fast. Hashtable is slow.

We can make the HashMap as synchronized by calling this Hashtable is internally synchronized and can't be
code unsynchronized.
Map m = Collections.synchronizedMap(HashMap);

HashMap is traversed by Iterator. Hashtable is traversed by Enumerator and Iterator.

Iterator in HashMap is fail-fast. Enumerator in Hashtable is not fail-fast.

HashMap inherits AbstractMap class. Hashtable inherits Dictionary class.

62 | P a g e
CHAPTER 2
GETTING STARTED WITH SELENIUM WEBDRIVER BASICS
INTRODUCTION AND FEATURES OF SELENIUM

Selenium is a free (open source) automated testing suite for web applications across different browsers and platforms. Selenium
focuses on automating web-based applications. Testing done using Selenium tool is usually referred as Selenium Testing or
Selenium Automation.

Selenium is not just a single tool but a suite of software's, each catering to different testing needs of an organization.

What is WebDriver?

WebDriver is a web automation framework that allows us to execute our tests against different browsers (Chrome, Firefox, IE,
Safari) with multiple platforms i.e. Windows. Apple OS X, Linux. It is exclusively for Web Applications.

It also enables us to use a programming language in creating our test scripts. Following programming languages are supported
by WebDriver
 
 Java
 .Net
 PHP
 Python
 Perl
 Ruby

SELENIUM WEBDRIVER ARCHITECTURE SIMPLIFIED

63 | P a g e
 After we trigger the test, complete Selenium Code (Client) which we have written will be converted to JSON format
 Generated JSON is sent to Browser Driver (Server) through http protocol Note: Each browser contains a separate
browser driver.
 Browser drivers communicate with its respective browser and executes the commands by interpreting JSON which it
received on the browser.
 Browser driver receives responses back from the browser and it sends JSON response back to client.

IMPORTANCE OF LOCATORS IDENTIFIERS IN SELENIUM

Locator is a command that tells Selenium WedDriver which GUI elements (say Text Box, Buttons, Check Boxes etc.) it needs to
operate on. Identification of correct GUI elements is a prerequisite to creating an automation script.

There are 8 locators in the Selenium WebDriver

1. id
2. name
3. className
4. linkText
5. partiallinkText
6. tagname
7. cssSelector
o tag and id
o tag and class
o tag and attribute
o tag, id and attribute
o tag, class and attribute
8. Xpath

IDENTIFYING LOCATORS (ID, NAME, LINKTEXT, PARTIALLINKTEXT) WITH DEVELOPER TOOL


Locating by Id

64 | P a g e
<input id="email" class="required" type="text"/>
driver.findElement(By.id("email"));
 
Locating by Name

<input name="register" class="required" type="text"/>


driver.findElement(By.name("register"));

Locating by LinkText

<a href="http://www.seleniumhq.org">Downloads</a>
driver.findElement(By.linkText("Downloads"));

Locating by PartialLinkText

<a href="seleniumhq.org">Download selenium server</a>


driver.findElement(By.PartialLinkText("Download"));

IDENTIFYING LOCATORS (CLASSNAME, TAGNAME) WITH DEVELOPER TOOL


Locating by ClassName

<input id="email" class="required" type="text"/>


driver.findElement(By.className(“required”));
 
Locating by TagName
TagName can be used with Group elements like, Select and check-boxes/dropdowns.

Select select = new Select(driver.findElement(By.tagName("select")));


select.selectByVisibleText("Nov");

or

select.selectByValue("11");

GENERATING CUSTOMIZED CSS FROM HTML ATTRIBUTES


Locating by cssSelector

 tag and id
In this case we need to follow this syntax css = tag#id. For id we need to use #sign before id value.

65 | P a g e
<input id = "txtName" class = "textboxes" tabindex ="1" type = "text">
driver.findElement(By.cssSelector("input#txtName"));

 tag and class


In this case we need to follow this syntax css = tag.className. For className we need to use dot (.) before className
value.
 
<input id = "txtName" class = "textboxes" tabindex ="1" type = "text">
driver.findElement(By.cssSelector("input.textboxes"));
 
If there is space between className we need to use dot (.) in between space.
 
<input id = "txtName" class = "textboxes top" tabindex ="1" type = "text">
driver.findElement(By.cssSelector("input.textboxes.top"));
 
 tag and attribute
Syntax for this combination is tag[attribute = 'value']
 
<input value = "Reading" type = "checkbox">
 
Css = input[type = 'checkbox']
or
Css = input[value= 'Reading']
 
 tag, id and attribute
Syntax for this combination is tag#id [attribute='value']
 
<input id = "txtName" class = "textboxes" tabindex ="1" name = "taComment" type =
"text"> 
driver.findElement(By.cssSelector("input#txtName[name = 'taComment']"));
 
 tag, class and attribute
Syntax for this combination is tag.className [attribute='value']
 
<input id = "txtName" class = "textboxes" tabindex ="1" name = "taComment" type =
"text">
driver.findElement(By.cssSelector("input.textboxes[name = 'taComment']"));

Handling cssSelector with methods

 Using contains - For contains we need to use * symbol after attribute.


 
tagName[attribute* = 'value']
 

66 | P a g e
 Using start-with - For start-with we need to use ^ symbol after attribute.
 
tagName[attribute^ = 'value']
 
 Using end-with - For start-with we need to use $ symbol after attribute.
 
tagName[attribute$ = 'value']

IDENTIFYING XPATH
What is X-path
X-path is defined as XML path. It is a syntax or language for finding any element on the web page using XML path expression. X-
path is used to find the location of any element on a webpage using HTML DOM structure. The basic format of XPath is
explained below with screen shot.

Types of X-path
There are two types of X-path:
 
1. Absolute X-path
2. Relative X-path
 
Absolute X-path (/)
It is the direct way to find the element, but the disadvantage of the absolute XPath is that if there are any changes made in the
path of the element then that XPath gets failed.
 
The key characteristic of XPath is that it begins with the single forward slash (/), which means we can select the element from
the root node.
 
Below is the example of an absolute X-path expression of the element shown in the below screen.
 
html/body/div[1]/section/div[1]/div/div/div/div[1]/div/div/div/div/div[3]/div[1]/div/h4
[1]/b
 
Relative X-path (//)
For Relative Xpath the path starts from the middle of the HTML DOM structure. It starts with the double forward slash (//),
which means it can search the element anywhere at the webpage.
 

67 | P a g e
We can start from the middle of the HTML DOM structure and no need to write long X-path.

Below is the example of a relative XPath expression of the same element shown in the below screen. This is the common format
used to find element through a relative XPath.
 
//*[@class='featured-box']//*[text()='Testing']
 
Handling X-path with methods

 Using Contains() - Contains() is a method used in XPath expression. It is used when the value of any attribute changes
dynamically, for example, login information. The contain feature has an ability to find the element with partial text. It
takes two parameters.
 
//*[contains(@type, 'sub')]
 
 Using OR & AND - In OR expression, two conditions are used, whether 1st condition OR 2nd condition should be true. It
is also applicable if any one condition is true or maybe both. Means any one condition should be true to find the
element.
 
//*[@type='submit' OR @name='btnReset']
 
In AND expression, two conditions are used, both conditions should be true to find the element. It fails to find element
if any one condition is false.
 
//input[@type='submit' AND @name='btnLogin']
 
 Using Start-with function - Start-with function finds the element whose attribute value changes on refresh or any
operation on the webpage. In this expression, match the starting text of the attribute is used to find the element whose
attribute changes dynamically. We can also find the element whose attribute value is static (not changes).
 
For example -: Suppose the ID of element changes dynamically like:
 
Id=" message12"
Id=" message345"
Id=" message8769"
 
and so on... but the initial text is same. In this case, we use Start-with expression.
 
//label[starts-with(@id, 'message')]
 
 Using Text() - In this expression, with text function, we find the element with exact text.
 
//td[text()='UserID']
 
XPath axes methods 

68 | P a g e
These XPath axes methods are used to find the complex or dynamic elements. Below we will see some of these methods.
 
 Following: Selects all elements in the document of the current node.
 
Xpath=//*[@type='text']//following::input
 
Suppose if there are 3 "input" nodes matching by using "following" axis. If we want to focus on any particular element,
then we can use the below XPath method:
 
Xpath=//*[@type='text']//following::input[1]
 
 Ancestor: The ancestor axis selects all ancestor’s element (grandparent, parent, etc.) of the current node. In the below
expression, we are finding ancestors element of the current node.
 
Xpath=//*[text()='Text_Of_Element']//ancestor::div
  
 Child: Selects all children elements of the current node
 
Xpath=//*[@id='ID_Of_Element']/child::li
  
 Preceding: Select all nodes that come before the current node. In the below expression, it identifies all the input
elements before particular element.
 
Xpath=//*[@type='submit']//preceding::input
 
 
 Following-sibling: Select the following siblings of the context node. Siblings are at the same level of the current node. It
will find the element after the current node.
 
Xpath=//*[@type='submit']//following-sibling::input
 
 Parent: Selects the parent of the current node
 
Xpath=//*[@id='ID_Of_Element']//parent::div
 
 Self: Selects the current node or 'self' means it indicates the node itself. One node matching by using "self " axis. It
always finds only one node as it represents self-element.
 
Xpath =//*[@type='password']//self::input
 
 Descendant: Selects the descendants of the current node. In the below expression, it identifies all the element
descendants to current element which means down under the node (child node, grandchild node, etc.).
 
Xpath=//*[@id='ID_Of_Element']//descendant::a

69 | P a g e
Identify Xpath with Parent Child Traverse relationship
 We can find the Xpath using parent child relationship when we are not able to find unique or static Xpath directly. For
this first we will find the Xpath of parent and then traverse from parent to child using tags.
 To validate the generated Xpath go to the developer tool i.e. Chrome Browser by pressing F12 or using right click and
select Inspect element and after that start type Xpath in console window of the developer tool

$x("//div[@class='RNNXgb']")

 Now we are traverse from Parent to chid

HANDLING MOUSE INTERACTIONS

Handling keyboard and mouse events are done using the Advanced User Interactions API. It contains the Actions and the
Actions classes that are needed when executing these events.

In Action class we are performing the below actions:

70 | P a g e
 Mouse Over
 Mouse and Keyboard interactions
 Context clicks on element
 Double click on element
 Drag and drop the element

In the following example, we will use moveToElement() method to mouse-over and build() method is used to build the actions
and it is the final method which is used so that all the listed actions will be compiled into a single step or we can say it is ready to
use. The perform() method is used when we execute the Actions Object after building.

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.interactions.Actions;

public class ActionsDemo


{
public static void main(String[] args)
{
System.setProperty("webdriver.chrome.driver", "./driver/chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.manage().window().maximize();
driver.get("https://www.amazon.com");

WebElement signIn = driver.findElement(By.cssSelector("a#nav-link-accountList"));

// Create Actions Class Object


Actions action = new Actions(driver);
action.moveToElement(signIn).build().perform();
}
}

Example how to convert text from lower case to upper case using keyDown() method and doubleClick() on the text

WebElement textEnter = driver.findElement(By.id("twotabsearchtextbox"));

// Create Actions Class Object


Actions action = new Actions(driver);
action.moveToElement(textEnter).click().keyDown(Keys.SHIFT).sendKeys("macbook")
.doubleClick()
.build().perform();

71 | P a g e
Example shows how to right click on any element on the UI using contextClick() method.

WebElement signIn = driver.findElement(By.cssSelector("a#nav-link-accountList"));

// Create Actions Class Object


Actions action = new Actions(driver);
action.moveToElement(signIn).contextClick().build().perform();

DESIREDCAPABILITIES IN SELENIUM WEBDRIVER

The desired capability is a series of key/value pairs that stores the browser properties like browserName, browser version, the
path of the browser driver in the system, etc. to determine the behaviour of the browser at run time.

Desired capability can also be used to configure the driver instance of Selenium WebDriver.

72 | P a g e
We can configure driver instance like FirefoxDriver, ChromeDriver, InternetExplorerDriver by using desired capabilities.

Why do we need Desired Capabilities?

Every Testing scenario should be executed on some specific testing environment. The testing environment can be a web
browser, Mobile device, mobile emulator, mobile simulator, etc. The Desired Capabilities Class helps us to tell the webdriver,
which environment we are going to use in our test script.

The setCapability method of the DesiredCapabilities Class is used to set the browser properties (Ex. Chrome, IE), Platform
Name (Ex. Linux, Windows) that are used while executing the test cases.

Desired Capabilities are more useful in cases like:

 In mobile application automation, where the browser properties and the device properties can be set.
 In Selenium grid when we want to run the test cases on a different browser with different operating systems and
versions.
 In Cloud testing i.e. Sauce Labs in which we give the capabilities of different environments like browser name, platform
name, browser version etc.

Different types of Desired Capabilities Methods

 getBrowserName(): Get the name of the browser, we want to run the test cases.
 setBrowserName(): Setting the browser name on which we want to run the test cases.
 getVersion(): Get the browser version
 setVersion(): Setting the browser version
 getPlatfrom(): Get the platform name i.e. Windows10, Mac and Linux
 setPlatform(): Set the platform name
 getCapability(): The getCapability() method can be used to get the capability that is in use currently in the
system.
 setCapability(): The setCapability() method can be used to set the device name, platform version, platform
name, absolute path.

HANDLING MULTIPLE WINDOWS

What is a window handle?

A window handle is a unique identifier that holds the address of all the windows. This is basically a pointer to a window, which
returns the string value. This window handle function helps in getting the handles of all the windows. It is guaranteed that each
browser will have a unique window handle. By default, Selenium handles the Parent window and we have to tell the driver to
deliberately switch to child window.

 get.windowhandle(): helps in getting the window handle of the current window


 get.windowhandles(): helps in getting the handles of all the windows opened and the return type of this method is
set <String>
 set: helps to set the window handles which is in the form of a string. set<string> set= driver.get.windowhandles()
 switchTo: helps in switching between the windows
 action: helps to perform certain actions on the windows.

import java.util.Set;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;

public class MultipleWindowHandling

73 | P a g e
{
public static String lastWindowHandle = "";
public static int count = 0;

public static void main(String[] args)


{
System.setProperty("webdriver.chrome.driver", "./driver/chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.manage().window().maximize();
driver.get("https://accounts.google.com/signup");

// Main or Parent Window


String parentWindow = driver.getWindowHandle();
WebElement helpLink = driver.findElement(By.xpath("//a[text()='Help']"));
helpLink.click();
System.out.println("Before Switch to Child Window -> "+driver.getTitle());

// Created Set of Windows IDs


Set <String> windows = driver.getWindowHandles();
for(String window : windows)
{
count++;
System.out.println("List of Windows -> "+count+" : "+window);
driver.switchTo().window(window);
lastWindowHandle = window;
}
System.out.println("After Switch to Child Window -> "+driver.getTitle());
System.out.println("Last Window -> "+lastWindowHandle);
driver.switchTo().window(parentWindow);
System.out.println("Back to Parent Window -> "+parentWindow);
System.out.println("Switch to Parent Window -> "+driver.getTitle());
}
}

Output:

HOW TO HANDLE FRAMES

What is Iframe?

74 | P a g e
Iframe is a web page which is embedded in another web page or an HTML document embedded inside another HTML
document.

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 iframe:

Observe the below image, Advertisement being displayed is an Iframe, we cannot locate or recognize that by just inspecting. So,
the question is how can we identify the iframe?

We can identify the iframes using methods given below:

 Right click on the element, if we find the option like 'This Frame' then it is an iframe. (Please refer the above image)
 Right click on the page and click 'View Page Source' and Search with the 'iframe', if we can find any tag name with the
'iframe' then it is meaning to say the page consisting an iframe.

In above image, we can see that 'This Frame' option is available upon right clicking, so we are now sure that it is an iframe.

We can even identify total number of iframes by using below snippet.

Int size = driver.findElements(By.tagName("iframe")).size();

How to switch over the elements in iframes using Web Driver commands:
Basically, we can switch over the elements in frames using 3 ways.

 By Index
 By Name or Id
 By Web Element

Switch to the frame by index:

Index is one of the attributes for the Iframe through which we can switch to it. Index of the iframe starts with '0'.

Suppose if there are 100 frames in page, we can switch to the iframe by using index.

 driver.switchTo().frame(0);
75 | P a g e
 driver.switchTo().frame(1);

Switch to the frame by Name or ID:

Name and ID are attributes of iframe through which we can switch to it.

 driver.switchTo().frame("iframe1");
 driver.switchTo().frame("id of the element");

Switch to the frame by Web Element:

We can even switch to the iframe using web element.

 driver.switchTo().frame(WebElement);

How to switch back to the Main Frame

We have to come out of the iframe. To move back to the parent frame, we can either use switchTo().parentFrame() or if
we want to get back to the main (or most parent) frame, we can use switchTo().defaultContent()

 driver.switchTo().parentFrame();
 driver.switchTo().defaultContent();

How to switch over the frame, if we CANNOT switch using ID or Web Element:

Suppose if there are 100 frames in the page, and there is no ID available, in this case, we just don't know from which iframe
required element is being loaded (It is the case when we do not know the index of the frame also).

The solution for the above concern is, we must find the index of the iframe through which the element is being loaded and then
we need to switch to the iframe through the index.

Concept of Nested Frames (Frames inside Frames)

Let's assume that there are two frames one inside other like shown in below image and our requirement is printing the text in
the outer frame and inner frame.

In the case of nested frames,

 At first, we must switch to the outer frame by either Index or ID of the iframe
 Once we switch to the outer frame, we can find the total number of iframes inside the outer frame, and
 We can switch to the inner frame by any of the known methods.

While exiting out of the frame, we must exit out in the same order as we entered into it from the inner frame first and then
outer frame.

76 | P a g e
The Html code for the above nested frame is as shown below.

The above HTML code clearly explains the iframe tag (highlighted in green) within another iframe tag, indicating presence of
nested iframes.

Below are the steps for switching to outer frame and printing the text on outer frames:

Step 1)

 Switch to the outer Frame.


 Prints the text on outer frame.

Once we switch to the outer frame, we should know whether any inner frame present inside the outer frame

WebDriver driver=new FirefoxDriver();

driver.get("Url");

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

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

int size = driver.findElements(By.tagName("iframe")).size();

77 | P a g e
System.out.println("Total Frames --" + size);

// prints the total number of frames

driver.switchTo().frame(0); // Switching the Outer Frame

System.out.println (driver.findElement(By.xpath("Xpath of the outer element")).getText());

Step 2)

size = driver.findElements(By.tagName("iframe")).size();

// prints the total number of frames inside outer frame

System.out.println("Total Frames --" + size);

 Finds the total number of iframes inside outer frame.


 If size was found '0' then there is no inner frame inside the frame.

Step 3)

driver.switchTo().frame(0); // Switching to innerframe

System.out.println(driver.findElement(By.xpath("xpath of the inner element ")).getText());

 Switch to the inner frame


 Prints the text on the inner frame.

HANDLING DROP-DOWNS MECHANISM

STATIC DROPDOWNS WITH SELECT WEBDRIVER API


To declare the drop-down element as an instance of the Select class. This Select class object requires one WebElement i.e. on
which element we are performing the actions.

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.Select;

public class Dropdown


{

78 | P a g e
public static void main(String[] args)
{
System.setProperty("webdriver.chrome.driver", "./driver/chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("https://www.spicejet.com");

// Select Class for Static Dropdown


WebElement currency =
driver.findElement(By.id("ctl00_mainContent_DropDownListCurrency"));
Select select = new Select(currency);
select.selectByVisibleText("AED");
}
}

Following are some common methods used to drop-down elements. Note: We can use the below methods only when the
dropdown has Select property

Method Description

 Selects/deselects the option that


selectByVisibleText() and deselectByVisibleText() Example:
displays the text matching the
parameter.
 Parameter: The exactly displayed text
of a particular option

selectByValue() and deselectByValue() Example:  Selects/deselects the option whose


"value" attribute matches the
specified parameter.
 Parameter: value of the "value"
attribute
 Remember that not all drop-down
options have the same text and
"value", like in the example below.

 
 

selectByIndex() and deselectByIndex() Example:  Selects/deselects the option at the


   given index.

 Parameter: the index of the option to


be selected.

 Returns TRUE if the drop-down


isMultiple() Example:    element allows multiple selections at

79 | P a g e
a time; FALSE if otherwise.

 No parameters needed

deselectAll() Example:     Clears all selected entries. This is only


valid when the drop-down element
supports multiple selections.
 No parameters needed

LOOPING UI DROPDOWN
In the new web development applications, the dropdown nature has been changed from traditional Select approach to looping
UI dropdown.

To automate this type of dropdown we will loop the number of instances of click i.e. if we want to add the number of passengers
then we have to click that number of times so to automate this step we will keep this step-in loop.

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

public class UIDropDown


{
public static void main(String[] args) throws InterruptedException
{
System.setProperty("webdriver.chrome.driver", "./driver/chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("https://www.spicejet.com");

// Validate Text of the Drop down


String beforeClick = driver.findElement(By.id("divpaxinfo")).getText();

80 | P a g e
System.out.println("Before Click Drop down :"+beforeClick);

// Demo for UI Looping Drop down


driver.findElement(By.id("divpaxinfo")).click();
Thread.sleep(2000L);
for(int i=1; i<=4; i++)
{
driver.findElement(By.id("hrefIncAdt")).click();
}
driver.findElement(By.xpath("//input[@value='Done']")).click();

String afterClick = driver.findElement(By.id("divpaxinfo")).getText();


System.out.println("After Click Drop down :"+afterClick);
}
}

DYNAMIC DROPDOWN
Dynamic drop down are change dynamically at the time of execution or we can say when we try to select or search for specific
content on this dropdown the content will changed accordingly. So, there is no static content. See the below image, in this
dropdown content will changes as per our selection.

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

public class Dropdown


{

81 | P a g e
public static void main(String[] args) throws InterruptedException
{
System.setProperty("webdriver.chrome.driver", "./driver/chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.manage().window().maximize();
driver.get("https://www.spicejet.com");

driver.findElement(By.id("ctl00_mainContent_ddl_originStation1_CTXT")).click();
driver.findElement(By.xpath("//a[@value='BLR']")).click();
Thread.sleep(2000);
driver.findElement(By.xpath("(//a[@value='MAA'])[2]")).click();
}
}

AUTO SUGGESTIVE DROPDOWNS


Autocomplete or Auto Suggestion allows the browser to predict the value. When a user starts to type in a field, the browser
should display options to fill in the field, based on earlier typed values. The auto complete works

import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;

public class AutoSuggestiveDropdown


{
public static void main(String[] args) throws InterruptedException
{
System.setProperty("webdriver.chrome.driver", "./driver/chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.manage().window().maximize();
driver.get("https://www.makemytrip.com/");
Thread.sleep(2000);

driver.findElement(By.xpath("//input[@id='fromCity']")).click();
driver.findElement(By.xpath("//div[@class='hsw_autocomplePopup
autoSuggestPlugin']/div/input")).sendKeys("MUM");
Thread.sleep(2000);
List <WebElement> list = driver.findElements(By.xpath("//p[@class='font14
appendBottom5 blackText']"));
System.out.println("Auto Suggest List ::" + list.size());

for(int i = 0;i< list.size();i++)


{
String cityList = list.get(i).getText();

82 | P a g e
System.out.println(cityList);
if(cityList.equals("Mumbai, India"))
{
list.get(i).click();
break;
}
}
driver.findElement(By.xpath("//div[@class='hsw_autocomplePopup
autoSuggestPlugin']/div/input")).sendKeys("DEL");
Thread.sleep(2000);
List <WebElement> toList = driver.findElements(By.xpath("//p[@class='font14
appendBottom5 blackText']"));
System.out.println("Auto Suggest List ::" + toList.size());

for(int i = 0;i< toList.size();i++)


{
String cityList = toList.get(i).getText();
System.out.println(cityList);
if(cityList.equals("Delhi, India"))
{
toList.get(i).click();
break;
}
}
}
}

HANDLING JAVA ALERTS

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. Alerts are not being the part of DOM
structure so we are not able to inspect alerts as these are not part of our HTML application.

To handle the alerts using selenium, there is method called “switchTo().alert()” by this method the context of the driver will
changed to alerts

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

public class Alerts


{
public static void main(String[] args) throws InterruptedException
{
System.setProperty("webdriver.chrome.driver", "./driver/chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.manage().window().maximize();

83 | P a g e
driver.get("https://rahulshettyacademy.com/AutomationPractice/");

driver.findElement(By.id("name")).sendKeys("Armaan");
driver.findElement(By.id("alertbtn")).click();

// Grab the Alert Text


System.out.println(driver.switchTo().alert().getText());

// Switch to Alert
driver.switchTo().alert().accept();
}
}

Methods in Alerts

 void dismiss() - To click on the 'Cancel' button of the alert.

driver.switchTo().alert().dismiss();
 
 void accept() - To click on the 'OK' button of the alert.

driver.switchTo().alert().accept();
 
 String getText() - To capture the alert message.

driver.switchTo().alert().getText();
 
 sendKeys(String stringToSend) - To send some data to alert box.                        

driver.switchTo().alert().sendKeys("Text");

HANDLING DYNAMIC WEB TABLES

There are two types of HTML tables published on the web

Static tables: Data is static i.e. Number of rows and columns are fixed.

Dynamic tables: Data is dynamic i.e. Number of rows and columns are NOT fixed.

Below is an example of a dynamic table of Sales. Based on input date filters, number of rows will get altered. So, it is dynamic in
nature.

84 | P a g e
Handling static table is easy, but dynamic table is a little bit difficult as rows and columns are not constant.

Using X-Path to Locate Web Table Elements

Before we locate web element, first let's understands-

What is a web element?

Web elements are nothing but HTML elements like textbox, dropdowns radio buttons, submit buttons, etc. These HTML
elements are written with start tag and ends with an end tag.

Steps for getting X-path of web element that we want to locate.

 Step 1) In Chrome, Go to http://money.rediff.com/gainers/bsc/daily/groupa

 Step 2) Right click on web element whose x-path is to be fetched. In our case, right click on "Company" Select Inspect
option. The following screen will be shown -

85 | P a g e
 Step 3) Right Click on highlighted web element > Select Copy -> Copy x-path option.
 Step 4) Use the copied X-path "//*[@id="leftcontainer"]/table/thead/tr/th [1]" in Selenium WebDriver to locate the
element.

Example: Fetch number of rows and columns from Dynamic Web Table

When the table is dynamic in nature, we cannot predict its number of rows and columns.

Using Selenium web driver, we can find

 Number of Rows and columns of web table


 X row or Y column's data.

Below is program for fetching total number of rows and columns of web table.

86 | P a g e
Example: Fetch cell value of a particular row and column of the Dynamic Table

Let's assume we need 3rd row of the table and its second cell's data. See the table below-

87 | P a g e
In above table, data is regularly updated after some span of time. The data we try retrieve will be different from the above
screenshot. However, the code remains the same. Here is sample program to get the 3rd row and 2nd column's data.

88 | P a g e
HANDLING CHECKBOX

Toggling a check box on/off is also done using the click() method. If want to validate that the checkbox is selected or not then in
Selenium, we have a method with “isSelected()” to check the checkbox. This method will return the Boolean value i.e. true or
false if checkbox selected then it is true otherwise false.

import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;

public class CheckBox


{
public static void main(String[] args) throws InterruptedException
{
System.setProperty("webdriver.chrome.driver", "./driver/chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.manage().window().maximize();

89 | P a g e
driver.get("https://www.spicejet.com");

WebElement seniorCitizen_Chkbx =
driver.findElement(By.cssSelector("input[id*='SeniorCitizenDiscount']"));
System.out.println("Before Clicked :: "+seniorCitizen_Chkbx.isSelected());
seniorCitizen_Chkbx.click();
System.out.println("After Clicked :: "+seniorCitizen_Chkbx.isSelected());

List <WebElement> checkList =


driver.findElements(By.xpath("//input[@type='checkbox']"));
System.out.println("Checkbox List ::" + checkList.size());

}
}

SYNCHRONIZATION IN SELENIUM (WAITS)

In selenium "Waits" play an important role in executing tests.

Why Do We Need Waits in Selenium?

Most of the web applications are developed using Ajax and JavaScript. When a page is loaded by the browser the elements
which we want to interact with may load at different time intervals.

Not only it makes this difficult to identify the element but also if the element is not located it will throw an
"ElementNotVisibleException" exception. Using Waits, we can resolve this problem.

Let's consider a scenario where we have to use both implicit and explicit waits in our test. Assume that implicit wait time is set
to 20 seconds and explicit wait time is set to 10 seconds.

Suppose we are trying to find an element which has some "ExpectedConditions "(Explicit Wait), if the element is not located
within the time frame defined by the Explicit wait (10 Seconds), it will use the time frame defined by implicit wait (20 seconds)
before throwing an "ElementNotVisibleException".

There are three types of Selenium Web Driver Waits

1. Implicit Wait
2. Explicit Wait
3. Fluent Wait

IMPLICIT WAIT
The implicit wait will tell to the web driver to wait for certain amount of time before it throws a "No Such Element Exception".
The default setting is 0. Once we set the time, web driver will wait for that time before throwing an exception.

In the below example we have declared an implicit wait with the time frame of 10 seconds. It means that if the element is not
located on the web page within that time frame, it will throw an exception.

To declare implicit wait:

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

90 | P a g e
Implicit wait will accept 2 parameters, the first parameter will accept the time as an integer value and the second parameter will
accept the time measurement in terms of SECONDS, MINUTES, MILISECOND, MICROSECONDS, NANOSECONDS, DAYS, HOURS,
etc.

EXPLICIT WAIT
The explicit wait is used to tell the Web Driver to wait for certain conditions (Expected Conditions) or the maximum
time exceeded before throwing an "ElementNotVisibleException" exception.

The explicit wait is an intelligent kind of wait, but it can be applied only for specified elements. Explicit wait gives
better options than that of an implicit wait as it will wait for dynamically loaded Ajax elements.

Once we declare explicit wait we have to use "ExpectedCondtions" or we can configure how frequently we want to
check the condition using Fluent Wait. These days while implementing we are using Thread.Sleep() generally it is not
recommended to use

In the below example, we are creating reference wait for "WebDriverWait" class and instantiating using
"WebDriver" reference, and we are giving a maximum time frame of 20 seconds.

WebElement link = driver.findElement(By.xpath("//div[@id='content']/p/following


sibling::a[2]"));
link.click();

WebElement linkText = driver.findElement(By.id("results"));


WebDriverWait wait = new WebDriver(driver, 20);
wait.until(ExpectedConditions.visibilityOf(linkText));
System.out.println(linkText.getText());

The above code states that we are waiting for an element for the time frame of 20 seconds as defined in the "WebDriverWait"
class on the webpage until the "ExpectedConditions" are met and the condition is "visibilityOf".

The following are the Expected Conditions that can be used in Explicit Wait

1. alertIsPresent()

2. elementSelectionStateToBe()

3. elementToBeClickable()

4. elementToBeSelected()

5. frameToBeAvaliableAndSwitchToIt()

6. invisibilityOfTheElementLocated()

7. invisibilityOfElementWithText()

8. presenceOfAllElementsLocatedBy()

9. presenceOfElementLocated()

10. textToBePresentInElement()

91 | P a g e
11. textToBePresentInElementLocated()

12. textToBePresentInElementValue()

13. titleIs()

14. titleContains()

15. visibilityOf()

16. visibilityOfAllElements()

17. visibilityOfAllElementsLocatedBy()

18. visibilityOfElementLocated()

FLUENT WAIT
The fluent wait is used to tell the web driver to wait for a condition, as well as the frequency with which we want to check the
condition before throwing an "ElementNotVisibleException" exception.

Frequency: Setting up a repeat cycle with the time frame to verify/check the condition at the regular interval of time

Let's consider a scenario where an element is loaded at different intervals of time. The element might load within 10 seconds, 20
seconds or even more then that if we declare an explicit wait of 20 seconds. It will wait till the specified time before throwing an
exception. In such scenarios, the fluent wait is the ideal wait to use as this will try to find the element at different frequency until
it finds it or the final timer runs out.

Please Note: Fluent Wait and WebDriver Wait are the classes implement Wait Interface.

Syntax:

Wait wait = new FluentWait(WebDriver reference)

.withTimeout(timeout, SECONDS)

.pollingEvery(timeout, SECONDS)

.ignoring(Exception.class);

Wait<WebDriver> wait = new FluentWait<WebDriver> (driver)

.withTimeout(30, TimeUnit.SECONDS)

.pollingEvery(5, TimeUnit.SECONDS)

.ignoring(NoSuchElementException.class);

In the above example, we are declaring a fluent wait with the timeout of 30 seconds and the frequency is set to 5 seconds by
ignoring "NoSuchElementException"

Frequency is set to 5 seconds and the maximum time is set to 30 seconds. Thus, this means that it will check for the element on
the web page at every 5 seconds for the maximum time of 30 seconds. If the element is located within this time frame it will
perform the operations else, it will throw an" ElementNotVisibleException"

HOW TO TAKE SCREENSHOTS

92 | P a g e
Screenshots are desirable for bug analysis. Selenium can automatically take screenshots during execution. We need to type cast
WebDriver instance to TakesScreenshot.

Taking Screenshot in Selenium is a 3 Step process

Step 1) Convert web driver object to TakeScreenshot

TakesScreenshot scrShot = ((TakesScreenshot)driver);

Step 2) Call getScreenshotAs method to create image file

File file = scrShot.getScreenshotAs(OutputType.FILE);

Step 3) Copy file to Desired Location

FileUtils.copyFile(source, target)

import java.io.File;
import java.io.IOException;
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.chrome.ChromeDriver;

public class ScreenShot


{
public static void main(String[] args) throws IOException
{
System.setProperty("webdriver.chrome.driver", "./driver/chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.manage().window().maximize();
driver.get("https://www.google.com");
driver.findElement(By.name("q")).sendKeys("Selenium");

File fileName = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);


FileUtils.copyFile(fileName, new File("./ScreenShots/Search.png"));

93 | P a g e
}
}

HANDLING CALENDAR UI

To handle the calendar date picker first check the current date elements, if we see any difference in this this means that we will
find the current date with unique elements.

import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;

public class CalendarUI


{
public static void main(String[] args)
{
System.setProperty("webdriver.chrome.driver", "./driver/chromedriver.exe");
WebDriver driver = new ChromeDriver();
JavascriptExecutor js = (JavascriptExecutor) driver;
driver.manage().window().maximize();
driver.get("https://www.cathaypacific.com");

WebElement toDate = driver.findElement(By.xpath("//div[@class='dates-picker-


wrapper splited-date-picker flight-datepicker']/div[1]"));

//This will scroll the page till the element is found


js.executeScript("arguments[0].scrollIntoView();", toDate);
toDate.click();

WebElement months = driver.findElement(By.cssSelector(".ui-datepicker-month"));


WebElement nextButton = driver.findElement(By.xpath("(//div[@class='ui-datepicker-
group ui-datepicker-group-last']/a[@data-handler='next'])[2]"));
while(!months.getText().contains("December"))
{
nextButton.click();
}

List<WebElement> dates = driver.findElements(By.cssSelector("a.ui-state-


default"));

for(int i=0;i<dates.size();i++)
{
String datesList = dates.get(i).getText();

94 | P a g e
if(datesList.equalsIgnoreCase("23"))
{
dates.get(i).click();
break;
}
}
}
}

CHAPTER 3
ADVANCED TECHNIQUES OF SELENIUM WEBDRIVER
INTRODUCTION TO MAVEN

Apache Maven is a software project management and build management tool for Java Frameworks. Based on the concept of a
project object model (POM), Maven can manage a project's build, reporting and documentation from a central piece of
information.

Apache Maven provides support for managing the full lifecycle of a test project.

 It is the central repository to get dependencies.


 Flexibility in integrating with CI tools.
 Maintaining common structure across the organization.
 Maven is used to define project structure, dependencies, build, and test management.
 Using pom.xml (Maven) we can configure dependencies needed for building testing and running code.
 Maven automatically downloads the necessary files from the repository while building the project.

INSTALLING AND CONFIGURING MAVEN


 Download Maven and add ‘MAVEN_HOME’ Environment Variables
Maven can be downloaded from https://maven.apache.org/download.cgi I have extracted in my local directory. We can
choose our own location.

Set the MAVEN_HOME variable to maven installation folder.

Include ‘maven/bin’ directory in ‘PATH’ variable. To run maven from command prompt, this is necessary.

To verify maven in console type mvn –version

95 | P a g e
TERMINOLOGIES OF MAVEN
ArtifactID and GroupID are the most commonly heard terms in the maven.

 ArtifactID is a file, usually a JAR, that gets deployed to a Maven repository.


 GroupID will identify our project uniquely across all projects.
 archetype:generate generates a new project from an archetype

Processes which can manage using maven:

 Builds
 Documentation
 Reporting
 Dependencies
 SCMs
 Releases
 Distribution
 mailing list

WHAT IS POM.XML FILE IN MAVEN


POM is an acronym for Project Object Model. The pom.xml file contains information of project and configuration information
for the maven to build the project such as dependencies, build directory, source directory, test source directory, plugin, goals
etc.

Maven reads the pom.xml file, then executes the goal.

Elements of maven pom.xml file

Element Description

project It is the root element of pom.xml file.

groupId It is the sub element of project. It specifies the id for the project group.

It is the sub element of project. It specifies the id for the artifact (project). An artifact is something that is
artifactId either produced or used by a project. Examples of artifacts produced by Maven for a project include:
JARs, source and binary distributions, and WARs.

version It is the sub element of project. It specifies the version of the artifact under given group.

96 | P a g e
name defines name of the maven project.

dependencies defines dependencies for this project.

dependency defines a dependency. It is used inside dependencies.

scope defines scope for this maven project. It can be compile, provided, runtime, test and system.

BUILD PHASES IN MAVEN


Each build life cycle is divided into a sequence of build phases, and the build phases are again subdivided into goals. Thus, the
total build process is a sequence of build life cycle(s), build phases and goals.

When we execute a build phase, all build phases before that build phase in this standard phase sequence are executed. Thus,
executing the install build phase really means executing all build phases before the install phase, and then execute the install
phase after that.

In Maven different build phases through which we can build our project. Below are the most commonly used build phases are:

Build Phases Description

Validates that the project is correct and all necessary information is available. This also makes sure the
validate
dependencies are downloaded.

compile Compiles the source code of the project.

Runs the tests against the compiled source code using a suitable unit testing framework. These tests
test
should not require the code be packaged or deployed.

package Packs the compiled code in its distributable format, such as a JAR.

install Install the package into the local repository, for use as a dependency in other projects locally.

deploy Copies the final package to the remote repository for sharing with other developers and projects.

97 | P a g e
WHAT IS MAVEN PLUGINS
Maven plugins enable us to add our own actions to the build process. We do so by creating a simple Java class that extends a
special Maven class, and then create a POM for the project. The plugin should be located in its own project.

INTRODUCTION TO TESTNG TESTING FRAMEWORK

TestNG is an open source automated testing framework where "NG" means "Next Generation"

Why do we need TestNG in Selenium?

TestNG can generate reports based on our Selenium test results.

 WebDriver has no native mechanism for generating reports.


 TestNG can generate the report in a readable format like the one shown below.

98 | P a g e
TestNG simplifies the way the tests are coded

 There is no more need for a static main method in our tests. The sequence of actions is regulated by easy-to-
understand annotations that do not require methods to be static.

99 | P a g e
 Uncaught exceptions are automatically handled by TestNG without terminating the test prematurely. These exceptions
are reported as failed steps in the report.

ANNOTATIONS IN TESTNG
Annotations are the predefined text, which holds a specific meaning. It lets the compiler/interpreter know, what should be
done upon execution.

Sr.No. Annotation & Description

1 @BeforeSuite - The annotated method will be run only once before all tests in this suite have run.

2 @AfterSuite - The annotated method will be run only once after all tests in this suite have run.

@BeforeClass - The annotated method will be run only once before the first test method in the current class is
3
invoked.

4 @AfterClass - The annotated method will be run only once after all the test methods in the current class have run.

@BeforeTest - The annotated method will be run before any test method belonging to the classes inside the
5
<test> tag is run.

100 | P a g e
@AfterTest - The annotated method will be run after all the test methods belonging to the classes inside the
6
<test> tag have run.

@BeforeGroups - The list of groups that this configuration method will run before. This method is guaranteed to
7
run shortly before the first test method that belongs to any of these groups is invoked.

@AfterGroups - The list of groups that this configuration method will run after. This method is guaranteed to run
8
shortly after the last test method that belongs to any of these groups is invoked.

9 @BeforeMethod - The annotated method will be run before each test method.

10 @AfterMethod - The annotated method will be run after each test method.

@DataProvider - 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. The @Test method that
11
wants to receive data from this DataProvider needs to use a DataProvider name equals to the name of this
annotation.

@Factory - Marks a method as a factory that returns objects that will be used by TestNG as Test classes. The
12
method must return Object[ ].

13 @Listeners - Defines listeners on a test class.

14 @Parameters - Describes how to pass parameters to a @Test method.

15 @Test - Marks a class or a method as a part of the test.

package testng;

import org.testng.annotations.AfterClass;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.AfterSuite;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.BeforeSuite;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;

public class TestngAnnotation {

101 | P a g e
// Test Case 1
@Test
public void testCase1() {
System.out.println("Test Case 1");
}

// Test Case 2
@Test
public void testCase2() {
System.out.println("Test Case 2");
}

@BeforeMethod
public void beforeMethod() {
System.out.println("In BeforeMethod");
}

@AfterMethod
public void afterMethod() {
System.out.println("In AfterMethod");
}

@BeforeClass
public void beforeClass() {
System.out.println("In BeforeClass");
}

@AfterClass
public void afterClass() {
System.out.println("In AfterClass");
}

@BeforeTest
public void beforeTest() {
System.out.println("In BeforeTest");
}

@AfterTest
public void afterTest() {
System.out.println("In AfterTest");
}

@BeforeSuite

102 | P a g e
public void beforeSuite() {
System.out.println("In BeforeSuite");
}

@AfterSuite
public void afterSuite() {
System.out.println("In AfterSuite");
}
}

Output:

HOW TO EXECUTE TESTNG TESTS


The test cases are executed using TestNG class. This class is the main entry point for running tests in the TestNG framework.
Users can create their own TestNG object and invoke it in many different ways such as −

 On an existing testng.xml.
 On a synthetic testng.xml, created entirely from Java.
 By directly setting the test classes.

Testng.xml file:

<?xml version="1.0" encoding="UTF-8"?>


<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="Suite">
<test thread-count="5" name="Test">
<classes>
<class name="testng.TestngAnnotation"/>
</classes>
</test> <!-- Test -->

103 | P a g e
</suite> <!-- Suite -->

The following table lists all the legal attributes that <suite> accepts.

Sr.No. Attribute & Description

1 name - The name of this suite. It is a mandatory attribute.

2 verbose - The level or verbosity for this run.

3 parallel - Whether TestNG should run different threads to run this suite.

4 thread-count - The number of threads to use, if parallel mode is enabled (ignored other-wise).

5 annotations - The type of annotations We are using in the tests.

6 time-out - The default timeout that will be used on all the test methods found in this test.

HOW TO IGNORE OR DISABLED TESTS


Sometimes, it happens that our code is not ready and the test case written to test that method/code fails. In such cases,
annotation @Test(enabled = false) helps to disable this test case. If a test method is annotated with @Test(enabled = false),
then the test case that is not ready to test is bypassed.

Now, let's see @Test(enabled = false) in action.

package testng;

import org.testng.annotations.AfterClass;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.AfterSuite;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.BeforeSuite;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;

public class TestngAnnotation {

// Test Case 1
@Test(enabled = false)
public void testCase1() {

104 | P a g e
System.out.println("Test Case 1");
}

// Test Case 2
@Test
public void testCase2() {
System.out.println("Test Case 2");
}

@BeforeMethod
public void beforeMethod() {
System.out.println("In BeforeMethod");
}

@AfterMethod
public void afterMethod() {
System.out.println("In AfterMethod");
}

@BeforeClass
public void beforeClass() {
System.out.println("In BeforeClass");
}

@AfterClass
public void afterClass() {
System.out.println("In AfterClass");
}

@BeforeTest
public void beforeTest() {
System.out.println("In BeforeTest");
}

@AfterTest
public void afterTest() {
System.out.println("In AfterTest");
}

@BeforeSuite
public void beforeSuite() {
System.out.println("In BeforeSuite");
}

105 | P a g e
@AfterSuite
public void afterSuite() {
System.out.println("In AfterSuite");
}
}

Output:

GROUPING OF TESTS
Group test is a new innovative feature in TestNG, which doesn’t exist in JUnit framework. It permits us to dispatch methods into
proper portions and perform sophisticated groupings of test methods.

Not only can declare those methods that belong to groups, but we can also specify groups that contain other groups. Then,
TestNG can be invoked and asked to include a certain set of groups (or regular expressions), while excluding another set.

Group tests provide maximum flexibility in how we partition the tests, and doesn't require to recompile anything if We want to
run two different sets of tests back to back.

Now, let's take an example to see how group test works.

106 | P a g e
package testng;

import org.testng.annotations.Test;

public class GroupingExample


{
// Group 1
@Test(groups = {"Smoke Testing"})
public void smokeTest() {
System.out.println("Smoke Testing Group");
}

// Group 2
@Test(groups = {"Regression Testing"})
public void regressionTest() {
System.out.println("Regression Testing Group");
}

// Group 3
@Test(groups = {"Unit Testing"})
public void unitTest() {
System.out.println("Unit Testing Group");
}
}

Groups are specified in the testng.xml file using the <groups> tag with <run> tag that specify group will include or which
exclude. It can be found either under the <test> or <suite> tag. Groups specified in the <suite> tag apply to all the <test> tags
underneath.

Testng.xml file:

<?xml version="1.0" encoding="UTF-8"?>


<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="Suite">
<test thread-count="5" name="Group Test Example">
<groups>
<run>
<include name = "Smoke Testing"/>
<include name = "Unit Testing"/>
</run>
</groups>

<classes>
<class name="testng.GroupingExample"/>
<class name="testng.TestngAnnotation"/>
</classes>

107 | P a g e
</test> <!-- Test -->
</suite> <!-- Suite -->

Output:

As mentioned above we have included two groups only in testng.xml

DEPENDENCY OF TESTS
Sometimes, we may need to invoke methods in a test case in a particular order, or we may want to share some data and state
between methods. This kind of dependency is supported by TestNG, as it supports the declaration of explicit dependencies
between test methods.

TestNG allows us to specify dependencies either with −

1. Using attribute dependsOnMethods in @Test annotations, OR.


2. Using attribute dependsOnGroups in @Test annotations.

Example using dependsOnMethods

package testng;

import org.testng.annotations.Test;

public class DependencyTest


{
@Test(dependsOnMethods = { "initEnvironmentTest" })
public void testDependency()
{
System.out.println("Inside testDependency()");
}

@Test
public void initEnvironmentTest()
{
System.out.println("This is initEnvironmentTest()");
}
}

Output:

108 | P a g e
Example using dependsOnGroups

package testng;

import org.testng.annotations.Test;

public class DependsOnGroupTest


{
@Test(dependsOnGroups = { "initialization group" })
public void testDependency()
{
System.out.println("Inside testDependency()");
}

@Test(groups = {"initialization group"})


public void initEnvironmentTest()
{
System.out.println("This is initialization group");
}
}

Output:

109 | P a g e
If a method depended upon fails, and we have a hard dependency on it (alwaysRun=false, which is the default), the methods
that depend on it are not marked as FAIL but as SKIP. Skipped methods will be reported as such in the final report, which is
important since skipped methods are not necessarily failures.

TEST PRIORITY
We can run a single or multiple test cases in our TestNG code. If test priority is not defined while running multiple test cases,
TestNG assigns all @Test a priority as zero (0).

Now, while running; lower priorities will be scheduled first. If we don’t mention any priority, TestNG will execute the @Test
methods based on alphabetical order of their method names irrespective of their place of implementation in the code.

package testng;

import org.testng.annotations.Test;

public class TestNGPriority {

@Test
public void c_method() {
System.out.println("I'm in method C");
}

@Test
public void b_method() {
System.out.println("I'm in method B");
}

@Test
public void a_method() {
System.out.println("I'm in method A");
}

110 | P a g e
@Test
public void e_method() {
System.out.println("I'm in method E");
}

@Test
public void d_method() {
System.out.println("I'm in method D");
}
}

Output:

Though we defined the methods in a random manner (c, b, a, e, d), TestNG executed the methods based on their method names
by considering alphabetical order and the same was reflected in the output as well.

Importance of Priority in running TestNG methods

As we have seen in the previous example that sequencing required in order to pass this scenario, so we will be modifying the
previous piece of code with Priority Parameter so that each test should run against to the priority assigned to them.

Now as we can see we have assigned the Priority to each test case means test case will the lower priority value will be executed
first.

Number 0 has the highest priority (it’ll be executed first) and the priority goes on based on the given number i.e., 0 has the
highest priority than 1. 1 has the highest priority than 2 and so on.

package testng;

111 | P a g e
import org.testng.annotations.Test;

public class TestNGPriority {

@Test(priority=6)
public void c_method() {
System.out.println("I'm in method C");
}

@Test(priority=9)
public void b_method() {
System.out.println("I'm in method B");
}

@Test(priority=1)
public void a_method() {
System.out.println("I'm in method A");
}

@Test(priority=0)
public void e_method() {
System.out.println("I'm in method E");
}

@Test(priority=3)
public void d_method() {
System.out.println("I'm in method D");
}
}

Output:

112 | P a g e
Methods with Same Priority

There may be a chance that methods may contain same priority. In those cases, TestNG considers the alphabetical order of the
method names whose priority is same.

Combining both prioritized (having same priority) and non-prioritized methods

In this case, we’ll cover two cases in one TestNG class.

 Methods having same priority value.


 More than one non-prioritized methods.

package testng;

import org.testng.annotations.Test;

public class TestNGPriorityEx {

// No Priority
@Test()
public void c_method() {
System.out.println("I'm in method C");
}

// No Priority
@Test()
public void b_method() {
System.out.println("I'm in method B");

113 | P a g e
}

// With Priority
@Test(priority=6)
public void a_method() {
System.out.println("I'm in method A");
}

@Test(priority=0)
public void e_method() {
System.out.println("I'm in method E");
}

// With Same Priority of Method a


@Test(priority=6)
public void d_method() {
System.out.println("I'm in method D");
}
}

Output:

Please Note:

First preference: Non-prioritized methods: ‘c’ and ‘b’: Based on alphabetical order ‘b’ was executed first and then ‘c’.

114 | P a g e
Second preference: Prioritized methods: ‘a’, ‘e’ and ‘d’, ‘e’ was executed first as it was having highest priority(0). As the priority
of ‘a’ and ‘d’ methods were same, testng considered the alphabetical order of their methods names. So, between them, ‘a’ was
executed first and then ‘d’.

PARAMETRIZATION IN TESTS
TestNG is parametric testing. In most cases, we will come across a scenario where the business logic requires a hugely varying
number of tests. Parameterized tests allow developers to run the same test over and over again using different values.

TestNG lets us pass parameters directly to our test methods in two different ways −

 With testng.xml
 With Data Providers

Passing Parameters with testng.xml

With this technique, we define the simple parameters in the testng.xml file and then reference those parameters in the source
files. Let us have an example to demonstrate how to use this technique to pass parameters.

 Create a java test class, say, ParameterizedTest.java.


 Add test method parameterTest() to our test class. This method takes a string as input parameter.
 Add the annotation @Parameters("myName") to this method. The parameter would be passed a value from testng.xml

package testng;

import org.testng.annotations.Parameters;
import org.testng.annotations.Test;

public class ParameterizedTest


{
@Test
@Parameters("myName")
public void parameterTest(String myName)
{
System.out.println("Parameter value : "+myName);
}

115 | P a g e
}

Testng.xml file:

<?xml version="1.0" encoding="UTF-8"?>


<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="Suite">
<test thread-count="5" name="Parameterization Test Example">
<parameter name="myName" value="Arman Khandelwal" />
<classes>
<class name="testng.ParameterizedTest" />
</classes>
</test>
</suite>

Output:

We can also define the parameters at the <suite> level. Suppose we have defined myName at both <suite> and <test> levels. In
such cases, regular scoping rules apply. It means that any class inside <test> tag will see the value of parameter defined in
<test>, while the classes in the rest of the testng.xml file will see the value defined in <suite>.

Now, run testng.xml, which will run the parameterTest method. TestNG will try to find a parameter named myName first in the
<test> tag, and then, if it can’t find it, it searches in the <suit> tag that encloses it.

Passing Parameters with DataProvider

When we need to pass complex parameters or parameters that need to be created from Java (complex objects, objects read
from a property file or a database, etc.), parameters can be passed using DataProvider.

A Data Provider is a method annotated with @DataProvider. This annotation has only one string attribute: its name. If the
name is not supplied, the data provider’s name automatically defaults to the method’s name. A data provider returns an array
of objects.

Data provider returns a two-dimensional JAVA object to the test method and the test method, will invoke M times in a M*N type
of object array. For example, if the DataProvider returns an array of 2*3 objects, the corresponding TestCases will be invoked 2
times with 3 parameters each time.

package testng;

import java.io.File;

116 | P a g e
import java.io.IOException;
import java.util.concurrent.TimeUnit;
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.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;

public class DataProviderEx


{
public static WebDriver driver;

@BeforeTest
public void getDriver()
{

System.setProperty("webdriver.chrome.driver","src/test/resources/driver/chromedriver.exe");
ChromeOptions options = new ChromeOptions();
options.addArguments("disable-infobars");
driver = new ChromeDriver(options);
driver.manage().window().maximize();
}

@Test(dataProvider="search")
public void parameterTest(String searchData) throws IOException
{
driver.get("https://www.google.com/");
WebElement searchTextBox = driver.findElement(By.name("q"));
searchTextBox.sendKeys(searchData);
getScreenShot();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
}

@DataProvider(name="search")
public static Object[][] getData()
{

117 | P a g e
return new Object[][]
{
{"Selenium"},
{"RestAssured"}
};
}

public static void getScreenShot() throws IOException


{
TakesScreenshot scrShot =((TakesScreenshot)driver);
File fileName=scrShot.getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(fileName, new
File("src/test/resources/ScreenShots/"+System.currentTimeMillis()+".png"));
}
}

Output:

118 | P a g e
LISTENERS IN TESTNG
There are two main listeners.

1. WebDriver Listeners
2. TestNG Listeners

What is Listeners in Selenium WebDriver

Listener is defined as interface that modifies the default TestNG's Behavior. As the name suggests Listeners " listen" to the event
defined in the selenium script and behave accordingly. It is used in selenium by implementing Listeners Interface. It allows
customizing TestNG reports or logs. There are many types of TestNG listeners available.

Types of Listeners in TestNG

There are many types of listeners which allows you to change the TestNG's Behavior.

Below are the few TestNG listeners:

1. IAnnotationTransformer
2. IAnnotationTransformer2
3. IConfigurable

119 | P a g e
4. IConfigurationListener
5. IExecutionListener
6. IHookable
7. IInvokedMethodListener
8. IInvokedMethodListener2
9. IMethodInterceptor
10. IReporter
11. ISuiteListener
12. ITestListener

Above Interface are called TestNG Listeners. These interfaces are used in selenium to generate logs or customize the Testing
reports.

ITestListener has following methods

 OnStart - OnStart method is called when any Test starts.


 onTestSuccess - onTestSuccess method is called on the success of any Test.
 onTestFailure - onTestFailure method is called on the failure of any Test.
 onTestSkipped - onTestSkipped method is called on skipped of any Test.
 onTestFailedButWithinSuccessPercentage - method is called each time Test fails but is within success percentage.
 onFinish - onFinish method is called after all Tests are executed.

Steps to create a TestNG Listener

Step 1) Create class "ListenerDemo" and implements “ITestListener”. Move the mouse over redline text, and Eclipse will suggest
us 2 quick fixes.

Just click on "Add unimplemented methods". Multiple unimplemented methods (without a body) is added to the code. Check
below-

package testng;

import org.testng.ITestContext;
import org.testng.ITestListener;
import org.testng.ITestResult;

public class ListenerDemo implements ITestListener


{

public void onFinish(ITestContext arg0) {


// TODO Auto-generated method stub

public void onStart(ITestContext arg0) {


// TODO Auto-generated method stub

120 | P a g e
public void onTestFailedButWithinSuccessPercentage(ITestResult arg0) {
// TODO Auto-generated method stub

public void onTestFailure(ITestResult result) {


// TODO Auto-generated method stub
System.out.println("The name of the testcase failed is :"+result.getName());
}

public void onTestSkipped(ITestResult result) {


// TODO Auto-generated method stub
System.out.println("The name of the testcase Skipped is :"+result.getName());
}

public void onTestStart(ITestResult result) {


// TODO Auto-generated method stub
System.out.println(result.getName()+" test case started");
}

public void onTestSuccess(ITestResult result) {


// TODO Auto-generated method stub
System.out.println("The name of the testcase passed is :"+result.getName());
}
}

Step 2) Create another class "TestCases" for the login process automation. Selenium will execute this 'TestCases' to login
automatically.

package testng;

import java.io.IOException;
import org.openqa.selenium. By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.testng.Assert;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;

public class ListenerTestCase


{
public static WebDriver driver;

121 | P a g e
@BeforeTest
public void getDriver()
{

System.setProperty("webdriver.chrome.driver","src/test/resources/driver/chromedriver.exe");
ChromeOptions options = new ChromeOptions();
options.addArguments("disable-infobars");
driver = new ChromeDriver(options);
driver.manage().window().maximize();
}

@Test
public void searchTest() throws IOException
{
System.out.println("Test Case Started!!!");
driver.get("https://www.google.com/");
WebElement searchTextBox = driver.findElement(By.name("q"));
searchTextBox.sendKeys("Selenium");
}

// Forcefully failed this test as to verify listener.


@Test
public void TestToFail()
{
System.out.println("This method to test fail");
Assert.assertTrue(false);
}
}

Step 3) Implement this listener in our regular project class i.e. "TestCase". There are two different ways to connect to the class
and interface.

The first way is to use Listeners annotation (@Listeners) as shown below:

@Listeners(Package_Name.Interface_ClassName.class)

@Listeners(testng.ListenerDemo.class)

122 | P a g e
Output:

123 | P a g e
Use of Listener for multiple classes.

If project has multiple classes adding Listeners to each one of them could be cumbersome and error prone. In such cases, we can
create a testng.xml and add listeners tag in XML.

<?xml version="1.0" encoding="UTF-8"?>


<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="Suite">
<listeners>
<listerner class-name="testng.ListenerDemo" />
</listeners>
<test thread-count="5" name="Parameterization Test Example">
<classes>
<class name="testng.ParameterizedTest" />
</classes>
</test>
</suite>

This listener is implemented throughout the test suite irrespective of the number of classes we have. When we run this XML file,
listeners will work on all classes mentioned. We can also declare any number of listener class.

DATA DRIVEN USING DIFFERENT FILE FORMATS

READ AND WRITE DATA FROM EXCEL FILE USING APACHE POI
File IO is a critical part of any software process. We frequently create a file, open it & update something or delete it in our
Computers. Same is the case with Selenium Automation. We need a process to manipulate files with Selenium.

Java provides us different classes for File Manipulation with Selenium, we are going to learn how can we read and write on Excel
file with the help of Java IO package and Apache POI library.

124 | P a g e
Classes and Interfaces in POI:

If we are using Maven in our project, the Maven dependency will be

We need a way to open the Excel sheet and read data from it within our Selenium test script. For this, we use the Apache POI
library, which allows us to read, create and edit Microsoft Office-documents using Java.

Download JAR files of Apache POI and Add Jars to our project library. That’s all about configuration of Apache POI with eclipse. If
we are using maven project, then add apache poi dependency in our pom.xml file.

package datahandling;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

125 | P a g e
import org.testng.annotations.Test;

public class ExcelUtil


{
XSSFWorkbook workbook;
Sheet sheet;

@Test
public void readExcel() throws IOException
{
File file = new File("src/test/resources/testdata/searchDetails.xlsx");
FileInputStream finput = new FileInputStream(file);

// Create Object of Workbook


workbook = new XSSFWorkbook(finput);

// Load Sheet
sheet = workbook.getSheet("Search");

//Find number of rows in excel file


int rowCount = sheet.getLastRowNum()-sheet.getFirstRowNum();

//Create a loop over all the rows of excel file to read it


for (int i = 0; i < rowCount+1; i++)
{
Row row = sheet.getRow(i);

//Create a loop to print cell values in a row


for (int j = 0; j < row.getLastCellNum(); j++)
{
//Print Excel data in console
System.out.print(row.getCell(j).getStringCellValue());
}
System.out.println();
}
}

@Test
public void writeExcel() throws IOException
{
File file = new File("src/test/resources/testdata/searchDetails.xlsx");
FileInputStream finput = new FileInputStream(file);
workbook = new XSSFWorkbook(finput);
sheet = workbook.getSheet("Search");

126 | P a g e
int rowCount = sheet.getLastRowNum()-sheet.getFirstRowNum();
for (int i = 0; i < rowCount+1; i++)
{
Row row = sheet.getRow(i);

//Create a loop to print cell values in a row


for (int j = 0; j < row.getLastCellNum(); j++)
{
//Fill Excel data
Cell cell = sheet.getRow(j).createCell(1);
cell.setCellValue("Passed");
}
}

FileOutputStream fout = new FileOutputStream(file);


workbook.write(fout);
workbook.close();
}
}

ExcelSheet:

Output:

127 | P a g e
PASSING DATA TO DATAPROVIDER FROM EXCEL SHEET
We can use an Excel sheet as a source of input. We can access data from excel sheet using DataProvider annotation and pass
arguments through @Test methods. Mainly this approach is used in Data Driven Framework.

128 | P a g e
To create the Excel DataProvider we will create below three class files

1. ExcelUtility Class – This is the utility class in which we will create all the generic methods of the excel like row count,
column count, read and write excel methods. Why we are creating this file because we want to separate all the
generic methods at one place.
2. ExcelToDataProvider Class – In this data provider class we will create the data provider method through which we will
drive the excel data into our test cases.
3. XLTest Class – This is the test class in which we are using the data provider.

ExcelUtility Class Code:

package datahandling;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.DateUtil;
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 ExcelUtility


{
public FileInputStream fis = null;

129 | P a g e
public FileOutputStream fos = null;
public XSSFWorkbook workbook = null;
public XSSFSheet sheet = null;
public XSSFRow row = null;
public XSSFCell cell = null;
String xlFilePath;

public ExcelUtility(String xlFilePath) throws IOException


{
this.xlFilePath = xlFilePath;
fis = new FileInputStream(xlFilePath);
workbook = new XSSFWorkbook(fis);
fis.close();
}

// Method Read Data from Excel using Col Number


public String getCellData(String sheetName, int colNum, int rowNum)
{
try
{
sheet = workbook.getSheet(sheetName);
row = sheet.getRow(rowNum);
cell = row.getCell(colNum);

if(cell.getCellType() == CellType.STRING)
return cell.getStringCellValue();
else if(cell.getCellType() == CellType.NUMERIC || cell.getCellType() ==
CellType.FORMULA)
{
String cellValue = String.valueOf(cell.getNumericCellValue());
if(DateUtil.isCellDateFormatted(cell))
{
DateFormat dt = new SimpleDateFormat("dd/MM/yyyy");
Date date = cell.getDateCellValue();
cellValue = dt.format(date);
}
return cellValue;
}
else if(cell.getCellType() == CellType.BLANK)
return "";
else
return String.valueOf(cell.getBooleanCellValue());
}
catch(Exception e)

130 | P a g e
{
e.printStackTrace();
return "row "+rowNum+" or column "+colNum+" does not exist in excel sheet";
}
}

// Method Read Data from Excel using Col Name


public String getCellData(String sheetName, String colName, int rowNum)
{
try
{
int colNum = -1;
sheet = workbook.getSheet(sheetName);
row = sheet.getRow(0);

for(int i=0;i<row.getLastCellNum();i++)
{
if(row.getCell(i).getStringCellValue().trim().equals(colName))
colNum = i;
}

//row = sheet.getRow(rowNum-1);
row = sheet.getRow(rowNum);
cell = row.getCell(colNum);

if(cell.getCellType() == CellType.STRING)
return cell.getStringCellValue();
else if(cell.getCellType() == CellType.NUMERIC || cell.getCellType() ==
CellType.FORMULA)
{
String cellValue = String.valueOf(cell.getNumericCellValue());
if(DateUtil.isCellDateFormatted(cell))
{
DateFormat dt = new SimpleDateFormat("dd/MM/yyyy");
Date date = cell.getDateCellValue();
cellValue = dt.format(date);
}
return cellValue;
}
else if(cell.getCellType() == CellType.BLANK)
return "";
else
return String.valueOf(cell.getBooleanCellValue());
}

131 | P a g e
catch(Exception e)
{
e.printStackTrace();
return "row "+rowNum+" or column "+colName+" does not exist in excel
sheet";
}

//return cell.getStringCellValue();
}

// Method Write Data into Excel using Col Number


public boolean setCellData(String sheetName, int colNum, int rowNum, String value)
{
try
{
sheet = workbook.getSheet(sheetName);
row = sheet.getRow(rowNum);

if(row==null)
row = sheet.createRow(rowNum);

cell = row.getCell(colNum);

if(cell==null)
cell = row.createCell(colNum);

cell.setCellValue(value);

fos = new FileOutputStream(xlFilePath);


workbook.write(fos);
fos.close();
}
catch(Exception e)
{
e.printStackTrace();
return false;
}

return true;
}

// Method to Write Data into Excel using Col Name


public boolean setCellData(String sheetName, String colName, int rowNum, String value)
{

132 | P a g e
try
{
int colNum = -1;
sheet = workbook.getSheet(sheetName);
row = sheet.getRow(0);

for(int i=0; i<row.getLastCellNum();i++)


{
if(row.getCell(i).getStringCellValue().trim().equals(colName))
{
colNum = i;
}
}

//row = sheet.getRow(rowNum-1);
row = sheet.getRow(rowNum);

if(row==null)
//row = sheet.createRow(rowNum-1);
row = sheet.createRow(rowNum);
cell = row.getCell(colNum);

if(cell==null)
cell = row.createCell(colNum);

cell.setCellValue(value);

fos = new FileOutputStream(xlFilePath);


workbook.write(fos);
fos.close();
}
catch(Exception e)
{
e.printStackTrace();
return false;
}

return true;
}

// Method to get Row Count


public int getRowCount(String sheetName)
{
sheet = workbook.getSheet(sheetName);
133 | P a g e
int rowCount = sheet.getLastRowNum()+1;
return rowCount;
}

// Method to get Column Count


public int getColCount(String sheetName)
{
sheet = workbook.getSheet(sheetName);
row = sheet.getRow(0);
int colCount = row.getLastCellNum();
return colCount;
}
}

ExcelToDataProvider Class Code:

package datahandling;

import java.io.IOException;
import org.testng.annotations.DataProvider;

public class ExcelToDataProvider


{
public static ExcelUtility objExcelUtility = null;
public static String xlFilePath = "src/test/resources/testdata/searchDetails.xlsx";
public static String sheetName = "Search";

@DataProvider(name="getData")
public static Object[][] getData() throws IOException
{
Object[][] data = testData(xlFilePath,sheetName);
return data;
}

public static Object[][] testData(String xlFilePath, String sheetName) throws


IOException
{
Object [][] excelData = null;
objExcelUtility = new ExcelUtility(xlFilePath);

// Get Rows and Columns


int rows = objExcelUtility.getRowCount(sheetName);

134 | P a g e
int columns = objExcelUtility.getColCount(sheetName);

excelData = new Object[rows-1][columns];

// Loop for Rows


for(int i=1;i<rows;i++)
{
// Loop for Columns
for(int j=0;j<columns;j++)
{
excelData[i-1][j] = objExcelUtility.getCellData(sheetName, j, i);
}
}

return excelData;
}
}

XLTest Class Code:

package datahandling;

import java.io.IOException;
import org.testng.annotations.Test;

public class XLTest


{
@Test (dataProvider = "getData", dataProviderClass = ExcelToDataProvider.class)
public void ReadXLData(String searchData, String Results) throws IOException
{
System.out.println("SearchData is : "+searchData);
System.out.println("Results is : "+Results);
System.out.println("***************************");
}
}
Excel Sheet:

Output:
135 | P a g e
READ DATA TO DATAPROVIDER FROM JSON FILE
We can use an JSON file as a source of input. Because we have scenarios in our project in which we will utilize the API Response
data directly to our test case scripts. Mostly API Response are in the JSON format.

Hence we JSON Dataprovider will play an important role in data driven frameworks.

We are adding the below maven dependency to configuration the eclipse.

To create the JSON DataProvider we will create below two files:

1. JsonUtility Class: This is the JSON utility class in which we will create the read and search data methods.
2. JsonToDataProvider Class: In this class we will create the Data provider which we used in our test class.
3. TestCase Class – This is the test class in which we are using the data provider.

JsonUtility Class Code:

package datahandling;

import java.io.FileNotFoundException;

136 | P a g e
import java.io.FileReader;
import java.util.Map;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonIOException;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.JsonSyntaxException;

public class JsonUtility


{
public static int totalCol;
public static int totalRow;
public static JsonElement noOfElement;
public static JsonObject colName;

// Method to get the data from the JSON File


public static Object[][] getData(String jsonFilePath, String jsonNode) throws
JsonIOException, JsonSyntaxException, FileNotFoundException
{
JsonObject jsonObj = JsonParser.parseReader(new
FileReader(jsonFilePath)).getAsJsonObject();
JsonArray jsonArray = (JsonArray) jsonObj.get(jsonNode);
totalRow = jsonArray.size();

for(int i=0;i<totalRow;i++)
{
colName = (JsonObject)(jsonArray.get(i));
}

totalCol = colName.entrySet().size();
System.out.println("Row Count : "+totalRow+" and Col Count : "+totalCol);

return searchJsonElement(jsonArray,totalRow,totalCol);
}

// Method to search the data from JSON File


public static Object[][] searchJsonElement(JsonArray jsonArray, int totalDataRow, int
totalColEntry) throws NullPointerException
{
Object[][] jsonData = new Object[totalDataRow][totalColEntry];
int i=0;
int j=0;

for(JsonElement jsonElement : jsonArray)


137 | P a g e
{
for(Map.Entry<String, JsonElement> elements :
jsonElement.getAsJsonObject().entrySet())
{
jsonData[i][j] = elements.getValue().toString().replace("\"", "");
j++;
}
i++;
j=0;
}
return jsonData;
}
}

JsonToDataProvider Class Code:

package datahandling;

import java.io.FileNotFoundException;
import java.lang.reflect.Method;
import org.testng.annotations.DataProvider;
import com.google.gson.JsonIOException;
import com.google.gson.JsonSyntaxException;

public class JsonToDataProvider


{
@DataProvider(name="searchDataProvider")
public static Object[][] searchDataProvider(Method testMethod) throws JsonIOException,
JsonSyntaxException, FileNotFoundException
{
return JsonUtility.getData("src/test/resources/testdata/searchData.json",
"SearchData");
}
}

TestCase Class Code:

package datahandling;

import java.io.IOException;
import org.testng.annotations.Test;

public class TestCase


{
@Test (dataProvider = "searchDataProvider", dataProviderClass =
JsonToDataProvider.class)

138 | P a g e
public void ReadJsonData(String searchData) throws IOException
{
System.out.println("Json Data Source");
System.out.println("SearchData is : "+searchData);
System.out.println("***************************");
}
}

JSON File:

Output:

READ DATA FROM PROPERTIES FILE

139 | P a g e
It is not the good practice to hard coded the data values in the framework so, with the help of properties file we will be
eliminating these hard coded values.

What is a Property file in Java?

The .properties files are mainly used in Java programs to maintain project configuration data, database config or project settings
etc. Each parameter in properties file are stored as a pair of strings, in key-value pair format, where each key is on one line. We
can easily read properties from some file using object of type Properties. This is a utility provided by Java itself.

Advantages of Property file in Java

If any information is changed from the properties file, we don’t need to recompile the java class. In other words, the advantage
of using properties file is we can configure things which are prone to change over a period of time without need of changing
anything in code.

For E.g. We keep application Url in property file, so in case we want to run test from on other test environment, just change the
Url in property file and that’s it. we do not require to build the whole project again.

Steps to read configuration from property file

1. Create a Property File


 Create a New Folder and name it as config, by right click on the root Project and select New >> Folder. We will
be keeping all the config files with in the same folder.
 And after that Create a New File by right click on the above created folder and select New >> File.
 The only thing we need to do is to give the file name and give the extension as .properties. In our case we
name it as configuation.properties.

2. Write Hard Coded Values in the Property File. Below is the properties file that we will use

3. Create a Config File Reader


 Create a New Package and name it as reader, by right click on the src/test/java and select New >> Package.
 Create a New Class file and name it as ConfigReader.java, by right click on the above created package and
select New >> Class.

ConfigReader Class Code:

package reader;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

140 | P a g e
import java.util.Properties;

public class ConfigReader


{
private Properties properties;
private final String propertyFilePath =
"src/test/resources/config/Configuration.properties";

public ConfigReader()
{
BufferedReader reader;
try
{
reader = new BufferedReader(new
FileReader(propertyFilePath));
properties = new Properties();
try
{
properties.load(reader);
reader.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
catch (FileNotFoundException e)
{
e.printStackTrace();
throw new RuntimeException("Configuration.properties not
found at " + propertyFilePath);
}
}

public String getDriverProperty()


{
String driverProperty = properties.getProperty("WebDriverProperty");
if (driverProperty != null)
return driverProperty;
else
throw new RuntimeException("WebDriverProperty not specified in
the Configuration.properties file.");
}

public String getDriverPath()

141 | P a g e
{
String driverPath = properties.getProperty("WebDriverLocation");
if (driverPath != null)
return driverPath;
else
throw new RuntimeException("WebDriverLocation not specified in
the Configuration.properties file.");
}

public String getAppUrl()


{
String appUrl = properties.getProperty("AppURL");
if (appUrl != null)
return appUrl;
else
throw new RuntimeException("AppURL not specified in the
Configuration.properties file.");
}

4. Use ConfigReader object in the test class file


 To use the ConfigFileReader object in the test, we need to fist create an object of the class.

// Create Object of ConfigReader


public ConfigReader reader = new ConfigReader();

Then we can replace the below statement


System.setProperty("webdriver.chrome.driver","src/test/resources/driver/chromedriv
er.exe");

With
System.setProperty(reader.getDriverProperty(),reader.getDriverPath());

Test Class Code:

public class ConfigEx


{
public static WebDriver driver;

// Create Object of ConfigReader


public ConfigReader reader = new ConfigReader();

@BeforeTest
public void getDriver()
{
// Call Properties from Configuration File

142 | P a g e
System.setProperty(reader.getDriverProperty(),reader.getDriverPath());
ChromeOptions options = new ChromeOptions();
options.addArguments("disable-infobars");
driver = new ChromeDriver(options);
driver.manage().window().maximize();
}

@Test
public void searchTest() throws IOException
{
driver.get(reader.getAppUrl());
WebElement searchTextBox = driver.findElement(By.name("q"));
searchTextBox.sendKeys("Selenium");
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
}
}

DATABASE CONNECTION USING JDBC

CONVERTING JDBC RESULTS INTO JAVA OBJECT WITH POJO CLASSES


 Create Mock Tables in Database: I have created the mock table in the MySQL in MYSQL Workbench

 Connect to Database through Java Code and retrieve records from table
o First create the Maven Project in Eclipse and add the below relevant Jars files in the pom.xml file.
https://mvnrepository.com/artifact/mysql/mysql-connector-java/8.0.16

143 | P a g e
o Now create class “JsonToJava” which is used to connect the Database. We are calling the class which is loading
dynamically at the run time of the class and talk with database and this class is present in the maven
dependency which we used above.

Class.forName("com.mysql.cj.jdbc.Driver");

o Now import “DriverManager” which is used to get the connection String of the database.

conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/Business",
"root123", "root@123");
o To execute any query first, we must create the object of the “Statement” class. Object of Statement class will
help us to execute queries.

Statement stmt = conn.createStatement();

o To store the query result we create the object of the “ResultSet” class. The Object is treated as an array and
store all the values from the database.

Statement stmt = conn.createStatement();


result=stmt.executeQuery("Select * from CustomerInfo where
PurchasedDate=current_date() and Location='Asia'");

o To traversed in between rows will use “next()” method. It is just like a pointer to particular row that how many
times the rows will traversed. But if there are around 100 records then this approach is not feasible. To do so
we can use “While loop”.
result.next();
while (rs.next()) {
System.out.println(rs.getString(1));
System.out.println(rs.getString(2));
System.out.println(rs.getInt(3));
System.out.println(rs.getString(4));
}

JsonToJava Class Code:

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class JsonToJava {

public static void main(String[] args) throws ClassNotFoundException, SQLException


{
Class.forName("com.mysql.cj.jdbc.Driver");
Connection conn = null;
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/Business",
"root123", "root@123");

144 | P a g e
//object of statement class will help us to execute queries
Statement st = conn.createStatement();
ResultSet rs = st.executeQuery("select * from CustomerInfo where location =
'Asia' and purchasedDate = curdate()");

while (rs.next())
{
System.out.println(rs.getString(1));
System.out.println(rs.getString(2));
System.out.println(rs.getInt(3));
System.out.println(rs.getString(4));
}
conn.close();
}
}

 Convert results of Table into Java object with the help of POJO class implementation
o To convert the tables into Java Object in POJO first we need to create a class and define all the columns which
is defined in the database table and create the getter and setter methods in the class.

public class CustomerDetails


{
private String CourseName;
private String PurchasedDate;
private int Amount;
private String Location;

public String getCourseName()


{
return CourseName;
}

public void setCourseName(String courseName)


{
CourseName = courseName;
}

public String getPurchasedDate()


{
return PurchasedDate;
}

145 | P a g e
public void setPurchasedDate(String purchasedDate)
{
PurchasedDate = purchasedDate;
}

public int getAmount()


{
return Amount;
}

public void setAmount(int amount)


{
Amount = amount;
}

public String getLocation()


{
return Location;
}

public void setLocation(String location)


{
Location = location;
}
}

JACKSON API TO CONVERT JAVA OBJECTS INTO JSON FILE FORMATS


 Convert Java Objects into JSON files using Jackson API
o First add Jackson API dependency in pom.xml
https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-core/2.9.9
o After this add Jackson Databind dependency in pom.xml
https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind/2.9.9
o Add one more dependency i.e. Jackson Annotations
https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-annotations/2.9.9
 Now create an instance of “ObjectMapper” class of Jackson API and call the “writeValue” method of the class.

ObjectMapper objMap = new ObjectMapper();


objMap.writeValue(new File("C:\\Users\\Armaan Khandelwal\\eclipse-
workspace\\mysqldbtest\\CustomerInfo.json"), custDetails);

 The “writeValue” method contains two parameters one is the File Path or location where we want to save our
converted JSON file and second parameter is the instance of the Java Object class or we say the getter and setter class
instance.

CustomerDetails custDetails = new CustomerDetails();

146 | P a g e
 Create object of ArrayList in “JsonToJava” class to fetch the list of results.

ArrayList <CustomerDetails> list = new ArrayList<CustomerDetails>();

for(int i=0;i<list.size();i++)
{
//Creating the Object of Jackson Class - ObjectMapper
ObjectMapper objMap = new ObjectMapper();
objMap.writeValue(new File("C:\\Users\\Armaan
Khandelwal\\eclipse-workspace\\mysqldbtest\\CustomerInfo_"+i+".json"),
list.get(i));
}
JsonToJava Class Code:

public class JsonToJava


{
public static void main(String[] args) throws ClassNotFoundException,
SQLException, JsonGenerationException, JsonMappingException, IOException
{

//ArrayList Object for Multiple Results


ArrayList <CustomerDetails> list = new ArrayList<CustomerDetails>();

//Load the MySQL driver


Class.forName("com.mysql.cj.jdbc.Driver");

//Creating Connection
Connection conn = null;
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/Business",
"root123", "root@123");

//object of statement class will help us to execute queries


Statement st = conn.createStatement();
ResultSet rs = st.executeQuery("Select * from CustomerInfo where
Location='Asia' and PurchasedDate=current_date();");

//Iterate the Table of Database


while (rs.next())
{
//Create instance for Json Object Class
CustomerDetails custDetails = new CustomerDetails();
custDetails.setCourseName(rs.getString(1));
custDetails.setPurchasedDate(rs.getString(2));
custDetails.setAmount(rs.getInt(3));
custDetails.setLocation(rs.getString(4));

147 | P a g e
list.add(custDetails);
}

for(int i=0;i<list.size();i++)
{
//Creating the Object of Jackson Class - ObjectMapper
ObjectMapper objMap = new ObjectMapper();
objMap.writeValue(new File("C:\\Users\\Armaan Khandelwal\\eclipse-
workspace\\mysqldbtest\\CustomerInfo_"+i+".json"), list.get(i));
}

//Close the connection


conn.close();
}
}

PARSE JSON FILE INTO JAVA OBJECT TO SEND THE DATA THROUGH GETTER METHODS
Earlier we are converting the String Files into JSON, but now we are parsing the JSON File into Java Objects using getter setter or
we say POJO class.

The parsing of JSON File to Java Object will help us when we compare the response from API with Front end in Selenium i.e. the
API response is JSON

import java.io.File;
import java.io.IOException;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;

public class ExtractCourseName


{
public static void main(String[] args) throws JsonParseException, JsonMappingException,
IOException
{
ObjectMapper objMap=new ObjectMapper();
CustomerDetails custDetails = objMap.readValue(new File("C:\\Users\\Armaan
Khandelwal\\eclipse-workspace\\mysqldbtest\\CustomerInfo_1.json"),
CustomerDetails.class);

System.out.println(custDetails.getCourseName());
}

REPORTS GENERATION WITH EXTENT REPORT AND TESTNG

148 | P a g e
Selenium provides inbuilt reports using frameworks such as JUnit and TestNG. Although the built-in reports provide information
on the steps that are executed as part of the test case, they need more customization to be shared with all the major project
stakeholders.

Hence Reporting is the most important part of the framework through we can see our test cases results i.e. passed, failed or
skipped. So in Selenium we have different custom API through which we can generate the reports using TestNG testing
framework.

Extent Reports is a customizable HTML report which can be integrated into Selenium WebDriver using JUnit and TestNG
frameworks.

Extent API can produce more interactive reports, a dashboard view, graphical view, capture screenshots at every test step, and
email able reports

If we have maven Project, then add the below dependency to pom.xml

To generate the Extent HTML report we will create ExtentBaseTest Class this is the base class in which we will create all the
generic methods of the extent report like setup extent report, screen shot get result methods.

ExtentBaseTest Class Code:

package reportgeneration;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.testng.ITestResult;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.AfterSuite;
import org.testng.annotations.BeforeSuite;
import com.aventstack.extentreports.ExtentReports;
import com.aventstack.extentreports.ExtentTest;
import com.aventstack.extentreports.Status;
import com.aventstack.extentreports.markuputils.ExtentColor;
import com.aventstack.extentreports.markuputils.MarkupHelper;
import com.aventstack.extentreports.reporter.ExtentHtmlReporter;
import com.aventstack.extentreports.reporter.configuration.Theme;

149 | P a g e
public class ExtentBaseTest
{
public static ExtentHtmlReporter htmlReporter;
public static ExtentReports extent;
public static ExtentTest test;
public static WebDriver driver;

@BeforeSuite
public void setUpExtentReport()
{
htmlReporter = new ExtentHtmlReporter(System.getProperty("user.dir")+"/test-
output/myExtentReport.html");
extent = new ExtentReports();
extent.attachReporter(htmlReporter);

extent.setSystemInfo("OS", "Windows 10");


extent.setSystemInfo("Host Name", "LocalHost");
extent.setSystemInfo("Environment", "Dev QA");
extent.setSystemInfo("User Name", "Arman Khandelwal");

htmlReporter.config().setDocumentTitle("AutomationReport");
htmlReporter.config().setReportName("Automation Report");
htmlReporter.config().setTheme(Theme.DARK);
}

// ScreenShot Method
public static String getScreenShot(WebDriver driver, String screenShotName) throws
IOException
{
String dateName = new SimpleDateFormat("yyyyMMddhhmmss").format(new Date());
TakesScreenshot scrShot = (TakesScreenshot) driver;
File source = scrShot.getScreenshotAs(OutputType.FILE);
String scrShotFilePath = System.getProperty("user.dir") + "/Screenshots" +
screenShotName + dateName + ".png";
File destination = new File(scrShotFilePath);
FileUtils.copyFile(source, destination);
return scrShotFilePath;
}

@AfterMethod
public void getResult(ITestResult result) throws IOException
{
if(result.getStatus() == ITestResult.FAILURE)
{
150 | P a g e
//test.log(Status.FAIL, "Test Case Failed is "+result.getName());
test.log(Status.FAIL, MarkupHelper.createLabel(result.getName()+" Test Case Failed
due to below issues", ExtentColor.RED));
test.log(Status.FAIL, "Test Case Failed is "+result.getThrowable());
String screenShotPath = getScreenShot(driver,result.getName());
test.addScreenCaptureFromPath(screenShotPath);
}

else if(result.getStatus() == ITestResult.SUCCESS)


{
//test.log(Status.PASS, "Test Case Passed is "+result.getName());
test.log(Status.PASS, MarkupHelper.createLabel(result.getName()+" Test Case
Passed", ExtentColor.GREEN));
String screenShotPath = getScreenShot(driver,result.getName());
test.addScreenCaptureFromPath(screenShotPath);
}

else
{
//test.log(Status.SKIP, "Test Case Skipped is "+result.getName());
test.log(Status.SKIP, MarkupHelper.createLabel(result.getName()+" Test Case
Skipped", ExtentColor.ORANGE));
test.log(Status.SKIP, "Test Case Skipped is "+result.getThrowable());
String screenShotPath = getScreenShot(driver,result.getName());
test.addScreenCaptureFromPath(screenShotPath);
}
}

@AfterSuite
public void endReport()
{
extent.flush();
}
}

First we have to extends the ExtentTestBase Class to TestCase Class so that we will inherit all the methods into Child or Sub
Class after that we will call the below method of Extent Report to add the steps in Extent report.

Please note we will the below in every test method to which we want to add into Extent Report.

test = extent.createTest("TestToFail");

TestCase Class Code:

public class TestCase extends ExtentBaseTest


{

151 | P a g e
// Create Object of ConfigReader
public ConfigReader reader = new ConfigReader();

@BeforeTest
public void getDriver()
{
// Call Properties from Configuration File
System.setProperty(reader.getDriverProperty(),reader.getDriverPath());
ChromeOptions options = new ChromeOptions();
options.addArguments("disable-infobars");
driver = new ChromeDriver(options);
driver.manage().window().maximize();
}

@Test
public void searchTest() throws IOException
{
// Call ExtentBaseTest test method
test = extent.createTest("SeleniumTest");
driver.get(reader.getAppUrl());
WebElement searchTextBox = driver.findElement(By.name("q"));
searchTextBox.sendKeys("Selenium");
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
}

@Test
public void TestToFail()
{
// Call ExtentBaseTest test method
test = extent.createTest("TestToFail");
System.out.println("This method to test fail");
Assert.assertTrue(false);
}

Extent HTML Report:

152 | P a g e
HEADLESS BROWSER TESTING USING HTMLUNITDRIVER

A headless browser is a web-browser without a graphical user interface. This program will behave just like a browser but will not
show any GUI.

Some of the examples of Headless Drivers include

 HtmlUnit
 Ghost
 PhantomJS
 ZombieJS
 Watir-webdriver

HTML UnitDriver is the most light weight and fastest implementation headless browser for of WebDriver. It is based on
HtmlUnit. It is known as Headless Browser Driver. It is same as Chrome, IE, or Firefox driver, but it does not have GUI so one
cannot see the test execution on screen.

package testng;

import java.io.IOException;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.htmlunit.HtmlUnitDriver;
import org.testng.annotations.Test;
import reader.ConfigReader;

public class TestCase


{
public static ConfigReader reader = new ConfigReader();

153 | P a g e
@Test(description="Search Test Case")
public void searchTest() throws IOException
{
// Calling Headless Browser
WebDriver driver = new HtmlUnitDriver();
driver.get("https://www.google.com/");
System.out.println("Page Title is :"+driver.getTitle());
WebElement searchTextBox = driver.findElement(By.name("q"));
searchTextBox.sendKeys("Selenium");
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
}
}

CROSS BROWSER TESTING WITH SELENIUM GRID

INTRODUCTION TO GRID
Selenium Grid is a part of the Selenium Suite that specializes in running multiple tests across different browsers, operating
systems, and machines in parallel.

Selenium Grid has 2 versions - the older Grid 1 and the newer Grid 2. We will only focus on Grid 2 because Grid 1 is gradually
being deprecated by the Selenium Team.

Selenium Grid uses a hub-node concept where we only run the test on a single machine called a hub, but the execution will be
done by different machines called nodes.

When to Use Selenium Grid?

We should use Selenium Grid when we want to do either one or both of following:

 Run our tests against different browsers, operating systems, and machines all at the same time. This will ensure that
the application we are testing is fully compatible with a wide range of browser OS combinations.

154 | P a g e
 Save time in the execution of our test suites. If we set up Selenium Grid to run, say, 4 tests at a time, then we would be
able to finish the whole suite around 4 times faster.

SELENIUM GRID ARCHITECTURE


Selenium Grid has a Hub and Node Architecture.

The Hub
 The hub is the central point where we load our tests into.
 There should only be one hub in a grid.
 The hub is launched only on a single machine, say, a computer whose O.S is Windows 7 and whose browser is IE.
 The machine containing the hub is where the tests will be run, but we will see the browser being automated on the
node.

The Nodes
 Nodes are the Selenium instances that will execute the tests that we loaded on the hub.
 There can be one or more nodes in a grid.
 Nodes can be launched on multiple machines with different platforms and browsers.
 The machines running the nodes need not be the same platform as that of the hub.

Selenium grid can be set up in two different ways; one through command line and the other through JSON config file.

HOW TO SET UP SELENIUM GRID? USING COMMAND LINE


In this section, we will use 2 machines. The first machine will be the system that will run the hub while the other machine will
run a node. For simplicity, let us call the machine where the hub runs as "Machine A" while the machine where the node runs
will be "Machine B." It is also important to note their IP addresses. Let us say that Machine A has an IP address of 192.168.1.3
while Machine B has an IP of 192.168.1.4.

Step 1

 Download the Selenium Server from official website.

Step 2

 We can place the Selenium Server .jar file anywhere in our Hard Drive. But for the purpose of this tutorial, place it on
the C drive of both Machine A and Machine B. After doing this, we are now done installing Selenium Grid. The following
steps will launch the hub and the node.

Step 3

155 | P a g e
 We are now going to launch a hub. Go to Machine A. Using the command prompt, navigate to the root of Machine A's -
C drive, because that is the directory where we placed the Selenium Server.
 On the command prompt, type java -jar selenium-server-standalone-2.30.0.jar -role hub
 The hub should successfully be launched. Our command prompt should look similar to the image below

Step 4

 Another way to verify whether the hub is running is by using a browser. Selenium Grid, by default, uses Machine A's
port 4444 for its web interface. Simply open up a browser and go to http://localhost:4444/grid/console

 Also, we can check if Machine B can access the hub's web interface by launching a browser there and going to where
"iporhostnameofmachineA" should be the IP address or the hostname of the machine where the hub is running. Since
Machine A's IP address is 192.168.1.3, then on the browser on Machine B we should type
http://192.168.1.3:4444/grid/console

Step 5

 Now that the hub is already set up, we are going to launch a node. Go to Machine B and launch a command prompt
there.
 Navigate to the root of Drive C and type the code below. We used the IP address 192.168.1.3 because that is where the
hub is running. We also used port 5566 though we may choose any free port number we desire.
 NOTE: We now have to give path to the Gecko driver if using Firefox. Here is updated code that needs to be used

java -Dwebdriver.gecko.driver="C:\geckodriver.exe" -jar selenium-server-standalone-


3.4.0.jar -role webdriver -hub http://192.168.1.3:4444/grid/register -port 5566

156 | P a g e
Step 6

 Go to the Selenium Grid web interface and refresh the page. We should see something like this.

 At this point, we have already configured a simple grid. We are now ready to run a test remotely on Machine B.

DESIGNING TEST SCRIPTS THAT CAN RUN ON THE GRID


To design test scripts that will run on the grid, we need to use DesiredCapabilites and the RemoteWebDriver objects.

 DesiredCapabilites is used to set the type of browser and OS that we will automate
 RemoteWebDriver is used to set which node (or machine) that our test will run against.

To use the DesiredCapabilites object, you must first import this package

To use the RemoteWebDriver object, you must import these packages.

Using the DesiredCapabilites Object

Go to the Grid's web interface and hover on an image of the browser that you want to automate. Take note of the platform, and
the browserName showed by the tooltip.

157 | P a g e
In this case, the platform is "XP" and the browserName is "Firefox."

We will use the platform and the browserName in our WebDriver as shown below (of course you need to import the necessary
packages first).

Using the RemoteWebDriver Object

Import the necessary packages for RemoteWebDriver and then pass the DesiredCapabilities object that we created above as a
parameter for the RemoteWebDriver object.

Running a Sample Test Case on the Grid

Below is a simple WebDriver TestNG code that we can create in Eclipse on Machine A. Once we run it, automation will be
performed on Machine B.

158 | P a g e
INTEGRATION OF JENKINS WITH SELENIUM

What is Jenkins?

Jenkins is the leading open-source continuous integration tool developed by Hudson lab. It is cross-platform and can be used on
Windows, Linux, Mac OS and Solaris environments. Jenkins supports many plugins which we can integrate such as Git, SVN, build
pipeline and many more. It fires pre-configured actions when a particular step occurs in jobs.

Important Features of Jenkins

 Change Support: Jenkins generates the list of all changes done in repositories like SVN.
 Permanent links: Jenkins provides direct links to the latest build or failed build that can be used for easy
communication
 Installation: Jenkins is easy to install either using direct installation file (exe) or war file to deploy using application
server.
 Email integration: Jenkins can be configured to email the content of the status of the build.
 Easy Configuration: To configure various tasks on Jenkins is easy.
 TestNG test: Jenkins can be configured to run the automation test build on TestNG after each build of SVN.
 Multiple VMs: Jenkins can be configured to distribute the build on multiple machines.
 Project build: Jenkins documents the details of jar, version of jar and mapping of build and jar numbers.
 Plugins: 3rd party plugin can be configured in Jenkins to use features and additional functionality.

Why Jenkins and Selenium?

159 | P a g e
 Running Selenium tests in Jenkins allows us to run our tests every time our software changes and deploy the software
to a new environment when the tests pass.
 Jenkins can schedule our tests to run at specific time.
 We can save the execution history and Test Reports.
 Jenkins supports Maven for building and testing a project in continuous integration.

Jenkins usage and integration with selenium

FILE UPLOADING USING AUTOIT

Why we Selenium need third party tools i.e. AutoIT

Web applications do not always confine themselves to working entirely on the web. Sometimes they need to interact with the
desktop to do things like downloads & uploads. Automating these sorts of workflow is tricky in Selenium. Selenium is confined to
automating browsers, so desktop windows are out of scope. If we are looking to automate workflows that go from browser to
desktop and back in Selenium, then a little AutoIt is in order.

WHAT IS AUTOIT
AutoIt v3 is a freeware BASIC-like scripting language designed for automating the Windows GUI and general scripting. It uses a
combination of simulated keystrokes, mouse movement and window/control manipulation in order to automate tasks in a way
not possible or reliable with other languages (e.g. VBScript and SendKeys). AutoIt is also very small, self-contained and will run
on all versions of Windows out-of-the-box with no annoying “runtimes” required!

In layman’s term AutoIt is just another automation tool like Selenium but unlike Selenium it is used for Desktop Automation
Rather Web Automation. It is a powerful tool and it just not automate desktop windows, button & form, it automates mouse
movements & keystrokes too. Just like Selenium IDE, it also gives us the recording capability which generates the scripts for us to
use the same script in our test.

Steps to Download AutoIt v3

1. Go to AutoIt website and navigate to download page https://www.autoitscript.com/site/autoit/downloads/. It will


display the latest version. The top most download is for AutoIt, click on it.

160 | P a g e
2. Once the download is complete, double click on the .exe file and it will ask us for Installation. Click on Next button.

3. Complete the process and click on the Finish button at the end of the installation.

161 | P a g e
RECORDING OF AUTOIT SCRIPT
AutoIt also have recording feature which helps in generating scripts automatically. But for that we need to use its extension
called AutoIt Script Editor. Although script editor is also get installed with AutoIt but it comes with very limited feature.

Steps to Download AutoIt Script Editor

1. Go to AutoIt website and navigate to download page https://www.autoitscript.com/site/autoit/downloads/. It will


display the latest version. The second download is for AutoIt Script Editor, click on it.

2. A new page will open, click on the top most link of “SciTE4AutoIt3.exe” and follow the process until the installation is
finished.

UPLOAD FILE IN SELENIUM USING AUTOIT


Uploading of file is a four steps process:

 Step 1: Identify the Windows control


 Step 2: Build a AutoIt script using identified windows control
 Step 3: Compile the .au3 script and convert it in to .exe file
 Step 4: Call the .exe file in to the Selenium test case

Step 1: Identify the Windows control

 Navigate to page on which we have a file upload feature.


 Click on “Browse” of “Choose File” any button which is used to upload the file. It will open a Windows box for “File
Upload”
 Now go to our Start > All Program > AutoIt v3 and open “SciTE Script Editor”. It will open an editor window where we
write out automation script of AutoIt.

Before writing scripts we should know that what we need to write, as we are new with this tool and we even do not
know what language it follows and how the script looks like. To get the help for it, open “Help” from SciTE Script Editor.

Type “Commands” on the search text field of the Help. It will give all the commands we can use in your test.

162 | P a g e
Open few commands and check out the description, it explains the syntax, parameter & detailed description of each
method with a descriptive example.

It says that we need “title”, “text” and “ControlID” to use the ControlFocus method. To obtain these we need help to
identify windows object.

163 | P a g e
 Open the AutoIt Recording for this go to Start > All Program > AutoIt v3 and open. Go to 'C:\Program Files
(x86)\AutoIt3 ' and click on “Au3Info.exe” file, the element identifier opens as shown in below screen.

 Now drag the “Finder Tool” box to the object in which we are interested.

164 | P a g e
Step 2: Build an AutoIt script using identified windows control

 Take the information from the “Window Info” tool and fill in the ControlFocus method ControlFocus (“title”, “text”,
“controlID”).
 We can get the value of attributes i.e. title='Open', class='Edit' and instance='1' as shown below. These values are used
in writing AutoIT.
o 1st parameter title is "Open".
o We ignore 2nd parameter, the text is not required.
o 3rd parameter controlID is the combination of class='Edit' and Instance='1' i.e., “Edit1”

165 | P a g e
s
 To open up AutoIT Editor Go to “C:\Program Files (x86)\AutoIt3\SciTE”

 Click on “SciTE.exe” file, the AutoIT editor opens as shown in below screen.

 There are three methods available which we can use in a script according to the requirement, below are the methods
which is required for writing file upload script:

ControlFocus(" title "," text ",controlID ) //Sets input focus to a given control on a window.
ControlSetText(" title "," text ",controlID ," File path which need to upload " ) // Sets text of a control.
ControlClick(" title "," text ",controlID ) //Sends a mouse click command to a given control.

166 | P a g e
 We can see in the above AutoIT script is completed to handle file uploader. Now we can close the element identifier
and save the script as "FileUpload" with .au3 extension at any location.

Step 3: Compile the .au3 script and convert it in to .exe file

 We can't execute the AutoIT (.au) script directly, we need to compile this script. For this we have to convert it in to .exe
format. For that we need to right click on the .au3 file and select “Compile Script“
 For compiling this script, we have two options "compile script x64" and "compile script x86", if we have windows 32-bit
machine then we go with "compile script x86" and for windows 64-bit machine then we go with "compile script x64"

Step 4: Call the .exe file in to the Selenium test case

 Once we done with the compiling, it will create the ‘.exe’ file with the same name under the same folder and that ‘.exe’
file will be called in the Selenium Test Script by using the following script:

Runtime.getRuntime().exec("D:\AutoIt\AutoItTest.exe");

public class TestCase


{
public static WebDriver driver;
public static ConfigReader reader = new ConfigReader();

@Test(description="Search Test Case")


public void searchTest() throws IOException

167 | P a g e
{
System.setProperty(reader.getDriverProperty(),reader.getDriverPath());
driver = new ChromeDriver();
//driver.get(reader.getAppUrl());
driver.get("https://www.toolsqa.com/automation-practice-form/");
System.out.println("Page Title is :"+driver.getTitle());
driver.findElement(By.id("photo")).click();

// Run FileUpload exe


Runtime.getRuntime().exec("E:/Armaan Khandelwal/FileUpload");
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
}
}

FILE UPLOADING USING SIKULI

File Upload using Sikuli in Selenium will discuss about how we can upload a file into web application while automating the
application using selenium webdriver. As we know that selenium webdriver automates only browsers (i.e. web applications
only). But sometimes we might need to automate windows based applications/popups such as upload a file or download a file
etc.

WHAT IS SIKULI
Sikuli automates anything we can see on the screen. It uses image recognition to identify and control GUI components. It is
useful when there is no easy access to a GUI’s internal or source code.

WHY TO USE SIKULI


As we know that Selenium web driver automates only browsers (i.e. web applications only). But sometimes we might need to
automate windows based applications/popups such as upload a file or download a file etc. But Selenium cannot handle these
kind of scenarios. So we will use some third party tools to automate these type of functionality. Especially uploading a file is one
of the scenarios we will face while automating most of the applications. For this we will depend mostly some third party tools
like AutoIT and Sikuli.

To work with Sikuli, need to download “sikuli-setup.jar” and run the same to get the “sikuli-java.jar” then we can use this jar file
in our project to work with Sikuli.

STEPS TO DOWNLOAD AND GET THE SIKULI JAR


1. Download the sikuli setup jar file from https://launchpad.net/sikuli/+download

2. Double click on the jar file. Then you will find the below screen and Click Yes to proceed further.

168 | P a g e
3. Then we will find the below screen. Check the check boxes of 2th options and click Setup Now button.

4. Now we can find the below screen and Click Yes to proceed further.

5. We can see the below screen

169 | P a g e
6. Once after completing the above procedure then we can able to see the “sikuli-java.jar” file in the same location where
the “sikuli-setup.jar” exist.

By following the above procedure, we will get the sikulixapi.jar file. Then we have to add this jar file to our selenium project to
work with sikuli in the selenium code.

Apart from all these things, we need to use two of the classes in Sikuli to automate the window based objects.

1. One is Screen Class this is a representation of the physical monitor where the capture process happens.
2. Second is Pattern class, this is used to associate an image file with additional attributes used in find operations and
when acting on a match object.

In simple words, Screen holds the entire screen and Pattern is a part of screen which we captured and stored in the project
folder. When we use Pattern object then it will verify where this kind of part is on the screen and once it identifies then it will
interact with that object.

Below are the sample captures of the File Name input box and Open Button.

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.sikuli.script.Pattern;
import org.sikuli.script.Screen;

public class FileUploadWithSikuli {

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

170 | P a g e
// TODO Auto-generated method stub

System.setProperty("webdriver.chrome.driver","src/test/resources/driver/chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.manage().window().maximize();
driver.get("http://demo.automationtesting.in/Register.html");
driver.findElement(By.id("imagesrc")).click();
Thread.sleep(5000);

// Sikuli Pattern Class used to find the Saved Screenshot path


Pattern fileNameInput = new Pattern("E:\\Armaan
Khandelwal\\SikuliCapture\\FileOpenInput.png");
Pattern openButton = new Pattern("E:\\Armaan
Khandelwal\\SikuliCapture\\OpenButton.png");

// Screen Class
Screen screen = new Screen();
screen.type(fileNameInput,"E:\\Armaan Khandelwal\\NewFile.txt");
screen.click(openButton);
}

CHAPTER 4
DIFFERENT TYPES FRAMEWORKS IN SELENIUM
WEBDRIVER
WHAT IS TEST FRAMEWORK IN SELENIUM

171 | P a g e
Selenium Framework is a code structure that helps to make code maintenance easy. Without frameworks, we will place the
“code” as well as “data” in the same place which is neither re-usable nor readable. Using Frameworks, produce beneficial
outcomes like increased code re-usage, higher portability, reduced script maintenance cost, higher code readability, etc.

There are different types of frameworks created by Selenium WebDriver to automate manual test cases

1. Data Driven Test Framework


2. Keyword Driven Test Framework
3. Behavior Data Driven Test Framework (BDD)
4. Page Object Model Test Framework

DATA DRIVEN TEST FRAMEWORK

 In data driven framework all of our test data is generated from some external files like Excel, CSV, JSON or some
database table.
 Data-driven is a test automation framework which stores test data in a table or spreadsheet format. This allows
automation engineers to have a single test script which can execute tests for all the test data in the table.
 In this framework, input values are read from data files and are stored into a variable in test scripts. DDT (Data Driven
testing) enables building both positive and negative test cases into a single test.
 For example, we want to test the login functionality with multiple input fields with 1000 different data sets. To test this,
we can take following different approaches:
o Approach 1) Create 1000 scripts one for each dataset and runs each test separately one by one.
o Approach 2) Manually change the value in the test script and run it several times.
o Approach 3) Import the data from the Excel, CSV and JSON File. Fetch test data from files by rows and column
one by one and execute the script.
In the given three scenarios first two are laborious and time-consuming. Therefore, it is ideal to follow the third
approach.
 Thus, the third approach is nothing but a Data-Driven framework.

How to create a Data Driven Automation Framework?

Consider we want to Test Login functionality of an application.

Step 1) Identify the Test Cases

 Input Correct username and password – Login Success


 Input incorrect username and correct password – Login Failure
 Input correct username and incorrect password - Login Failure

Step 2) Create detailed Test Steps for above 3 Test Cases

Test
Description Test Steps Test Data Expected Results
Case#

1. Launch the application


2. Enter Username password Username: valid Login Success
1 Check Login for valid credentials 3. Click Okay password: valid
4. Check Results

172 | P a g e
Test
Description Test Steps Test Data Expected Results
Case#

1. Launch the application


2. Enter Username password Username: invalid Login Fail
2 Check Login for invalid credentials 3. Click Okay password: valid
4. Check Results

1. Launch the application


2. Enter Username password Login Fail
3 Check Login for invalid credentials 3. Click Okay
4. Check Results

Step 4) Create an Excel/CSV/JSON file with the Input Test Data

Step 3) Create Test Script

We need to create a Test Script to execute these steps.

KEYWORD DRIVEN TEST FRAMEWORK

In the keyword-driven test framework, all the operations and instructions are Keyword Driven Framework is a type of Functional
Automation Testing Framework which is also known as Table-Driven testing or Action Word based testing.

The basic working of the Keyword Driven Framework is to divide the Test Case into four different parts.

1. First is Test Step


2. Second is Object of Test Step
3. Third is Action on Test Object
4. Fourth is Data for Test Object.

The above categorization can be done and maintained with the help of Excel spreadsheet:

 Test Step: It is a very small description of the Test Step or the description of the Action going to perform on Test Object.
 Test Object: It is the name of the Web Page object/element, like Username & Password.
 Action: It is the name of the action, which is going to perform on any Object such as click, open browser, input etc.
 Test Data: Data can be any value which is needed by the Object to perform any action, like Username value for
Username field.

173 | P a g e
BEHAVIOR DRIVEN DEVELOPMENT (BDD) TEST FRAMEWORK

What is Behavior Driven Development framework?

Consider we are assigned to create Login Functionality of the module in a Web application.

There are multiple ways to test it

 Correct username and incorrect password


 Incorrect username and correct password
 Correct username and correct password
 Incorrect username and incorrect password

174 | P a g e
The “Test Scenario” become more elaborate and complex as we consider additional features and so on. The general tendency of
developers is to develop features and write test code later. As, evident in above case, Test Case development for this case is
complex and developer will put off Testing till release, at which point he will do quick but ineffective testing.

To overcome this issue (Behavior Driven Development) BDD was conceived. It makes the entire testing process easy for a
developer.

In BDD, whatever we write must go into Given-When-Then steps. It more like writing documentation for the for the module.

Features in BDD

 Shifting from thinking in “tests” to thinking in “Behavior”


 Collaboration between Business stakeholders, Business Analysts, QA Team and developers
 Ubiquitous language, it is easy to describe
 Driven by Business Value
 Extends Test Driven Development (TDD) by utilizing natural language that non-technical stakeholders can understand
 BDD frameworks such as Cucumber or JBehave are an enabler, acting a “bridge” between Business & Technical
Language

What is Cucumber Framework

Cucumber is a tool that supports Behavior Driven Development (BDD). It offers a way to write tests that anybody can
understand, regardless of their technical knowledge.

In BDD, users (business analysts, product owners) first write scenarios or acceptance tests that describes the Behavior of the
system from the customer's perspective, for review and sign-off by the product owners before developers write their codes.

Gherkins Language

In Cucumber it executes the test scripts, which have been defined in the “feature file”. The language, in which this executable
feature files is written, is known as Gherkin. Gherkin is a plain English text language, which helps the tool - Cucumber to
interpret and execute the test scripts.

Gherkin provides the common set of keywords in English text, which can be used by people amongst the different community
and yet get the same output in the form of test scripts.

Gherkin will parse each step written in step definition file. So, the steps mentioned in the feature file and the step definition file
should match.

What is Feature

A Feature can be defined as a standalone unit or functionality of a project. Let’s take a very common example of a social
networking site. How does the feature of this product/project look like? Few basic features can be determined as −

 Create and remove the user from the social networking site.
 User login functionality for the social networking site.
 Sharing photos or videos on the social networking site.
 Sending a friend request.
 Logout.

By now each independent functionality of the product under test can be termed as a feature when we talk about Cucumber. It is
a best practice later when we start testing, that before deriving the test scripts, we should determine the features to be tested.

A feature usually contains a list of scenarios to be tested for that feature. A file in which we store features, description about
the features and scenarios to be tested is known as Feature File.

175 | P a g e
The keyword to represent a feature under test in Gherkins is “Feature”. The suggested best practice is, to write a small
description of the feature beneath the feature title in the feature file. This will fulfil the need of a good documentation as well.

Feature Files

The file, in which Cucumber tests are written, is known as feature files. It is advisable that there should be a separate feature
file, for each feature under test. The extension of the feature file needs to be “.feature”.

One can create as many feature files as needed. To have an organized structure, each feature should have one feature file.

What is Scenario

Scenario is one of the core Gherkin structures. Every scenario starts with the keyword “Scenario:” and is followed by an optional
scenario title. Each feature can have one or more scenarios and every scenario consists of one or more steps.

Scenario outline

Scenario outline basically replaces variable/keywords with the value from the table. Each row in the table is a scenario. Scenario
outline is like scenario structure; the only difference is the provision of multiple inputs.

Annotation

Annotation is a predefined text, which holds a specific meaning. It lets the compiler/interpreter know, what should be done
upon execution. Cucumber has got the following few annotations –

 Given –
o It describes the pre-requisite for the test to be executed.
o Example − GIVEN I am a Facebook user
 When −
o It defines the trigger point for any test scenario execution.
o Example − WHEN I enter "<username>"
 Then −
o Then holds the expected result for the test to be executed.
o Example − THEN login should be successful.
 And −
o It provides the logical AND condition between any two statements. AND can be used in conjunction with
GIVEN, WHEN and THEN statement.
o Example − WHEN I enter my "<username>" AND I enter my "<password>"
 But −
o It signifies logical OR condition between any two statements. OR can be used in conjunction with GIVEN,
WHEN and THEN statement.
o Example − THEN login should be successful. BUT home page should not be missing.
 Scenario −
o Details about the scenario under the test needs to be captured after the keyword “Scenario:”
o Example −

Scenario:

GIVEN I am a Facebook user


WHEN I enter my username
AND I enter my password
THEN login should be successful.
BUT home page should not be missing.

176 | P a g e
PAGE OBJECT MODEL (POM) & PAGE FACTORY

Why POM?

Starting an UI Automation in Selenium WebDriver is NOT a tough task. We just need to find elements, perform operations on it.

As we know in the test framework, all we are doing is finding elements and filling values for those elements. For small script the
maintenance looks easy. But with time test suite will grow. As we add more and more lines to our code, things become tough.

The chief problem with script maintenance is that if 10 different scripts are using the same page element, with any change in
that element, we need to change all 10 scripts. This is time consuming and error prone.

A better approach to script maintenance is to create a separate class file which would find web elements, fill them or verify
them. This class can be reused in all the scripts using that element. In future, if there is a change in the web element, we need to
make the change in just 1 class file and not 10 different scripts.

This approach is called Page Object Model (POM). It helps make the code more readable, maintainable, and reusable.

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 Web Elements of that web page and also contains Page methods which perform operations
on those Web Elements.

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. The Second benefit is the object repository is independent of test cases, 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 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. I.e. if after clicking
on the button we land on the home page, the method name will be like 'gotoHomePage()'.

What is Page Factory?

177 | P a g e
Page Factory is an inbuilt Page Object Model concept for Selenium WebDriver but it is much optimized. Here as well, we follow
the concept of separation of Page Object Repository and Test Methods. Additionally, with the help of PageFactory class, we use
annotations @FindBy to find WebElement. We use initElements method to initialize web elements

CHAPTER 5
INTRODUCTION TO CI AND CD TOOLS

178 | P a g e
INTRODUCTION TO DOCKER

WHAT IS DOCKER AND HOW IT HELPS IN AUTOMATION?


 Docker is a computer program that performs operating-system-level virtualization. The Operating system level
virtualization (OS virtualization) is a server virtualization technology which involves altering of an operating system
making it possible to run different applications that can be operated by different users working on a single computer at
one time. Below image will illustrate the concept of the Docker.

 Docker is a tool designed to make it easier to create, deploy and run applications by using containers.
 In simple words, Docker is a software containerization platform, meaning we can build our application, package them
along with their dependencies into a container and then these containers can be easily shipped to run on other
machines.

What are containers and images in Docker Software?

 An image is a lightweight, standalone, executable package of the software that includes everything needed to run an
application: code, runtime, system tools, system libraries and settings.
 Container is the runtime instance of an image i.e. An object is the runtime instance of a class. Similarly, a container is
the runtime instance of an image. The file system and configuration(read-only) application which is used to create
containers.
 A Docker file is where we write the instructions to build a Docker image.

How exactly Virtual Machines are different from Docker?

 Virtualization is the technique of importing a Guest operating system on top of a Host operating system.
 Containerization is however more efficient because there are no guest OS resources here and utilises a host’s operating
system, share relevant libraries and resources as and when needed unlike virtual machines.
 They are lightweight and faster than Virtual Machines.
 Containers are therefore smaller than Virtual Machines and enable faster start up with better performance, less
isolation and greater compatibility possible due to sharing of the host’s kernel.

HOW TO INSTALL DOCKER INTO MACHINES WITH PREREQUISITES NEEDED?


 Docker Installation
o To install the Docker Software on our machine go the official website of the Docker
https://docs.docker.com/docker-for-windows/install/ and click on “Download from Docker Hub” it will
redirect to you on different page.

179 | P a g e
o As we can see to download the Docker Hub we need to login. To login click on “ Please Login to Download”
Button

o After clicking on the “Please Login to Download” button the below login screen will open. Enter Docker ID and
password if you have already had else click on “Create Account”

o I don’t have Docker ID so I have clicked on “Create Account” and below screen will open. Enter new Docker Id,
Password and Email ID.

180 | P a g e
o After passing new Docker Id, Password and Email the complete registration will open. Complete all your details
and click on continue.

o Once we clicked on “Continue” button the below page will open

181 | P a g e
o Check your Email Id which you have provided at the time of registration and click on “Confirm Your Email with
Docker”

o After confirming Email click on “Get Docker” and the Docker Software will start downloading.

182 | P a g e
UNDERSTAND WORKING WITH DOCKERHUB
 To start working on Automation first we need a dependency software in the Docker Containers
 Selenium – Docker https://github.com/SeleniumHQ/docker-selenium image is already created by the Selenium Team,
so we don’t need to create the separate DockerFile for Selenium. It is already created we just need to download the
same.
 Before starting we will check that any container is running in our hosted machine by using the command prompt and
enter the command “docker ps”. It gives the status of the containers.
 So now we will download the image from DockerHub repository. There is a list on images on GitHub page
https://github.com/SeleniumHQ/docker-selenium from there we get the name of the image.

 Now we will pull the image from DockerHub by using the CMD and putting the command “ docker pull
selenium/standalone-chrome” the image name is “selenium/standalone-chrome”
 If we want to download the latest image, then put colon and write “ latest” after the image name i.e. “docker pull
selenium/standalone-chrome:latest”.
 To find out the list of images type command “docker images”.
 To execute the images on the system we will use “docker run -d -p 4444:4444 -v /dev/shm:/dev/shm
selenium/standalone-chrome:latest”
o Whereas “d” stands that containers are running in the background and “p” stands for the port number
o “4444:4444” stands that we are redirecting to container port 4444
o When executing docker run for an image with Chrome or Firefox please either mount -v /dev/shm:/dev/shm
or use the flag --shm-size=2g to use the host's shared memory.
 To stop the container, use the command “docker stop container_id”

IMPLEMENTATION OF DOCKER TO AUTOMATE TESTS


Remote WebDriver capabilities details for Selenium Docker Integration

 To execute the tests cases on the docker containers we will use the “RemoteDriver” class which accepts two
parameters i.e. URL and DesiredCapabilities. Whereas the URL is the HTTPS address of the docker hub
https://localhost:4444/wd/hub

183 | P a g e
Source Code of the ChromeStandaloneTest:

import java.net.MalformedURLException;
import java.net.URL;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;

public class ChromeStandaloneTest {

public static void main(String[] args) throws MalformedURLException


{
DesiredCapabilities cap = new DesiredCapabilities().chrome();
URL url = new URL("https://localhost:4444/wd/hub");
RemoteWebDriver driver = new RemoteWebDriver(url,cap);
driver.get("https://google.com");
System.out.println(driver.getTitle());
}

Invoking Docker with Firefox images for Selenium Tests

 We can execute the Selenium tests on different browsers i.e. chrome and Firefox etc. The only difference is that we
have to pull the selenium Firefox image from docker hub and run the same on container.

Source Code of FireFoxStandaloneTest:

import java.net.MalformedURLException;
import java.net.URL;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;

public class FirefoxStandaloneTest {

public static void main(String[] args) throws MalformedURLException


{
DesiredCapabilities cap = new DesiredCapabilities().firefox();
URL url = new URL("https://localhost:4444/wd/hub");
RemoteWebDriver driver = new RemoteWebDriver(url,cap);
driver.get("https://google.com");
System.out.println(driver.getTitle());
}
}

DOCKER COMPOSE FILE IN CREATING NODES AND HUB


 Selenium Grid have hub and nodes so we will link the hub with nodes via .yaml file. This file have all the services or we
can say have all the information about the images of hub and nodes.

184 | P a g e
 We can find this file on the official website https://github.com/SeleniumHQ/docker-selenium. Below I have shared the
yaml extension file.

# To execute this docker-compose yml file use `docker-compose -f <file_name> up`


# Add the `-d` flag at the end for detached execution
version: "3"
services:
selenium-hub:
image: selenium/hub:3.141.59-titanium
container_name: selenium-hub
ports:
- "4444:4444"
chrome:
image: selenium/node-chrome:3.141.59-titanium
volumes:
- /dev/shm:/dev/shm
depends_on:
- selenium-hub
environment:
- HUB_HOST=selenium-hub
- HUB_PORT=4444
firefox:
image: selenium/node-firefox:3.141.59-titanium
volumes:
- /dev/shm:/dev/shm
depends_on:
- selenium-hub
environment:
- HUB_HOST=selenium-hub
- HUB_PORT=4444

 Copy the above code and save this locally in the same folder with “docker-compose.yaml”
 To execute the yaml file Go to the location of the yaml file using command prompt and run “docker-compose -f docker-
compose.yaml up” and if we need to stop the same then we will use “docker-compose -f docker-compose.yaml down”
 If we want to create four more nodes of the chrome in the existing “docker-compose.yaml” file, then we will run
“docker-compose scale chrome=5”. Scale means we are increasing the count of the existing node present in the yaml
file and 5 is the number i.e. how much we will increase the scale

Parallel Distribution of tests with Multiple Dockers

 For parallel distribution of tests, we have to create the TestNG xml and will execute all the test classes in parallel by
using the tag “parallel” in the suite tag.
 The rest of the code is same as of previous there is no change in the code the only change in the tesng.xml file.

INTEGRATE DOCKER TESTS WITH MAVEN AND JENKINS


 Now to make the project with maven compatible to do first we have to add “plugin” tag in our “pom.xml”.
 Go to https://maven.apache.org/surefire/maven-surefire-plugin/examples/testng.html and search for “Using Suite
XML Files” section and add the same in pom.xml file.
185 | P a g e
 Please remember the plugin tag will be adding under the build tag

 After adding the Plugin tag go to Jenkins and create a new job for our project.

INTRODUCTION TO JENKINS PIPELINES

WHAT ARE JENKINS PIPELINES?


 A Pipeline is a collection of jobs that brings the software from version control into the hands of the end users by using
automation tools.
 In simple words, Jenkins Pipeline is a combination of plugins that support the integration and implementation of
continuous delivery pipelines using Jenkins. A pipeline has an extensible automation server for creating simple or
complex delivery pipelines "as code," via pipeline DSL (Domain-specific Language).
 What are Continuous Delivery Pipelines? How it Works? In a Jenkins pipeline, every job or event has some sort of
dependency on at least one or more events.

 The picture above represents a continuous delivery pipeline in Jenkins. It contains a group of states called build, deploy,
test and release. These events are interlinked with each other. Every state has its events, which work in a sequence
called a continuous delivery pipeline.
A continuous delivery pipeline is an automated expression to display our process for getting software for version
control. Thus, every change made in our software goes through a number of complex processes on its way to being
released. It also involves developing the software in a reliable and repeatable manner, and progression of the built
software through multiple stages of testing and deployment.
 It is a workflow used to achieve continuous delivery in software development process.

Pipeline can be implemented with below two methods

1. Jenkins build Pipeline plugin (Suitable for Small Scale Applications)


2. Jenkins Pipeline Project (Large Scale Applications with many Jobs)

In second approach Pipeline is created by executing Jenkins File. A Jenkins file is a text file that stores the entire workflow as
code.

JENKIN PIPELINE VIEW PLUGIN TO CHAIN THE JOBS

186 | P a g e
 Go to Jenkins dashboard http://localhost:8080/
 We will go with first approach “Jenkins Build Pipeline Plugin” to do click on “Manage Jenkins” and after that click on
“Manage Plugins”

 If we have already installed the plugin, it is shown under the installed tab. If we do not have the plugin previously
installed, it shows up under the Available tab.

 Once we logged in to our Jenkins Dashboard and Build Pipeline Plugin installed. Now Click on the "+" button on the
left-hand side of our Jenkins dashboard to create a pipeline.

187 | P a g e
 We will be asked to give a name to the pipeline view and call it "Pipeline Build" and Select “Build a pipeline view”
under options and Click “OK”

 In the next page, we will be asked for some more details to configure our Jenkins pipeline. Just accept the default
settings, and make sure to choose the first job under the settings.

 This will show us the sample pipeline view of our item, as given below:

 For running a pipeline build, we need to chain our jobs first. For this, go to our first job and click on configure. Now,
under Build Triggers, check the Build after other projects are built option.

188 | P a g e
 In future if is there any changes in happen in any build like code update, just click on the “ Run” button on the Pipeline
Build Demo dashboard

 We can also change the pipeline display by clicking on the “Configure”. Suppose currently in the pipeline there is only
one Pipeline instances if we change this to 5 then it shows the how many runs.

GROOVY SCRIPT SYNTAX TO BUILD PIPELINE


 Now we will go with the second approach i.e. Jenkins Pipeline Project. In this approach Pipeline is created by executing
Jenkins File. A JenkinsFile is a text file that stores the entire workflow as code. The JenkinsFile is written using the
Groovy DSL (Domain Specific Language). It is written based on two syntaxes, namely:
Declarative Pipeline syntax and Scripted pipeline syntax
 In the “Declarative Pipeline Syntax” we will create one JenkinsFile and placed this file to some SCM tool i.e. Script
Management Tool (Git, SVN etc.) and pass the path of Git and SVN repository to this Jenkins Pipeline.
 But in “Scripted pipeline syntax” we will create the script in Jenkins itself.

189 | P a g e
 The most used method is “Declarative Pipeline Syntax”.

Create Pipeline job and Construct it using Declarative Syntax

pipeline
{
//agent is Server
agent any
//Stages are Jobs
stages
{
stage('Build')
{
steps
{
//Commands
}
}

stage('Deploy')
{
steps
{
//Commands
}
}

stage('Test')
{
steps
{
//Commands
}
}

stage('Release')
{
steps
{
//Commands
}
}
}
}

190 | P a g e
IMPORTANCE OF “JENKINSFILE” AND ITS KEYWORDS FOR PIPELINE BUILDING
What is JenkinsFile

Jenkins pipelines can be defined using a text file called JenkinsFile. We can implement pipeline as code using JenkinsFile, and
this can be defined by using a domain specific language (DSL). With JenkinsFile, we can write the steps needed for running a
Jenkins pipeline.

The benefits of using JenkinsFile are:

 We can create pipelines automatically for all branches and execute pull requests with just one JenkinsFile.
 We can review our code on the pipeline
 We can audit our Jenkins pipeline
 This is the singular source for our pipeline and can be modified by multiple users.

JenkinsFile can be defined by either Web UI or with a JenkinsFile.

Declarative versus Scripted pipeline syntax:

There are two types of syntax used for defining our JenkinsFile.

1. Declarative
2. Scripted

Declarative:

Declarative pipeline syntax offers an easy way to create pipelines. It contains a predefined hierarchy to create Jenkins pipelines.
It gives us the ability to control all aspects of a pipeline execution in a simple, straight-forward manner.

Scripted:

Scripted Jenkins pipeline runs on the Jenkins master with the help of a lightweight executor. It uses very few resources to
translate the pipeline into atomic commands. Both declarative and scripted syntax are different from each other and are defined
totally differently.

Jenkins Pipeline Concepts

Term Description

Pipeline The pipeline is a set of instructions given in the form of code for continuous delivery and consists of
instructions needed for the entire build process. With pipeline, we can build, test, and deliver the
application.

Node The machine on which Jenkins runs is called a node. A node block is mainly used in scripted pipeline
syntax.

Stage A stage block contains a series of steps in a pipeline. That is, the build, test, and deploy processes all come
together in a stage. Generally, a stage block is used to visualize the Jenkins pipeline process.

191 | P a g e
Step A step is nothing but a single task that executes a specific process at a defined time. A pipeline involves a
series of steps.

Run Pipeline using JenkinsFile

 First create a new job on Jenkins. I have created the Job and call it “ PipeLineScriptDemo” and select “Pipeline”
template and click Save and Apply
 After creating the Job on Jenkins now config the Pipeline and choose the option “Pipeline script from SCM” and in SCM
choose “Git”. Now go to Git repository and copy the path of repository and paste in the “Repository URL”

 Check the “Script Path” i.e. we have the correct file name path.

 Now go to “Jenkins Dashboard” and run the build by using “Build Now”. The pipeline will start executing.

192 | P a g e
CHAPTER 6
GIT COMMANDS AND ITS USES – VERSION CONTROL
SYSTEM
INTRODUCTION TO GIT

1. Git is a free and open source distributed version control system designed to handle everything from small to very large
projects with speed and efficiency.
2. We can find the basic Git commands from the link https://confluence.atlassian.com/bitbucketserver/basic-git-
commands-776639767.html

193 | P a g e
Git task Notes Git commands

Tell Git who Configure the author name git config --global user.name "Arman Khandelwal"
you are and email address to be git config --global user.email [email protected]
used with your commits.

Note that Git strips some


characters (for example
trailing periods)
from user.name.

Create a new   git init


local
repository

Check out a Create a working copy of a git clone /path/to/repository


repository local repository:

For a remote server, use: git clone username@host:/path/to/repository

Add files Add one or more files to git add <filename>


staging (index):
git add *

Commit Commit changes to head git commit -m "Commit message"


(but not yet to the remote
repository):

Commit any files you've git commit -a


added with git add, and
also commit any files
you've changed since then:

Push Send changes to the git push origin master


master branch of your
remote repository:

Status List the files you've git status


changed and those you still
need to add or commit:

Connect to a If you haven't connected git remote add origin <server>


remote your local repository to a
repository remote server, add the
server to be able to push
to it:

194 | P a g e
List all currently configured git remote -v
remote repositories:

Branches Create a new branch and git checkout -b <branchname>


switch to it:

Switch from one branch to git checkout <branchname>


another:

List all the branches in your git branch


repo, and also tell you
what branch you're
currently in:

Delete the feature branch: git branch -d <branchname>

Push the branch to your git push origin <branchname>


remote repository, so
others can use it:

Push all branches to your git push --all origin


remote repository:

Delete a branch on your git push origin :<branchname>


remote repository:

Update from Fetch and merge changes git pull


the remote on the remote server to
repository your working directory:

To merge a different git merge <branchname>


branch into your active
branch:

View all the merge git diff


conflicts: git diff --base <filename>
View the conflicts against git diff <sourcebranch> <targetbranch>
the base file:
Preview changes, before
merging:

After you have manually git add <filename>


resolved any conflicts, you
mark the changed file:

Tags You can use tagging to git tag 1.0.0 <commitID>

195 | P a g e
mark a significant
changeset, such as a
release:

CommitId is the leading git log


characters of the
changeset ID, up to 10, but
must be unique. Get the ID
using:

Push all tags to remote git push --tags origin


repository:

Undo local If you mess up, you can git checkout -- <filename>
changes replace the changes in
your working tree with the
last content in head:
Changes already added to
the index, as well as new
files, will be kept.

Instead, to drop all your git fetch origin


local changes and
commits, fetch the latest git reset --hard origin/master
history from the server and
point your local master
branch at it, do this:

Search Search the working git grep "foo()"


directory for foo():

CREATING GIT CONFIG AND REPOSITORIES

Create a Git Repository

1. First, go to the BitBucket by using the link https://bitbucket.org/dashboard/repositories.


2. Click + in the global sidebar and select Repository under Create a new.

196 | P a g e
3. Choose a repository Workspace.
4. Enter a Repository name that will describe your repository and appear in its URL.

5. Keep access to your repository set to Private unless you want to make your repository public so that anyone can see it.
6. If we already have files that we want to add to our repository, select No from Include a README? Otherwise, go with
the default option or select a one of the included README options.
7. Select the Version control system. If we don't know the difference, keep Git as the default system.
8. Click Create.

How to push code to remote repository or add unversioned code to a repository

If you have code that is currently not under version control and you want to start controlling it, you can prepare it by putting
your code into a Git repository locally. From there, you push it to Bitbucket.

Add to a Git repository

1. From your terminal or use Command Prompt, change to the root directory of your existing code. By using the command
“cd location of the project”
2. Now “Tell Git who you are” by using the below commands.

$ git config –-global user.name “Arman Khandelwal”

$ git config –-global user.email “[email protected]

3. Initialize the directory under version control from the following command, the “./git” file is created:

$ git init

4. Add the existing files to the repository you have initialized, add is the command which is used to staging the code into
Git Repository.

$ git add –all

5. Commit the files, there is two terminologies in the Git i.e. Staging (1 st Level of Commit) and Commit (Final Level of
Commit). Without commit we are not able to push into Git.

$ git commit -m "initial commit"

6. Connect your new local Git repository to the remote repository on Bitbucket. To do so, enter git remote add origin with
the remote URL:

$ git remote add origin <bitbucket_URL>

You can find the URL next to the git clone command for the repository:

197 | P a g e
7. Push all the code in your local repo to Bitbucket with the following command:

$ git push -u origin –all

Push the code on existing Git Repository

 Prior we have uploaded the whole new code on the Git Repository. Now to get latest code from the Git repository so
we have to clone the existing Git Repository into our local repository.
 Clone is the process to extract the code which is present in our Git Repository. We are cloning the repository first time
after cloning has been done, we will only pull the code.
 To clone the Git Repository as a fresh, we use commands

$ git clone <bitbucket_URL>

 After cloning, the whole project’s code is downloaded in our system. Now do some changes and push these changes
back to Git Repository.
 Before staging the code first, we will check the status of the Git Repository by using the command.

$ git status

 Now staging the code after changes we will use the command:

$ git add <filename>


$ git add *

 After staging we commit the code by using command:

$ git commit -m "initial commit"

 Connect your local Git repository to the remote repository on Bitbucket.

$ git remote add origin <bitbucket_URL>

 Now push the code to Git Repository, by using the command:

$ git push origin master <Branch Name>

Pull the latest changes or code from existing Git Repository to our local repository

 If you want to get the latest changes from the Git Repository, by using the command:

$ git pull origin master <Branch Name>

198 | P a g e
Importance of Branching in Git

 Once a feature is ready, it is merged into our Develop branch, tested, fixed if necessary, then Develop gets merged into
Master. Branching in open source projects is important because of the number of committers that could potentially be
pushing and pulling code to your project.
 Create a new branch and switch to it by using the command:

$ git checkout -b <branchname>

 If we want to see the List all the branches in our repo, and also tell us what branch we're currently in:

$ git branch

 We will Switch from one branch to another:

$ git checkout <branchname>

 Now Push the branch to your remote repository, so others can use it:

$ git push origin <branchname>

 To Pull the code into branch

$ git pull origin <branchname>

 To merge a different branch into your active branch <master>

$ git merge <branchname>

HOW TO RESOLVE MERGE CONFLICTS WITH GIT?

 Conflicts generally arise when two people have changed the same lines in a file, or if one developer deleted a file while
another developer was modifying it. In these cases, Git cannot automatically determine what is correct. Conflicts only
affect the developer conducting the merge, the rest of the team is unaware of the conflict. Git will mark the file as being
conflicted and halt the merging process. It is then the developers' responsibility to resolve the conflict.
 If there is merge conflict then first, we have to resolve the issues by deleting or adding the changes into the conflicted
file and after that process the staging i.e. $ git add *
 And “committing” the code. Now we are able to merge the code.

How to identify merge conflicts?

 Think of these new lines as "conflict dividers". The ======= line is the "center" of the conflict. All the content between
the center and the <<<<<<< HEAD line is content that exists in the current branch master which the HEAD ref is pointing
to. Alternatively, all content between the center and >>>>>>> “new_branch_to_merge_later” is content that is present
in our merging branch.

<<<<<<< HEAD
=======
>>>>>>> new_branch_to_merge_later

199 | P a g e
CHAPTER 7
AGILE SCRUM METHODOLOGY
WHAT IS AGILE SOFTWARE DEVELOPMENT?

Agile is a term used to describe approaches to software development emphasizing incremental delivery, team collaboration,
continual planning, and continual learning, instead of trying to deliver it all at once near the end.

Agile focuses on keeping the process lean and creating minimum viable products (MVPs) that go through a number of iterations
before anything is final. Feedback is gathered and implemented continually and in all, it is a much more dynamic process where
everyone is working together towards one goal.

200 | P a g e
DIFFERENT CEREMONIES IN AGILE

Meetings, or "ceremonies" are an important part of agile development. But they are one of many important elements, and
shouldn’t be conducted in a vacuum. (It's tempting to add some ceremonies to a waterfall project and call it "agile", but this will
get you nowhere.)

Scrum ceremonies ensure that everyone (the scrum master, product owner and development team) is in-sync. These
ceremonies are held at key instances in a sprint, which we’ll outline below.

There are four Scrum Ceremonies

Scrum is executed in what are called sprints, or short iterations of work lasting usually no more than two weeks. A sprint
employs four different scrum ceremonies to ensure proper execution: sprint planning, daily scrum, sprint review and sprint
retrospective. These scrum ceremonies are outlined below:

 Sprint Planning: This is where the team meets and decides what they need to complete in the coming sprint
 Daily Scrum: This is a stand-up meeting, or a very short – 15-minute mini-meeting – for the team to make sure they’re
all on the same page.
 Sprint Review: This is another type of meeting, but one in which the team demos what they shipped in the sprint.

201 | P a g e
 Sprint Retrospective: This is when the team reviews their work, identifying what they did well and what didn’t go as
planned, so they can make the next sprint better.

1. Sprint Planning

Attendees: Development team, Scrum master, Product owner

When: At the beginning of a sprint.

Duration: Usually an hour per week of iteration–e.g. a two-week sprint kicks off with a two-hour planning meeting.

Agile Framework: Scrum and Kanban

Purpose: Sprint planning sets up the entire team for success throughout the sprint. Coming into the meeting, the product
owner will have a prioritized product backlog. They discuss each item with the development team, and the group
collectively estimates the effort involved. The development team will then make a sprint forecast outlining how much work
the team can complete from the product backlog. That body of work then becomes the sprint backlog.

2. Daily Stand-up or Daily Scrum

Attendees: Development team, Scrum master, Product owner

When: Once per day, typically in the morning.

Duration: No more than 15 minutes. Don't book a conference room and conduct the stand-up sitting down. Standing up
helps keep the meeting short!

Agile Framework: Scrum and Kanban.

Purpose: Stand-up is designed to quickly inform everyone of what's going on across the team. It's not a detailed status
meeting. The tone should be light and fun, but informative. Have each team member answer the following questions?

 What did I complete yesterday?


 What will I work on today?
 Am I blocked by anything?

There's an implicit accountability in reporting what work you completed yesterday in front of your peers. No one wants to
be the team member who is constantly doing the same thing and not making progress.

3. Sprint Review

Attendees:

Required: Development team, Scrum master, Product owner

Optional: Project stakeholders

When: At the end of a sprint or milestone.

Duration: 30-60 minutes.

Agile Framework: Scrum and Kanban. Like planning, review for Kanban teams should be aligned with team milestones
rather than on a fixed cadence.

Purpose: Iteration review is a time to showcase the work of the team. They can be in a casual format like "demo Fridays", or
in a more formal meeting structure. This is the time for the team to celebrate their accomplishments, demonstrate work

202 | P a g e
finished within the iteration, and get immediate feedback from project stakeholders. Remember, work should be fully
demonstrable and meet the team's quality bar to be considered complete and ready to showcase in the review.

4. Sprint Retrospective

Attendees: Development team, Scrum master, Product owner

When: At the end of an iteration.

Duration: 60 minutes.

Agile Framework: Scrum and Kanban. Scrum teams do sprint retrospective based on a fixed cadence. Kanban teams can
benefit from occasional retrospectives, too.

Purpose: Agile is about getting rapid feedback to make the product and development culture better. Retrospectives help the
team understand what worked well–and what didn't.

Retrospectives aren't just a time for complaints without action. Use retrospectives to find out what's working so the team
can continue to focus on those areas. Also, find out what's not working and use the time to find creative solutions and
develop an action plan. Continuous improvement is what sustains and drives development within an agile team, and
retrospectives are a key part of that.

WHAT IS STORY POINT IN AGILE? HOW TO ESTIMATE A USER STORY?

A story point is a metric used in agile project management and development to estimate the difficulty of implementing a given
user story, which is an abstract measure of effort required to implement it. In simple terms, a story point is a number that tells
the team about the difficulty level of the story. Difficulty could be related to complexities, risks, and efforts involved.

Story point estimation, a kind of relative estimation, is typically performed at the Product Backlog Grooming Sessions and the
Product Backlog is evaluated by the team who responsible for the actual development and testing work.

In order to make the Sprint Planning more efficient in practice, PO and the Team will make a rough estimation called product
backlog grooming before the Sprint Planning and check for:

 If the Sprint Plan is readily to be conducted efficiently?


 Is there enough information to complete these matters?
 Is the user story split reasonably?

Fibonacci number for Story Point

When the development team conducts an estimation, it is recommended to abandon the traditional “human-day” assessment
method, using the point of the story point, using the Fibonacci number (1, 2, 3, 5, 8, 13, 21…) to estimate the story point.

How to do Agile Estimation?

In order to do that each team would have to find a baseline story. It does not necessarily to be the smallest one, but the one
that everyone within the team can resonate with. Once determined, sizing of all the user stories should be initiated by
comparing them against the baseline.

When estimating new stories all you have to do is pick a story and say: “will this take longer than reference story x?” or “will it
be less than reference y?” With enough reference stories there should be a suitable comparator to find a similar sized story and
give it the same points or a bit more or a bit less based on a considered factor.

203 | P a g e
While estimating story points, we assign a point value to each story. Relative values are more important than the raw values. A
story that is assigned 2 story points should be twice as much as a story that is assigned 1 story point. It should also be two-thirds
of a story that is estimated 3 story points.

In addition, it is important to note that when the single story point of the assessment is greater than 21, the user story needs to
be split again, and the single user story point is no more than 8 is the most rational state.

Story points vs. hours

Traditional software teams give estimates in a time format: days, weeks, months. Many agile teams, however, have transitioned
to story points. Story points rate the relative effort of work in a Fibonacci-like format: 0, 0.5, 1, 2, 3, 5, 8, 13, 20, 40, 100. It may
sound counter-intuitive, but that abstraction is actually helpful because it pushes the team to make tougher decisions around
the difficulty of work. Here are few reasons to use story points:

 Dates don’t account for the non-project related work that inevitably creeps into our days: emails, meetings, and
interviews that a team member may be involved in.
 Dates have an emotional attachment to them. Relative estimation removes the emotional attachment.
 Each team will estimate work on a slightly different scale, which means their velocity (measured in points) will naturally
be different. This, in turn, makes it impossible to play politics using velocity as a weapon.
 Once you agree on the relative effort of each story point value, you can assign points quickly without much debate.
 Story points reward team members for solving problems based on difficulty, not time spent. This keeps team members
focused on shipping value, not spending time.

WHAT IS VELOCITY IN AGILE SCRUM METHODOLOGY

In agile velocity is the amount of work done during a sprint. In agile, velocity provides the distance our team travel to reach to
the sprint objective.

It helps us to understand how long it will take our team to finish the whole backlog. In general, it takes few sprint to get to know
the team velocity.

It is the average the amount of user story completed by our team in for e.g. past three sprint take the average of it is our team
velocity. Assuming our team is completing 5-7 user stories in each sprint with total story points of 25-35. So, the average velocity
of team in past three is 25 – 35

How to Calculate Sprint Velocity in Agile Development?

Assuming that team is having one-week sprint.

Calculating Sprint 01 Velocity in Agile Scrum

 Assuming that in sprint 01, team committed to total of 5 user stories


 Story point of each of the user story = 8 story points
 Total story points committed by team in sprint 01 = 40 story points

By end of sprint 01 team completed 3 out of 5 user stories

 Total user stories completed in sprint 01 = 3 user stories


 Total story points completed in sprint 01 = 3 x 8 story points -> 24 story points

Calculating Sprint 02 Velocity in Agile Scrum

 Assuming that in sprint 02, team committed to total of 7 user stories

204 | P a g e
 Story point of each of the user story = 8 story points
 Total story points committed by team in sprint 01 = 56 story points

By end sprint team completed 4 out of 7 user stories

 Total user story completed in sprint 02 = 4 user stories


 Total story points completed in sprint 02 = 4×8 story points->32 story points

Calculating Sprint 03 Velocity in Agile Scrum

 Assuming that in sprint 03, team committed to total of 9 user stories


 Story point of each of the user story = 8 story points
 Total story points committed by team in sprint 03 = 72 story points

By end sprint 03, team completed 5 out of 9 user stories

 Total user story completed in sprint 03 = 5 user stories


 Total story points completed in sprint 03 = 5×8 story points->40 story points

Calculating Average Velocity of Sprints

Once we know the velocity of past three sprints, calculate the average of them. Let’s assume our previous sprint velocities were
[completed story points in each of the sprints]

 Sprint 01: 24
 Sprint 02: 32
 Sprint 03: 40

So our average velocity of sprint is: 24+32+40/32 = 32

That is our average velocity in past three sprints. This is the reference how our team will be finishing the user stories in a sprint.

We need to successfully complete at least 3-5 sprints and check our completed story points in each of the prints, this will give us
better visibility and help us in planning future sprints, when planning our sprint, velocity will provide us reference how much
user stories can be completed in a sprint, by using this value we are sure that we are not over or under planning our sprint. So
the total number of user story taken during a sprint should not be exceeding the average velocity of past sprints.

205 | P a g e

You might also like