Selenium With Java
Selenium With Java
Selenium With 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.
Create Object
package corejava;
package corejava;
6|P a g e
}
WHAT IS CLASS
A class is a group of objects which have common properties. It is a template from which objects are created.
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;
// Create Method
public static void methodDemo()
{
System.out.println("Method Example");
}
}
Output:
package corejava;
Output:
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;
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.
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.
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
package corejava;
10 | P a g e
}
Output:
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;
// Create Method
public void details()
{
System.out.println("Name : "+name+" and age : "+age);
}
Output:
We are not creating any constructor so compiler provides us a default constructor. Here 0 and null values are provided by
default 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;
// Create Method
public void details()
{
System.out.println("Name : "+name+" and age : "+age);
}
Output:
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 constructor name must be same as the class name. The method name may or may not be same as the class name.
Yes, it is the current class instance, we cannot use return type yet it returns a value.
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.
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.
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;
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);
}
objConstructorEx.details();
}
}
Output:
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.
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.
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.
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.
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;
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 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.
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.
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;
}
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;
17 | P a g e
Output:
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
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();
18 | P a g e
// Creating the Object of Parent Class
MethodOverridingEx objMethodOverridingEx = new MethodOverridingEx();
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.
Whenever we create the instance of subclass, an instance of parent class is created implicitly which is referred by super
reference variable.
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.
If we make any variable as final, we cannot change the value of final variable (It will be constant).
package corejava;
package corejava;
class FinalEx
{
// final method
final void details()
{
20 | P a g e
System.out.println("In final method");
}
}
package corejava;
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.
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;
package corejava;
22 | P a g e
// Setting value in the name method
objEncapsulationEx.setName("Arman Khandelwal");
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.
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.
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.
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.
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.
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.
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.
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
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 method
abstract void abstractMethod();
}
class AbstractExTest
{
public static void main(String[] args)
{
AbstractEx objAbstractEx = new SubAbstractEx();
System.out.println(objAbstractEx.operation(4, 5));
}
}
Output:
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.
There are below reasons to use interface. They are given below.
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.
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();
}
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();
}
@Override
public void methodInterfaceEx()
{
System.out.println("Implementing from InterfaceEx interface");
}
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.
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.
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.
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;
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;
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;
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
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.
package corejava;
// 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.
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;
Output:
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;
32 | P a g e
{
public static void main(String[] args)
{
// Declaring an array
int arr[] = {1,2,3,4,5};
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;
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;
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.
Exception Handling is a mechanism to handle runtime errors such as ClassNotFound, IO, SQL, Remote etc.
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
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
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;
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.
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:
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;
Output:
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;
}
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.
Finally block in java can be used to put "clean-up" code such as closing a file, closing connection etc.
package corejava;
// 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;
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.
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.
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.
// finally block
finally
{
System.out.println("Finally Block is always Executed");
}
}
}
Output:
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:
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?
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.
Below table depicts the various methods that are used for performing operations on Java files.
File Operations
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.
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:
package filehandling;
import java.io.File;
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());
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");
// 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.
package filehandling;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
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.)
Collection framework represents a unified architecture for storing and manipulating group of objects. It has:
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.
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.
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;
// 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);
51 | P a g e
}
// remove method
list.remove("XYZ");
// Clear ArrayList
list.clear();
System.out.println("ArrayList after Clearing : "+list);
}
}
Output:
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.
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;
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);
// Remove Items
list.remove(1);
System.out.println("The Elements in LinkedList after removing item : "+list);
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;
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.
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.
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;
// Duplicate Element
hs.add("Java");
hs.add("Python");
// Duplicate Element
hs.add("Python");
hs.add("C#");
hs.add("JavaScript");
// 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.
package collectionsframework;
import java.util.TreeSet;
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.
package collectionsframework;
import java.util.HashMap;
import java.util.Map;
for(Map.Entry m:map.entrySet())
{
System.out.println(m.getKey()+ " : "+m.getValue());
}
}
}
59 | P a g e
Output:
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.
package collectionsframework;
import java.util.LinkedHashMap;
// Fetching Keys
System.out.println("Keys : "+map.keySet());
// Fetching Values
System.out.println("Values : "+map.values());
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.
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.
HashMap TreeMap
HashMap can contain one null key. TreeMap can not contain any null key.
HASHTABLE CLASS
Java Hashtable class implements a Hashtable, which maps keys to values. It inherits Dictionary class and implements the Map
interface.
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.
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.
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);
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
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.
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.
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
64 | P a g e
<input id="email" class="required" type="text"/>
driver.findElement(By.id("email"));
Locating by Name
Locating by LinkText
<a href="http://www.seleniumhq.org">Downloads</a>
driver.findElement(By.linkText("Downloads"));
Locating by PartialLinkText
or
select.selectByValue("11");
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"));
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']")
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.
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;
Example how to convert text from lower case to upper case using keyDown() method and doubleClick() on the text
71 | P a g e
Example shows how to right click on any element on the UI using contextClick() method.
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.
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.
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.
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.
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.
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;
73 | P a g e
{
public static String lastWindowHandle = "";
public static int count = 0;
Output:
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.
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?
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.
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
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);
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");
driver.switchTo().frame(WebElement);
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.
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.
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)
Once we switch to the outer frame, we should know whether any inner frame present inside the outer frame
driver.get("Url");
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(2, TimeUnit.SECONDS);
77 | P a g e
System.out.println("Total Frames --" + size);
Step 2)
size = driver.findElements(By.tagName("iframe")).size();
Step 3)
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;
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");
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
79 | P a g e
a time; FALSE if otherwise.
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;
80 | P a g e
System.out.println("Before Click Drop down :"+beforeClick);
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;
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();
}
}
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;
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());
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());
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;
83 | P a g e
driver.get("https://rahulshettyacademy.com/AutomationPractice/");
driver.findElement(By.id("name")).sendKeys("Armaan");
driver.findElement(By.id("alertbtn")).click();
// Switch to Alert
driver.switchTo().alert().accept();
}
}
Methods in Alerts
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");
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.
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.
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.
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;
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());
}
}
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".
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.
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.
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:
.withTimeout(timeout, SECONDS)
.pollingEvery(timeout, SECONDS)
.ignoring(Exception.class);
.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"
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.
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;
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;
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.
Include ‘maven/bin’ directory in ‘PATH’ variable. To run maven from command prompt, this is necessary.
95 | P a g e
TERMINOLOGIES OF MAVEN
ArtifactID and GroupID are the most commonly heard terms in the maven.
Builds
Documentation
Reporting
Dependencies
SCMs
Releases
Distribution
mailing list
Element Description
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.
scope defines scope for this maven project. It can be compile, provided, runtime, test and system.
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:
Validates that the project is correct and all necessary information is available. This also makes sure the
validate
dependencies are downloaded.
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.
TestNG is an open source automated testing framework where "NG" means "Next Generation"
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.
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[ ].
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;
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:
On an existing testng.xml.
On a synthetic testng.xml, created entirely from Java.
By directly setting the test classes.
Testng.xml file:
103 | P a g e
</suite> <!-- Suite -->
The following table lists all the legal attributes that <suite> accepts.
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).
6 time-out - The default timeout that will be used on all the test methods found in this 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;
// 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.
106 | P a g e
package testng;
import org.testng.annotations.Test;
// 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:
<classes>
<class name="testng.GroupingExample"/>
<class name="testng.TestngAnnotation"/>
</classes>
107 | P a g e
</test> <!-- Test -->
</suite> <!-- Suite -->
Output:
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.
package testng;
import org.testng.annotations.Test;
@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;
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;
@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.
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;
@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.
package testng;
import org.testng.annotations.Test;
// 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");
}
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
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.
package testng;
import org.testng.annotations.Parameters;
import org.testng.annotations.Test;
115 | P a g e
}
Testng.xml file:
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.
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;
@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"}
};
}
Output:
118 | P a g e
LISTENERS IN TESTNG
There are two main listeners.
1. WebDriver Listeners
2. TestNG Listeners
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.
There are many types of listeners which allows you to change the TestNG's Behavior.
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.
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;
120 | P a g e
public void onTestFailedButWithinSuccessPercentage(ITestResult arg0) {
// TODO Auto-generated method stub
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;
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");
}
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.
@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.
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.
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:
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;
@Test
public void readExcel() throws IOException
{
File file = new File("src/test/resources/testdata/searchDetails.xlsx");
FileInputStream finput = new FileInputStream(file);
// Load Sheet
sheet = workbook.getSheet("Search");
@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);
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.
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;
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;
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";
}
}
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();
}
if(row==null)
row = sheet.createRow(rowNum);
cell = row.getCell(colNum);
if(cell==null)
cell = row.createCell(colNum);
cell.setCellValue(value);
return true;
}
132 | P a g e
try
{
int colNum = -1;
sheet = workbook.getSheet(sheetName);
row = sheet.getRow(0);
//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);
return true;
}
package datahandling;
import java.io.IOException;
import org.testng.annotations.DataProvider;
@DataProvider(name="getData")
public static Object[][] getData() throws IOException
{
Object[][] data = testData(xlFilePath,sheetName);
return data;
}
134 | P a g e
int columns = objExcelUtility.getColCount(sheetName);
return excelData;
}
}
package datahandling;
import java.io.IOException;
import org.testng.annotations.Test;
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.
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.
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;
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);
}
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;
package datahandling;
import java.io.IOException;
import org.testng.annotations.Test;
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:
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.
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.
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.
2. Write Hard Coded Values in the Property File. Below is the properties file that we will use
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 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);
}
}
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.");
}
With
System.setProperty(reader.getDriverProperty(),reader.getDriverPath());
@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);
}
}
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.
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.
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));
}
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
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.
145 | P a g e
public void setPurchasedDate(String purchasedDate)
{
PurchasedDate = purchasedDate;
}
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.
146 | P a g e
Create object of ArrayList in “JsonToJava” class to fetch the list of results.
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:
//Creating Connection
Connection conn = null;
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/Business",
"root123", "root@123");
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));
}
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;
System.out.println(custDetails.getCourseName());
}
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
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.
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);
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
{
//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");
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);
}
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.
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;
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);
}
}
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.
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.
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.
Step 1
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
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.
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
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).
Import the necessary packages for RemoteWebDriver and then pass the DesiredCapabilities object that we created above as a
parameter for the RemoteWebDriver object.
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.
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.
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.
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.
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.
2. A new page will open, click on the top most link of “SciTE4AutoIt3.exe” and follow the process until the installation is
finished.
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.
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"
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");
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();
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.
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.
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.
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;
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);
// 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
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.
Test
Description Test Steps Test Data Expected Results
Case#
172 | P a g e
Test
Description Test Steps Test Data Expected Results
Case#
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.
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
Consider we are assigned to create Login Functionality of the module in a Web application.
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
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:
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()'.
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
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.
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.
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.
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.
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”
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;
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.
import java.net.MalformedURLException;
import java.net.URL;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;
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.
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
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.
After adding the Plugin tag go to Jenkins and create a new job for our project.
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.
In second approach Pipeline is created by executing Jenkins File. A Jenkins file is a text file that stores the entire workflow as
code.
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.
189 | P a g e
The most used method is “Declarative Pipeline 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.
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.
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.
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.
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.
194 | P a g e
List all currently configured git remote -v
remote repositories:
195 | P a g e
mark a significant
changeset, such as a
release:
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.
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.
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.
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.
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.
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.
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:
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:
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
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:
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:
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:
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
Now Push the branch to your remote repository, so others can use it:
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.
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.
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
Duration: Usually an hour per week of iteration–e.g. a two-week sprint kicks off with a two-hour planning meeting.
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.
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!
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?
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:
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
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.
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:
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.
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.
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.
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
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
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
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