0% found this document useful (0 votes)
26 views90 pages

Selenium Notes

The document provides an overview of Java concepts for Selenium testing including Java environment setup, program structure, syntax, fundamentals like variables, operators, flow control, string handling, exceptions, OOP concepts like inheritance, polymorphism, abstraction and encapsulation.

Uploaded by

Venkat
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
0% found this document useful (0 votes)
26 views90 pages

Selenium Notes

The document provides an overview of Java concepts for Selenium testing including Java environment setup, program structure, syntax, fundamentals like variables, operators, flow control, string handling, exceptions, OOP concepts like inheritance, polymorphism, abstraction and encapsulation.

Uploaded by

Venkat
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 90

JAVA For Selenium

Java Environment Setup

Java Program structure and java syntax

a) Java fundamentals / Basics


1-Comments
2-Data Types
3-Modifiers
4-Variables
5-Operators
7-Flow Control
i) Conditional Statements
ii) Loop statement
8- String Handling
9- Input and Output Operations, File Handling
10- Methods
i) Built in Methods
ii) User Defined Methods
11- Exceptional Handling

b) JAVA OOPS
1- Inheritance
2- Polymorphism
3- Abstraction
4- Encapsulation
JAVA Notes

System.out.println(“ Define ”);

System – class (built in class)


Out – object
Println – Method

Code block – comprised of curly locks - {}

Object: It is an entity that has states and behaviors is known as object


Example: pen, chair, table.
Dog is an object
Properties are color, height, weight
Behaviors are move, jump, bark etc.

Class: class is a template or blueprint from which objects are created.

- A class is a group of objects that has common properties

Method: An operation on object


Data type: Data type is a classification of the type of the data that a
variable or constant or method can hold in computer program e.g. char, int,
Boolean etc.

In JAVA there are two types of datatypes;

1-Primitive data types -- 8 types of datatypes


2-Non-primitive data types – 2 types of datatypes

Primitive data types are:

Integer data types

1)-Byte (8 bits)
Example: byte a =10;

2)-Short (16 bits)


Example: short b =10000;

3) - int (32 bits)


Example: Int c =100000;

4) - long (64 bits)


Example: long d =100000L

Relational Data types (Numbers with decimal places)


5) - float (32 bits)
Example: float a =1.2;

6)-double (64 bits)


Example: double b =19.234567;

Characters

7) - Char (16 bits)


Example: char a =’z’

Conditional
8) - Boolean
Example: Boolean a = true

Non – Primitive Data types

Non-primitive data types are objects, String and arrays


Example: button = new button (“Ok”);

Datatypes are two types: --- Look for more information

 Variable – for variable you can change the value in the code
 Constant – for constant you cannot change the values and it is final,
once declared. E.g., final int a = 10; (final is a keyword and needs to declare
before variable)

Wrapper class:

In order to use primitive data types as Objects, we have to use Wrapper Classes which help us in
converting the primitive data types into objects.

 The below are the different wrapper class data types:

Java Variables:
What is variable – a named memory location to store the temporary data
within a program

Java supports explicit declaration (only) of data and we need to specify


the data type before declaring variables or constant
Variables are naming restriction: when declare the variable in lower case
then used in the lower case only and not to use in upper case meaning using
the variable in one case only throughout the program

- Java variable names should start with a letter (alphabets) or $ (dollar


sign) or _ (underscore) e.g.
Myvar or myvar or $myvar or _myvar or myvar7 -- ( Correct)
7myvar or *myvar or (myvar – (incorrect)

- Variable names should not match with java keywords or reserved words
and must be unique in the scope of declaration meaning no duplications of
variable and not must exceed 255 characters e.g.

int a; -- correct
int new; --- incorrect
Types of variable in JAVA are:

1- Local Variables – declared in inside the methods are local variables or in


the blocks and we can use in those blocks only.
2- Instance Variables – are declared in the class but can be called outside
of a method or any code block.
3- Class/Static variables – are declared as static and these cannot be
declared as local and can be called inside and outside of the block but
declared outside of the main method only

Advantage of instance variable over local variable is you can access the
variable outside the block or inside any block

Java opertors

- Arithmetic Operators e.g. addition and string concatenation +,


Subtraction and negation -, Multiplication *, Modulus (Remainder) %,
division /, increment ++, decrement – (Return value based)

- Relational Operators e.g. equal to == , Not equal to != , Greater then >


, Less than < , Greater than equal to >= , Less than equal to <= (Return
true or false based upon the condition)

- Assignment Operators e.g. equal to = , add and assign += , Subtract


and assign - = , Multiply and assign *=
- Logical Operators e.g.
Logical Not operator  !

Operand 1 Operand 2 Result


True True False
True false True
False true true
false false true

Logical And Operator  &&

Operand 1 Operand 2 Result


True True True
True false False
False true False
false false false

Logical Or operator  ||

Operand 1 Operand 2 Result


True True True
True false True
False true True
false false false
Example 1:

Boolean a = true, b = false;


System.out.println(!(a&&b)); // true
System.out.println(a&&b)); // false
System.out.println(a||b)); // true

Example 2:

Int a =1000, b =5000, c=700;


If (!(a>b) && (A>c)){
System.out.println(“A is a big number”)
}
Else{
System.out.println(“A is not a big number”)
}
/// A is a big number  will print
Conditional statements:

Note usage of conditional statements in test automation: As per QA


conditional statements are used for verification points and error
handling

Flow Control: Conditional statements and loop statements

Type of Conditional Statements in Java:

- If Statement

- Switch Statement

Types of conditions in java are as follows:

 Single Condition (Positive or Negative conditions)

Positive example: if (a>b) {sysout ()}

Negative example: if (! (a<b)){Sysout ()}

 Compound conditions e.g. if ((a>b) && (a>c)) OR ((a>b) || (a>c))

 Nested Condition e.g. if (a>b) {if (a>c) {if (a>d)…n number of conditions
but it will check one by one condition and then go forward

Usage of Conditional Statements


 One way condition meaning without else part OR Execute a block of
statements when condition is true e.g. if (Condition e.g. a>b)
{statement}

 Execute a block of statement when condition is true otherwise execute


another block of statements e.g. if (Condition) {statements} else
{Statements}

 Decide among several alternates block of code based on the condition OR


(Else if structure)
E.g. if (Condition) {Statements}
Else if (condition) {statements}
Else if (Condition) {statement}
Else {statements} // if all the statement are all false then else condition
will execute without the condition

Execute a block of statements when more than one condition is true


(Nested if)
E.g. if (condition) {
If (condition) {
If (condition) {
Statements
}}}
For example:

Int a =100, b=90, c=80, d=70;


If (a>b) {
If (a>c) {
If (a>d) {
System.out.println(“A is a big number”);
}
Else {
System.out.println(“A is not a big number”)
}
}
Else {
System.out.println(“A is not a big number”)
}
}
Else {
System.out.println(“A is not a big number”)
}

Above example by Compound condition:

If ((a>b) && (a>c) && (a>d))


{
System.out.println(“A is a big number”);
} else {
System.out.println(“A is not a big number”);
}

Advantage of nested condition over compound condition is that we can write


multiple else parts and in compound condition we can write single else part.

Decide among several alternatives (using switch statement)


Syntax:
Switch (expression) {
Case value: statements
Break;
Case value: statements
Break;
Case value: statements
Break;
Default: Statements (other than above)
}
Example:

Char grade = ‘A’;


Switch (grade) {
Case ‘A’:
System.out.println(“Excellent”)
Break;
Case ‘B’:
System.out.println(“Well Done”)
Break;
Case ‘C’:
System.out.println(“better”)
Break;
Default:
System.out.println(“Invalid”)
}

Java Loop Statements and String Handling

- Loop Statements – for repetitive execution


1-For Loop
2-While Loop
3- Do While Loop
4- Enhanced For Loop (For each loop) – used by arrays

For Loop

Description: It repeats a block of statements for a specified number of


times.
Syntax:
For (startValue; endValue; increment/decrement) {
Statement;
}
Example 1: Print 1 to 10 numbers
For (int i =1; i<=10; i++) {
System.out.println(i);
}

Example 2: Print 1 to 10 numbers except 7


For (int i =1; i<=10; i++) {
If (i ! =7) {
System.out.println(i);
}
Example 3: Print 1 to 10 numbers except 7
For (int i =1; i<=10; i++) {
If ((i ! =4) &&( i!=7)) {
System.out.println(i);
}

While Loop – It repeats a block of statement while condition is true


Syntax:

Int i=1; // Initialization


While (i<5) { // condition
System.out.put(“i”) Statements
i++
}

Do while loop: It repeats a block of statement while condition is true and at


least executes once irrespective of the condition

Syantax:

Int i =1; /// Initialization


Do
{
system.out. println(i)
i++
}
While (i<=5);
}

Enhanced for Loop: It executes all elements in array


Syntax:
Array Declaration;
For (declaration: Expression/Array) {
Statements
}

Example:
String languages [ ] = {“C”.”Cobol”,”Java”,VBScript”}
For (String Lang: Languages) {
System.out.println(lang);
}
Example 2:

Int a=10,b=20;
Int math = new int [3];
Math[0] = a+b;
Math[1] = a-b;
Math[2] = a*b;
For(int ma : math){
System.out.println(ma);
}

String Handling in java

What is a string  string is a sequence of characters written in double


quotes.
- String may have alphabets, numeric values, and special characters.
- String is an object in java
Example: “Canada” , “1234” , “Canada123” , “Canada*123”

Numbers :

Integer – Byte, short, int, long


Floating point/decimal value – float, double
Character – char
Logical Values – Boolean (true or false)
String type data - String

Operations on String:
- String + String - Concatenation by ‘+ ‘operator
- String + int  Concatenation by – concat method
- Int + int  addition

Example:
String str1=”Selenium”;
String str2=”UFT”;
System.out.println(str1+str2); // Selenium UFT
System.out.println(str1.concat(str2));concat is a method //Selenium UFT
System.out.println(“Selenium”+1+1); //Selenium11
System.out.println(1+1+”Selenium”); //2Selenium
String Comparison

1) 2-way Comparison (true/false)


2) 3-way comparison (=/>/<) (0/>0/<0) are as follows :

a) String comparison using relational operator (==) supports 2-way


comparisons (true/False)
b) String comparison using equals method -- > supports 2-way
comparisons (true/False)
c) String comparison using compareTo() method  supports 3- way
comparisons (= / > /<)

Results Criteria for 3-way comparison:

a) If string1 – string2 then result is 0 (zero)


b) If string1>string2 then positive value (greater than 0 or depends
upon the compiler)
c) If string1<string2 then negative value

// for ANSI character codes (ASCI values)


-A to Z (65 to 90)  Capital letter
- a to z ( 97 to 122)  Small Letter
- 0 to 9 (48 to 57)  Numbers

Example:

String str1 = “SELENIUM”;


String str2 = “selenium”;
String str3 = “SELENIUM”;
String str4 = “zselenium”;

//String Comparison using relational operator


System.out.println(str1==str2); // false
System.out.println(str1==str3); // true

//String Comparison using equals Method


System.out.println(str1.equals(str2)); // false
System.out.println(str1.equals(str3)); // true

//String Comparison using compareTo() Method (in compareTo() first it will


take first letter and then second value to compare the string)

System.out.println(str1.compareTo(str2)); // Negative value


System.out.println(str1.compareTo(str3)); // 0 (zero)
System.out.println(str4.compareTo(str2)); // Positive value

JAVA Arrays

A Java array is an object that holds fixed numbers of values of single data
types (Only constant array in java)
- The length of array is established when array is created.
- Array length is fixed and index starts from 0 (zero)

Declaration of arrays:
Syntax:

DataType arrayName[]; // Creating array


arrayName[] = new datatype[size]; // define size
arrayName[0] =value; //assign value
arrayName[1] =value; //assign value

Example: 1st method or format for displaying array

Int a []; // create array


a=new [3]; // define size or length
a [0]=10; // assign values
a [1]=20;
a [2]=30
a [3] = 40; // it will not show any error but on run time it will show error as
we declare only 3 in the array.
system.out.println(a[1]+a[2]); // 50

Example: 2nd method or format for displaying array

Int a [] =new int [3]; // create array and define size


a [0]=10;
a [1]=20;
a [2]=30
system.out.println(a[1]+a[2]); // 50

Example: 3rd method or format for displaying array

Int a [] = {10, 20, 30}; // declare array and assign value


system.out.println(a[1]+a[2]); // 50
Declaring different types of arrays

Note : You can use the same datatype in java meaning you can use the fixed
datatype.
Two types of array:
1- Single Dimensional array
2- Multi dimensional array

Example of 2 dimensional arrays:

Int array2 [][] = new {{1,3,5,7},{2,4,6,7}}


System.out.println(array2[0][0]); // 1
System.out.println(array2[0][1]); // 2
System.out.println(array2[1][2]); // 6

Assignment 2 dimensional array using nested for loop

Advantages of arrays are:

- Using array we can optimize the code, data code be retrieve easily
- we can get required data index position

Disadvantage of arrays are:

- We can store fixed number of elements only


- it does not change the size during execution

Input and output operations ( IO operations in JAVA)

There are three ways available for reading input:


1- Scanner
2- DataInputStream
3- BuffuredReader

Two concepts:

Reading Data- read input, read data from files


Reading Input- read input using input devices // this is a part of reading
data

Using java.util.Scanner -- > Java is project, util is project, scanner is class


(Scanner is the easier way and it includes many methods to check input is
valid to read)
Example:

Scanner scan = new scanner (system.in); // system.in is an input stream


System.ou.println(“enter your name”);
String name = scan.nextLine(); // storing in variable and nextLine is a
method and it is used for reading the string type data
// String name = scan.nex(); // IT WILL READ ONLY FIRST ENTERED
LETTER
System.out.println(“Your name” + name);
String city = scan.next();
System.out.println(“your city”+city);
System.out.println(“Enter your number”);

Int num = scan.nextint(); // for integer type


System.out.println(“your number”+num);

// same for all the datatypes

Char a = scan.next().charAt(1); // char At(1) meaning whatever you


entered in the input it will print it out only 2 character as it starts from index
0 (zero)
System.out.println(“your character”+a);

Boolean b = scan.nextBoolean(); // value will true or false only


System.out.println(“Your value”);
Transfer Statements

Transfer statements are used to transfer the flow of execution from one block of code to a different
block of code.

 Different types of Transfer Statements:

 break;
o The purpose of the break; statement is to come out of the statements based on some condition.
o Demonstrate the usage of break; statements inside any loop statement (Demonstrate here)
 continue;
o The purpose of the continue statement is to skip the current iteration of a loop based on some
condition and continue with the next iteration.
o Demonstrate on how to use continue; statements inside any loop statement (Demonstrate here)
 return
o Will be explained later, as it is used with methods.
 try, catch, finally
o Will be explained later, as it is used in Exception Handling

Java Exception handling

An exception is an event that occurs during execution of a program when


normal execution of the program is interrupted
- Exceptional handling is a mechanism to handle exceptions

Common scenarios where exceptions may occur are:

1- Scenario where arithmetic Exception occurs


If we divide any number by zero then arithmetic exception occurs
Example: int a = 10/0;

2- Scenario where NullPointerException occurs


If we have no value in any variable,performing operations by the variable.
Example: String s = null
System.out.println(s.lenght0)

3- Scenario where NumberFormatException occurs


The wrong formatting of any value.
Exmaple: String s = “abcd”;
Int a = Integer.parseInt(s);
System.out.println(a); // NumberFormatException

Example of converting from string to integer: Data conversion


String s1 =”12”;
String s2 = “14”;
Int a = integer.parseInt(s1);
Int b = integer.parseInt(s2);
System.out.println(a+b);
}

Example:
Scanner scan = new scanner (system.in);
System.out.println(“Read Two numbers”);
String s1 = scan.nextline();
String s2 = scan.nextline();
Int a = Integer.parseInt(s1); // if you do not covert from string to int then it
will concatinating
Int b = Integer.parseInt(s2);
System.out.println(a+b)

Data Conversion :

Whenever we read any type of data from files or application objects then
computer program considers the data as string type data, in order to
perform mathematical operators then we need to convert the data (convert
only numeric values only and not alphabets)

4- Scenario where ArrayIndexOutofbounds exception occurs


If we assign any value in the wrong index.
Example:
Int []a=new int[5];
a[10] = 1234
System.ou.println(a[10]);

How to handle the error:


I we cannot correct the error then we need to right the try catch block

Use try catch block

Syntax:
Try
{
Statements
------------
-----------
}
Catch (exception name) {
Syso(Exception handling code)
}

Example:

Int a =10;
Int b=0;

Try
{
Int result = a/b;
System.out.println(result);
}
Catch(ArithmaticException e){
System.out.println(“dived by zero error”);
}
System.out.println(“Hello”);
System.out.println(“Selenium”);

Int c[]=new int [4];


Try
{
C[7]=100;
System.out.println(c[7]);
}
Catch(ArrayIndexOutOfBoundsException e2){
System.out.println(“Array index error”);
}
System.out.println(“HELLO”);
}
File Handling
Using file class (Predefined or build in class) we can handle computer files

Using file class we can create any data type of file and treat them as text
files only e.g. word ,excel etc. You can create excel or word file too but you
cannot enter the data in to the file

Example:

//Create a Folder on to your desktop


File fileObject = new File (“c: /Users/lenovo/Desktop/ABC”);
FileObject.mkdir();

//Check the folder if exist or not


File fileObject = new File (“c: /Users/Lenovo/Desktop/ABC”);
Boolean a = fileObject.exists();
If (a==true){
System.out.println(“Folder exist”){
Else{
System.out.println(“folder not exist”)}

// Delete a Folder
File fileObject = new File (“c: /Users/Lenovo/Desktop/ABC”);
fileObject.delete();
systemout.println(“folder deleted”);

// create text file

File fileObject = newFile(“c:/Users/Lenovo/Desktop/ABC/abc.txt”)


fileObject.createNewfile();
system.out.println(“Test file created”)

// to read the data from notepad file (txt file)


String line;
//FileReader purpose is to open the file in read mode
FileReader file = new FileReader(“c:/Users/Lenovo/Desktop/ABC/abc.txt”);
// Creating bufferedReader object by passing fileReader object
BufferedReader br=new BufferedReader(file);
While ((line = br.readLine())!=null){ // we are suing while loop as we do not
know that loop should run up to what condition.
System.out.println(line);
}
br.close();
file.close();
}
// Writing in txt file

//FileReader purpose is to open the file in read mode


FileReader file = new FileReader(“c:/Users/Lenovo/Desktop/ABC/abc.txt”);
// Creating bufferedReader object by passing fileReader object
BufferedReader bw=new BufferedReader(file);
String data = “welcome to Selenium”
bw.write(data);
bw.close();
}

// Reading writing from one file to another text file


String Line;
FileReader file1 = new FileReader(“c:/Users/Lenovo/Desktop/abc.txt”);
FileReader file 2= new FileReader(“c:/Users/Lenovo/Desktop/xyz.txt”);

BufferedReader br=new BufferedReader(file);


BufferedReader bw=new BufferedReader(file);
While((line=br.readline())!=null){
bw.write(line);
bw.newLine();
}
Bw.close();
}}

Constructors:--
the purpose of the constructor to simplify the process of initialization of the
variables.

Constructors are similar to methods, but have the below differences:

 Constructors have the same name as Class name


 Constructors are automatically called when an object is created for the
Class
 Constructors won't have any return type - Return types like void, int
etc won't be available for constructors
 Empty hidden Constructor will be called, when an object is created for
the Class not specified with explicit constructors
 Constructors simplify the initialization of variables 
 Demonstrate initialization of variables without using constructors -
Demonstrate here
 Demonstrate initialization of variables with constructors -
Demonstrate here

public class DemoClass {

public static void main(String[] args) {

Car benz = new Car();

benz.carModel = "Benz A-Class";


benz.startCar();

class Car {

String carModel;

public Car(){

System.out.println("Inside Car Constructor");

public void startCar(){

System.out.println("Starting Car: "+carModel);

this keyword
 The purpose of this keyword is to differentiate the instance variable
with the parameterized variables of methods/constructors.

 Using this keyword with Methods


 Demonstrate the program which don’t use this keyword - Demonstrate
here
 Demonstrate the advantage of using this keyword with methods -
Demonstrate here
 Using this keyword with Constructors
 Generally required for constructors, as constructors are automatically
called when objects are created and there by all the required variables
will be initialized automatically
 Similar to methods. Overloading Duplicate methods/constructor names
are allowed inside the same class, as long as their parameters count or
declaration or order of parameters are different.

Java Methods – User Defined Methods

Introduction to Java methods: a java method is a set of statements that


are grouped together to perform an operation.

Note: Methods are also called as function in programing language


- In structured programming (Ex: C language we use Functions (built-in and
User defined)
- In Object Oriented Programming (Ex: Java Language) we use methods
(built-in and User defined)
- Build in methods are limited and read only but user defined methods are
depends upon the user as it can be made as many as user wants.
- Whenever we want perform any operation multiple times then we choose
methods
Advantage of methods:

- Code Reusability, using methods we can reduce project code size.


- Code maintenance is easy (Modifications are easy)

Types of methods: Two types of methods

1- User Defined method


2- Built in method (Pre-defined) you cannot change the method name

Built in method (Pre-defined) – Java has library of classes and methods


are organized in packages
Example: Java.IO.Console
Java  project
IO  package
Console class

If we want import all the classes we will use  Import java.io.*;

In order to use built in methods we need to import packages/classes.

Java.lang package is automatically imported in every Java program

Using “import” keyword we can import packages/classes.

Categories of built in methods:

1-String methods
2-Array methods
3-Number methods
4-character methods

User defined methods:

Two types of user defined methods are as follows:

1-Method without returning any value – only performs operation with no


returning value.

Two types of calling are:


a) Calling methods by invoking object
b) Calling methods without invoking an object
Advantage: You can use the value in other methods or pass the value to
other methods

2-Method with returning value- Performs operation and return value

Two types of calling are:


a) Calling methods by invoking object
b) Calling methods without invoking an object

Note:
Calling External methods- Creating in other class and calling in other class
Calling internal methods – Calling methods in same class is called internal
methods

Examples:
1- Writing methods (with returning value)
//Write Methods (Before main methods)
//Call Methods (After main methods)

Syntax:1(a)
accessModifier returnType methodName(parameters-optional and use
comma and pass n numbers of parameters);{
--------
--------
--------
}

//Calling Methods
Syntax:
ClassName ObjectName = new ClassName();
//Call methods by invoking object
ObjectName.MethodName(Values of parameter if any);

Example:
Public class JavaMethods{
//User defined methods
Public int multiply (int a, int b, int c) {
Int result = a*b*c;
Return result;
}
Public static void main (String [] args) {
// Create Object

JavaMethods abc = new JavaMethods();


//Call methods
Int x =abc.multiply(10,25,35);
System.out.println(x);
}

1(b)- Method with returning value and calling the method without
object

Writing methods
accessModifier nonaccessModifier returnTypeName (Parameters){
Statements
-------------
------------
}

Calling methods without object

DataType variablename = className.methodName(Parameter)

Example:

Public class JavaMethods{


//User defined methods
Public static int multiply (int a, int b, int c) {
Int result = a*b*c;
Return result;
}
Public static void main (String [] args) {
//Call methods
Int x =JavaMethods.multiply(10,25,35); //classname and method name
System.out.println(x);
}

2 – Writing methods without returning any values


A) Call methods by invoking object
Syntax: for creating methods
accessModifier returnTypeNothing MethodName(parametres){
Statements
------
-----
}
Call
Create Object
ClassName objectName = new ClassName();
objectName.methodsName(values..);
Example:
Public void studentRank(int marks){
If(marks>=600){
System.out.println(‘Rank A”);
}
Elseif(marks>s=500){
System.out.println(“Rank b”);
}
Else{
System.out.println(“Rank C”);
}}
Public static void main (string[] args){
//Create Object
Javamethods obj – new JavaMethods();
//Call Methods
Obj.stdentRank(700);
}}

b) Call methods without invoking object


Syntax: for creating methods
accessModifier NonaccessModifier returnTypeNothing
MethodName(parametres){
Statements
------
-----
}
Call
ClassName.methodName(values..);
Example:
Public static void studentRank(int marks){
If(marks>=600){
System.out.println(‘Rank A”);
}
Elseif(marks>s=500){
System.out.println(“Rank b”);
}
Else{
System.out.println(“Rank C”);
}}
Public static void main (string[] args){
//Call Methods
Javamethods.studentRank(700);
}}
Calling External methods:
Calling the object from class1 to class 2 and creating the object of
class1 in class2 in within same package

Example 1: with invoking object and with returning value


Class1
Public class class1 {
Public int multiply (int a, int b, int c){
Int result = a*b*c;
Return result;
}
Public static void main (String [] args) {
}

Class2 (Calling in class2 or accessing in class2)


Public static void main (String [] args) {
//creating object
Class1 xyz = new Class1 ();
Int y = xyz.multiply(10,25,35);
System.out.println(y);
}}

Example 2: without invoking object and returning value


Class1
Public class class1 {
Public static int multiply (int a, int b, int c) {
Int result = a*b*c;
Return result;
}
Public static void main (String [] args) {
}

Class2 (Calling in class2 or accessing in class2)


Public static void main (String [] args) {
Int y = class1.multiply(10,25,35);
System.out.println(y);
}}

Example3: Method without returning value and calling the method by


invoking Object
Class1
Public void studentRank(int marks){
If(marks>=600){
System.out.println(‘Rank A”);
}
Elseif(marks>s=500){
System.out.println(“Rank b”);
}
Else{
System.out.println(“Rank C”);
}}
Public static void main (string[] args){
//Call Methods
Javamethods.studentRank(700);
}}

Class2
Public class class2 {
Public static void main (String [] args){
Class1 xyz = new class1();
xyz.studentRank(700);
}}

Example 4: Method without returning value and calling the method by


without invoking the Object

Class1
Public static void studentRank(int marks){
If(marks>=600){
System.out.println(‘Rank A”);
}
Elseif(marks>s=500){
System.out.println(“Rank b”);
}
Else{
System.out.println(“Rank C”);
}}
Public static void main (string[] args){
//Call Methods
Javamethods.studentRank(700);
}}

Class2
Public class class2 {
Public static void main (String [] args) {
Class1.studentRank (700);
}}

Java Built in methods

Note: Method name starts with small letters

Categories of built in methods

1- String methods
2- Number methods
3- Character methods
4 -Array methods

1-String Methods:

a) compareTo Method – Compares two string and support 3-way


comparison.

Result Criteria in 3-way comparison:-

If string 1 = string 2 then 0 (zero)


If string 1 > string 2 then positive value
If string 1 < string 2 then negative value

Result Criteria in 2-way comparison: - do not provide any value based


results

If string 1 = string 2 then true


If string 1 != string 2 then false (not equal to)

Example:
String str1 =”Selenium”;
String str2 =”SELENIUM”;
String str3 =”Seleniuma”;
String str4 =”Selenium”;
System.out.println(str1.compareTo(str2)); // positive value meaning >0
System.out.println(str1.compareTo(str3)); // Negative value
System.out.println(str1.compareTo(str4)); // both are equal value meaning
=0

equals() method – give the results in true or false


Compares 2-way comparison
Example:
String str1 =”Selenium”;
String str2 =”SELENIUM”;
String str3 =”Seleniuma”;
String str4 =”Selenium”;
System.out.println(str1.equals(str2)); // false
System.out.println(str1.equals(str4)); // true

Concat() methods : Concatenates two strings


Example:
String str1 =”Selenium”;
String str2 =”Testing”;
System.out.println(str1+str2); // operator for concatenating two strings
System.out.println(str1.concat(str2)); // concat is a method

charAt() method – returns a character by index


Example:
String str1 =”Selenium”;
System.out.println(str1.charAt(1)); // result will be e because index starts
from 0 (zero)

equalsIgnorecase() method – compares two string not considering upper


case or lower case
Example:
String str1 =”Selenium”;
String str2 =”SELENIUM”;
String str3 = “UFT”;
System.out.println(str1.equalsIgnoreCase(str2)); // true
System.out.println(str1.equalsIgnoreCase(str3));// false
Note: 2-way comparison

toUppercase() Method – Converts the values to upper case


Example:
String str1 =”Selenium”;
String str2 =”SELENIUM”;
String str3 = “SeLENIUM”;
String str4 = “Selenium123”;

System.out.println(str1.toUppercase()); //Convert to upper case


System.out.println(str2.toUppercase()); //Convert to upper case
System.out.println(str3.toUppercase()); //Convert to upper case
System.out.println(str4.toUppercase()); // do not touch the numbers and
coverts the alphabets only
toLowercase() Method – Converts the values to lower case
Example:
String str1 =”Selenium”;
String str2 =”SELENIUM”;
String str3 = “SeLENIUM”;
String str4 = “Selenium123”;

System.out.println(str1.toLowercase()); //Convert to Lower case


System.out.println(str2.toLowercase ()); //Convert to Lower case
System.out.println(str3.toLowercase ()); //Convert to Lower case
System.out.println(str4.toLowercase ()); // do not touch the numbers and
coverts the alphabets only

Trim() Methods – remove spaces from both sides of a string

Example:
String str1 =” Se lenium”;
String str2 =”SEL ENIUM ”;

System.out.println(str1.trim()); //Convert to Lower case


System.out.println(str2.trim()); //Convert to Lower case

Substring() Method – based on index


Example:
String str1 =” Welcome to Selenium Testing”;
System.out.println(str1.substring(11)); //it will count from the index from
11 onwards
System.out.println(str1.substring(11,19)); // to start from middle then start
index and end index

endsWith() method – ends with specified suffix and returns Boolean


results
Example:
String str1 =” Welcome to Selenium Testing”;
System.out.println(str1.endsWith(“Selenium Testing”)); // true
System.out.println(str1.endsWith(“Testing”)); // true
System.out.println(str1.endsWith(“Selenium”)); // false

Length() method – returns length of a string ( even spaces are also


countable)
Example:
String str1 =”Welcome to Selenium Testing”;
String str2 =”Testing”;
System.out.println(str1.lenght()); // 16
System.out.println(str2.lenght()); // 8

2) Number Methods

1) CompareTo() compares two integers and support 3-way comparison


//Integer Class wraps a value of primitive data type int in an object
// an object of integer contains a single field whose type is int
Example:
Int x=5;
Integer a=x;
System.out.println(a.compareTo(5)); //0
System.out.println(a.compareTo(7)); //-1
System.out.println(a.compareTo(3)); //1
}

2) equals() – Supports 2-way comparison


Example:
Int x=5;
Integer a=x;
System.out.println(a.equals(5)); //true
System.out.println(a.equals(7)); //false
}

3) abs() absolute value mean returns positive value but no rounding off
the value
Example
Double a =-10.234;
Double b =-10.784;
System.out.println(Math.abs(a)); // 10.234
System.out.println(Math.abs(b)); // 10.784

4) round()  Rounds the value to nearest integer.

Example
Double a =-10.234;
Double b =-10.784;
System.out.println(Math.round(a)); // 10
System.out.println(Math.round(b)); // -11

5) min ()  returns minimum value between two numbers


Example:
Int a =5;
Int b=8;
Double c =-10.234;
Double d =-10.784;
System.out.println(Math.min(a,b)); // 5
System.out.println(Math.min(c,d)); // 10.234
System.out.println(Math.min(10,14);//10  direct values without declaring
the variable

6) max() returns maximum value between two numbers or decimal


numbers
Example:

Int a =5;
Int b=8;
Double c =-10.234;
Double d =-10.784;
System.out.println(Math.max(a,b)); // 8
System.out.println(Math.max(c,d)); // 10.784
System.out.println(Math.max(10,14);//14  direct values without declaring
the variable.

7) random ()  generates a random number


Example:
System.out.println(math.random()); // 0.23456 and whenever you execute
then you will get a random number each time.

3) Character Methods

// the character class wraps a value of primitive data type char in an object.

1) isletter()  checks if weather the value is alfa byte or not


Example:
Char a =’z’; // single quote for char and double quote for string
Char b = ‘1’;
System.out.println(character.isLetter(a));//true
System.out.println(character.isLetter(b));//false
System.out.println(character.isLetter(‘d’)); // direct without declaring the
value

2) isAlphabetic() 
Example:
Char a =’z’; // single quote for char and double quote for string
Char b = ‘1’;
System.out.println(character.isAlphabetic(a));//true
System.out.println(character. isAlphabetic (b));//false
System.out.println(character. isAlphabetic (‘d’));

3) isDigit() checks the value is number or not


Example:
Char a =’z’; // single quote for char and double quote for string
Char b = ‘1’;
System.out.println(character.isDigit(a)); //false
System.out.println(character. isDigit(b)); //true
System.out.println(character.isDigit(‘*’)); //false (direct initialization and
validation)

4) isUpperCase()  checks weather the value is uppercase or not


Example: Boolean example
Char a =’z’; // single quote for char and double quote for string
Char b = ‘a’;
Char c=’1’;
System.out.println(character.isUpperCase(a)); //true
System.out.println(character. isUpperCase (b)); //false
System.out.println(character. isUpperCase (c)); //false
System.out.println(character. isUpperCase (‘*’)); //false (direct initialization
and validation)

5) isLowercase()  checks weather the value is lower case or not


Example:
Char a =’z’; // single quote for char and double quote for string
Char b = ‘a’;
Char c=’1’;
System.out.println(character.isLowerCase(a)); //false
System.out.println(character. isLowerCase (b)); //true
System.out.println(character. isLowerCase (c)); //false
System.out.println(character. isLowerCase (‘*’)); //false (direct initialization
and validation)

4- Array Methods (array object)


1-Length () - returns length of an array ( is not a method and it is a
property)
Example:
Int array [] = {10.20.30,40,50}
System.out.println(aray1.lengh); // 5

2-toString() – Prints an array ( without this method you can print via for
loop)
Example:
String array1 [] = {“selenium”,”UFT”,”RFT”,”Silktest”};
String str = Arrays.toString(array1); //Arrays is class and toString() is a
method
System.out.println(str);

Output will come as [“selenium UFT RFT Silktest]

3)- contains() – checks if the array contains certain values or not


Example: Boolean result
String array1 [] = {“selenium”,”UFT”,”RFT”,”Silktest”};
Boolean a = Arrays.asList(array1).contains(“UFT”); // true -
asList=property , contains=method.
Boolean b = Arrays.asList(array1).contains(“Java”); // false
System.out.println(a);
System.out.println(b);

Method syntax are as follows:


Object.method();
Classname.method();
Class or Object.property.method();

Java Inheritance and Polymorphism

Java OOPS: Object Oriented Programming system

Four fundamentals of OOPS are as follows:

1-Inheritance
2-Polymorphism
3-Abstraction
4-Encapsulation
Inheritance : It is a process of inheriting(reusing) the class
members(variables and methods(user defined methods but build in methods
you can use it anywhere) from one class to another class.

- Non static class members can only be inherited.


- The class where the class members are getting inherited is called as super
class or parent class or base class
- The Class to which the class members are getting inherited is called as sub
class or child class or derived class
- The inheritance between Super class and sub class is achieved using
extends keyword.

How to create static class members?


- Using static non access modifier

How to access static class members?


Using class name.method name

How to access Non static class member?


-using Object/Instance of the class.method name

Example:

Public class Inheritance {


//Create and declare static variables
Static int a =10, b=20;

//Create and declare non-static variables


Int c=30, d=40;

//Create a static method with returning a value


Public static int add () {
Int result=a+b;
Return result;
}
//create a static method without returning a value
Public static void multiply () {
System.out.println(a*b);
}
//Create non static method with returning a value
Public int add2 () {
Int res = c+d;
Return res;
}
//Create non static method without returning a value
Public void multiply2 () {
System.out.println(c*d);
}

Public static void main(String[] args){


//Access static class members
System.out.println(inheritance.a); //10
Int x= inheritance.add();
System.out.println(x); //30
Inheritance.multiply(); // 200

//Access Non static class members


Inheritance obj = new Inheritance();
System.out.println(obj.c); //30

Int y = obj.add2()
System.out.println(y); // 70
Obj.multiply2(); //1200
}
}

Three types of inheritance

1- Single inheritance
Example:
ClassB extends ClassA (ClassA is a super class)

2-Multi level Inheritance


Example:
ClassB extends ClassA (ClassA is a super class)
ClassC extends ClassB (ClassC sub sub or child)

3- Multiple Inheritance (* Java does not support due to different parents


class and it can be clashes of same methods)
ClassB extends ClassA
ClassB extends ClassD
Example for Single inheritance:
Class 1:

Public class ClassA {


Int a =10;
Int b=20;

Public void add(){


System.out.println(a+b);
}
Public static void main(String[] args)
ClassA objA = new ClassA();
System.out.println(objA.a); //10
objA.add()//30
}}

Class 2

Public class ClassA {


Int a =100;
Int b=200;

Public void add(){


System.out.println(a+b);
}
Public static void main(String[] args)
ClassB objB = new ClassB();
System.out.println(objB.a); //100
objA.add()//300
}}

Example for Multi-Level Inheritance:

Class 1:

Public class ClassA {


Int a =10;
Int b=20;

Public void add(){


System.out.println(a+b);
}
Public static void main(String[] args)
ClassA objA = new ClassA();
System.out.println(objA.a); //10
objA.add()//30
}}

Class 2

Public class ClassB {


Int a =100;
Int b=200;

Public void add(){


System.out.println(a+b);
}
Public static void main(String[] args)
ClassB objB = new ClassB();
System.out.println(objB.a); //100
objA.add()//300
}}

Class 3

Public class ClassC extends ClassB{


Int a =1;
Int b=2;

Public void add(){


System.out.println(a+b);
}
Public static void main(String[] args)
ClassC objC = new ClassC();
System.out.println(objC.a); //1
objC.add()//3
}}

Note: In multilevel inheritance local class members will have the preference
to execute first if class members are same in all classes and after local then
parent class will have preference and then grandparents class will have
preference

Another example for accessing the class1 class members in class2

Class 1:

Public class ClassA {


Int a =10;
Int b=20;

Public void add(){


System.out.println(a+b);
}
Public static void main(String[] args)
ClassA objA = new ClassA();
System.out.println(objA.a); //10
objA.add()//30
}}

Class 2

Public class ClassB {


Int a =100;
Int b=200;

Public void add(){


System.out.println(a+b);
}
Public static void main(String[] args)
ClassB objB = new ClassB();
System.out.println(objB.a); //100
objB.add()//300

ClassA objA = new ClassA(); // we are making an object of class1 in class2


System.out.println(objA.a); //100
objA.add()//300
}}

Another example by accessing the class1 (package1) to another


class2 (package2)

Class 1:

Public class ClassA {


Int a =10;
Int b=20;

Public void add(){


System.out.println(a+b);
}
Public static void main(String[] args)
ClassA objA = new ClassA();
System.out.println(objA.a); //10
objA.add()//30
}}

Class2

Import xyza.ClassA; // in order access a class1 of different package we need


to import the classA in Class C

Public class ClassC{


Public static void main (String [] args{
ClassAobj=new ClassA();
System.out.println(obj.a); //100
Obj.add(); //300
}}

Another example if you want to access the variable and methods of class1
(package1) in Class2 (Package2) by making a class2 object but accessing
the variable and methods of class1(package1)

Class 1:

Public class ClassA {


Int a =10;
Int b=20;

Public void add(){


System.out.println(a+b);
}
Public static void main(String[] args)
ClassA objA = new ClassA();
System.out.println(objA.a); //10
objA.add()//30
}}

Class2

Import xyza.ClassA; // in order access a class1 of different package we need


to import the classA in Class C

Public class ClassC extends ClassA{ // by extending the ClassA to C


Public static void main (String [] args{
ClassC obj=new ClassC();
System.out.println(obj.a); //100
Obj.add(); //300
}}

Polymorphism
Existence of object behavior in many ways (forms) is known as
polymorphism
Derived from Greek word:
Poly – many
Morph – ways

Two types of polymorphism:

1-Complie time Polymorphism / Static binding / Method Overloading


2- Run time Polymorphism / Dynamic binding / Method Overriding

1-Complie time Polymorphism / Method Overloading

If two or more methods with same name in the same class but they differ in
following ways:
- Number of arguments or parameters
- Type of arguments

Example:

Public class Class1 {

Public void add (int a , int b){


System.out.println(a+b);
}
Public void add (int a, int b, int c) {// number of arguments are different but
class name is same

System.out.println(a+b+c);
}
Public void add (double a , double b){ // type is different but class name is
same
System.out.println(a+b);
}
Public static void main (String[] args){
Class1 obj = new class1 ();
obj.add(10,20,30); // object access methods based on their parameters
value and this is accessed by second method
obj.add(10,20); // Access by first method
obj.add(1.23,2.34) // Access by third method

Note: above concept is method overloading where same name in the


same class with different parameters (types of arguments or
numbers of arguments)

2- Run Time Polymorphism / Method Overriding

If two or more methods are available in the super class and sub class

Example:
Public class Class1 {
Public void myMethod(){
System.out.println(“Selenium for test automation”);
}
Public static void main (String[] args){
Class1 obj1=new Class1 ();
Obj1.myMethod();

Create another class2

Public class Class2 extends Class1 {


Public void myMethod(){
System.out.println(“UFT/QTP for test automation”);
}
Public static void main (String [] args){
Class2 obj2=new Class2 ();
Obj2.myMethod();

Output will be: UFT/QTP for test automation (Due to home or local method
is present that is why first it will access the home method and if there is no
home method then it will access the parent method)

Note: above concept is method overriding where same name with


same parameters
Java abstraction and encapsulation

Abstraction: It is a process of hiding implementation details and showing


only functionality to the user.

OR,

Data abstraction is the process of hiding certain details and showing only


essential information to the user.
Abstraction can be achieved with either abstract classes or interfaces (which
you will learn more about in the next chapter).

The abstract keyword is a non-access modifier, used for classes and methods:

 Abstract class: is a restricted class that cannot be used to create objects


(to access it, it must be inherited from another class).

 Abstract method: can only be used in an abstract class, and it does not


have a body. The body is provided by the subclass (inherited from).

Two types of methods in JAVA from abstraction point of view are:

1- Concreate methods or Complete methods – The methods which are


having body.

Syntax:
Public void add () {
Statements
-----------
}

2- Abstract methods – the methods which are not having body (If we
know the method name but not known the method functionality).

Syntax:
Public abstract void add ();  abstract is a keyword

- Java Class contains 100 percent concrete methods


- Abstract class contains one or more abstract methods (If abstract methods
present in the class then we call it as abstract class)
- Abstract class cannot access by creating object in the same class but can
be access in sub class by declaring it and then access by creating object and
coming back to the parent class and access them by making object as in sub
class we already declare the abstract methods and due to that we can access
the abstract method in parent class.

Example1:
Class 1 (having 10 methods)
10 methods are concrete methods then it is called java class

Example2:
Class2 (having 10 methods)
5 methods are concrete methods and 5 methods are abstract methods and it
is known as abstract class

Example1:
Class 3 (having 10 methods)
All 10 methods are abstract methods then it will call as abstract class

Abstract class example:


Package JavaExamples;
Public abstract class Bikes {// if one method is abstract then class should
be abstract too.
Public void handle (){
System.out.println(“Bikes have handle”)}

Public void seat () {


System.out.println(“Bikes have seat”)}

Public abstract void engine (); //Eclipse will show error and give you a
option to change to abstract class.

Public abstract void wheels ();

Public static void main (String [] args) {

Another sub class of bikes:

Package javaexamples;
Public class HeroHonda extends Bikes{
Public void engine(){
System.out.println(“Bikes have engine”);
}

Public void wheels () {


Syste,.out.println(“bikes have wheel”);
}

Public static void main (string [] args) {


HeroHonda abc = new HeroHonda();
abc.engine();
abc.wheels();
abc.seat();
abc.handle();

}}

Note:

QHow to inherit Abstract class method?


-We have to implement abstract methods in sub class then we can use in
sub class, as well as in parent class.
Q How to use/access in abstract class?
- Create Object using Sub class

Interfaces
- Selenium IDE has integrated development environment
- Selenium WebDriver has programming Interface but no IDE
- UFT/QTP has both IDE and programming Interface.

Java Interfaces

Interface is a java type definition block is 100% abstract.

Java Class Vs Abstract Class

Java Class: Java classes have 100% concrete methods

Abstract classes have one or more/all abstract

Class Vs Interface

Java Class: Java classes have 100% concrete methods


Interfaces have 100% abstract method

Abstract Vs Interface

Abstract classes have one or more/all abstract

Interfaces have 100% abstract method

Note:
- All interface methods are by default public and abstract
- Static and final modifiers are not allowed in interface methods (Only static
and not non-static)
- In interfaces variables have to initialize at the time of declaration only
For Example: int a; a=100; (incorrect); int a=100; (Correct)
- In interfaces variables are public and final by default
- Interfaces are going to be used using “implements” keyword.

Example for JAVA Interface: (hierarchy)


Java Project
Java Package
Java Class
Example: (We cannot use objects in interfaces)
Package JavaExample;
// No concreate methods in interfaces
Public interface Interface1{
Public void engine ();
Public void wheels();
Public void seat();
Public void handle();
//accessing from sub class to interface meaning we declare the methods in
sub class and then accessing the methods by creating the object of that
class to the interface.
ClassNew abcd = new ClassNew();
Abcd.handle();
Abcd.engine();
Abcd.wheels();
}}

}
//Reuse methods from interface to Class

Create a new class with ClassNew

Package javaExamples;
Public class ClassNew implements Interface1 {
// it will show the error on ClassNew to implement the unimplemented
methods
//after clicking then all the interfaces will come on the sub class
//give a body to all methods
Public void engine () {
System.out.println(“Bikes have engine”)
}
Public void wheels () {
System.out.println(“Bikes have wheels”)
}
Public void seat () {
System.out.println(“Bikes have seat”)
}
Public void handle () {
System.out.println(“Bikes have handle”)
}
Public static void main (String [] args){
ClassNew obj=new ClassNew();
Obj.seat();
Obj.engine();
Obj.handle();

Note:
1- From class (Concreate class or Abstract class) to class we use extends
keyword
2- From interface to class we use implements keyword to re-use the
methods
3- Interface to interface  we cannot access the methods from interface to
interface

Encapsulation

Note: encapsulation is generally not used by QA and used by developer for


field validation e.g. for phone number it is supposed to accept the numeric
value only and character and if user tries to enter the char data then it will
reject the data.

Encapsulation: It is a process of wrapping code and data in to a single unit.


Ex: Capsule (mixer of several medicines)

Encapsulation is the technique making the fields in a class private and


providing access via public methods.
OR,

The meaning of Encapsulation, is to make sure that "sensitive" data is hidden


from users. To achieve this, you must:

 declare class variables/attributes as private


 provide public get and set methods to access and update the value of
a private variable

Advantage:
- It provides control over the data
- By providing setter and getter method, we can make a class read only or
write only
Example:
Package JavaExamples;
Public class Class1{
Private string name =”test Automation”;
Public string getName(){
Return name;
} public void setName(){
Name = newName;
}
Public static void main(String[] args){
Class1 obj = new Class1();
System.out.println(obj.getname);
}

// create another class and this class will be read only due to getter method
Packages javaExamples;
Public static void main(String[] args){
Class2 abc=new Class2();
abc.setName(“Selenium testing”); // for writing the value
System.out.println(abc.getName()); // for reading the value (can be used
read or write)
}}

Modifiers :

Two types of modifiers are in java are:


1- Access modifiers
2- Non – access modifiers

1.1 - Access Modifiers are: we use access modifiers to define access


control for classes, methods and variables.

 Public access modifiers are accessible everywhere even outside of the


class , inheritance e.g. public class sample{ }
 Private access modifiers are accessible in within class

 default ( with small d)access modifier within package – if we do not


specify any modifier then it is treated as default and this can be accessible
within package
 protected ( with small p) is accessible within package , outside of the
package but though inheritance.

Access Within Within Outside of Outside of the


Modifier Class Package the package(everywhere)
package(by
sub class)
private Y N N N
default Y Y N N
protected Y Y Y N
public Y Y Y Y

Note: As a QA public is only used as we are using in testing environment


and developers used other access modifiers are used as they are developing
the code.

2.1 - Non-Access Modifiers

 static modifier- static modifier is used to create classes, methods and


variables
static in methods – means no need to create the object and without
invoking the object , we can access the methods
static in variables – if you need to make a variable of a classes only then
we need to use the static variables ( Class level variable)
final modifier – for using a final modifier for finalizing the classes ,
methods and variables meaning it will fixed and in future you cannot change
the value
abstract modifier- is used to create abstract classes and abstract
methods ( incomplete classes & methods)
Software testing:
Testing can be done in two ways:

- Using Manual Testing

- Test Automation

Advantages and disadvantages of manual testing

Advantages of manual testing:

- No test tool cost


- Can be used for dynamically changing UI design
- No environment Limitation
- Useful for short term project
- For usability testing manual testing is the only option

Disadvantages of manual testing


- It takes more time or more human resources or sometime both
- Performance testing is impractical.
- Comparing large amount of data is difficult
- Data driven testing and batch testing take more time and effort
- Checking GUI objects sizes and color combinations is difficult to validate
- Less test coverage (e.g. to test the phone number of 10 values and it will
take 1000 of test cases)
- Less accuracy (human can do mistake as compare to tools)

Advantages and disadvantages of test automation

Advantages:

- Tools are faster than human in test execution


- Reusable: Sanity, Regression
- Repeatable by different test data: data driven tests
- Reliable e.g. calculating again and again and if we provide correct logic
then tool provide correct calculation
- Programmable: we can programed it by using conditions and loops
- Comprehensive: execute batch testing (saves time and effort)
- For performance testing only automation is only possible and not manual
e.g.1000 users logged in together

Disadvantage of test automation:

- Not suitable for short term project


- 100 % test automation is not possible
- All types of testing is not possible ex: usability testing
- Lack of knowledge (needs to learn programing language)
- Debugging issue (sometime scripts failed and did not show any meaningful
message)
- Test tools have their own defects, so we may not get desired benefits.
- Environment limitations (Selenium do not support windows based
application)
- Not suitable for dynamically change applications or User Interface designs

Types of test tools

a) Business Classification
- Vendor Tools e.g. HP tools, test complete etc.
- Open source tools e.g. Selenium, Jmeter, Bugzilla etc.
- In house tools

b) Technical Classification:
- Functional and regression test tools – UFT, RFT, Silk test, Selenium
etc.
- Performance test tools – Loadrunner, Jmeter , RPT , Silk Performer
- Test management tools – ALM/QC, JIRA etc.
- Defect management tools – Bugzilla, PR- tracker etc.

Automation test life cycle methodology (ATLM)

a) Decision to automation

Test type: Functional testing or performance testing ( based on


testing)
Time: for complex testing
Budget: if you have a budget
Customer interest: it depends upon cx
Maintenance: if project is longer for e.g.10yrs or more then
maintenance is easy

b) Test tool Selection:

Test Type: Functional testing or performance testing ( based on


testing)
Application environment: if it is web based or windows based or UNIX,
Linux or any other environment.
Cost:
Available Resource
Technical Support

Testing Planning and test Developments

- Configure the tool


- Analyzing the AUT
- Select test cases of automation
- Sanity (tests that we have to execute on every build)
- Regression (tests that we have to execute on every modified build)
- Data driven (tests that we have to execute using multiple sets of test
data (data driven)
- Select Automation framework and implement
- Developing tests using recording or writing test scripts manually
- Enhancing test using tool IDE and programing features (condition and
loops)

d) Test Execution:
- Single test run
- Batch testing (executing series of batch)
- generating test reports

e) Analyzing test results and reporting defects

f) Maintenance of automation resources e.g. library files , Object


repository , XML files etc.

Software Test Process / Selenium Test Life cycle:

1-Test Planning
2-Test Design
3-Test Execution
4-Test Closure

UFT Test Process:

1- Planning
2- Generating Basic tests
3- Enhancing Tests
4- Running and debugging Tests
5- Analyzing Test Results
6- Reporting Defects
Selenium Test Process
Phase I – Test Planning (Tasks)

- Get application Environment details (UI designs and Database) from


development team
- Analyze the Application under test (AUT) in terms of UI elements
identification (Using Selenium IDE recording feature OR using Firebug to use
for inspecting UI elements)
- Select test cases for automation (Sanity, functional and regression)
- Select Framework (Test Ng) and configure

Phase II – Generating Basic Tests

In UFT:
- Object Repository based test design (Recording, Keyword Driven
methodology)
- Descriptive Programing (Static, dynamic Programing)

In Selenium:
- Using recording feature in selenium IDE / Type test scripts using UI
element identifiers and selenium commands
- Write test scripts using UI elements locators in Selenium RC (Out dated)
- Write test scripts using UI elements locators in WebDriver interface

Note: In Selenium no object repository so no centralized maintenance of


objects or elements

Phase III – Enhancing tests

1-Insert Verification points


- WebDriver: using java conditional statements
- WebDriver: using Test Ng / Junit assertion methods (can match
expected with actual value)
- Selenium IDE: using Assert and verify commands
2- Add Comments: we use comments for readability (understand) of the
code or to make the code disable
3- Parameterization: Replacing constant (fixed) values using parameters
(we use parametrization in data driven testing [testing same functionalities
using multiple values is known as data driven testing and used to test
positive and negative values])
4-Synchronization: It is the process of matching speed of test tool and
application (two things) e.g. two devices or two applications
5- Working with files
6- Error handling: handling expected and unexpected errors e.g. when we
use unexpected values for negative value or when fetching the data from file
then come across unexpected errors

IV – Running tests and debugging Tests

Running Test: Running or executing tests (mandatory)

1-Single Test Run


2-Batch Testing Using Junit or Test Ng Framework, we can execute test
batches (Group of test cases)

Debugging tests: (Optional)


Locating and isolating errors though step by step execution and not required
for all test cases, only for some test cases, for example:
1. Test case is not showing any errors and providing correct output (Not
required)
2. Test case is showing any errors then correct the errors first (debugging
is optional)
3. Test case is not showing any errors and not providing correct output
(debugging is required) e.g. x= a*b; here we have to addition but we are
using multiplication operator insisted of addition and that is a error created
by human

Phase V – Analyzing Test Result

Note: Selenium does not provide detailed test reports (summary only) and
using either Junit or Test Ng we can get detailed test reports

Status of test result is functional test automation.


When we get a status as:

 Pass (If expected result = Actual Result)


 Fail (If expected result ! = Actual Result)
 Done (Test executed without error , No verification points)
Example: measuring execution time in performance of the application
 Warning (If any interruption during test execution e.g. database)

Define Test Result: (Before test execution)

- WebDriver does not have any built in test report generator


- Using programmatic statements we can generate test results
VI- Reporting Defects

Note: Selenium does not integrate directly with any other tool for test
management or defect management tool (Double check)

Functional test automation Defect Management tool


Selenium Manual ( no support) or whatever
your company is using for defect
reporting e.g. then use excel
Selenium Bugzilla, JIRA or any tool
Selenium Notes

What is Selenium?

- It is suite of software tools to automates web browsers


- Selenium is a set of API’s that helps us to automate the browser
- In Selenium you have jar files and API’s that you configure it
- It is an open source tool, No license fee and anybody can download
- Selenium is developed on java technology

Advantages of Selenium:

- Selenium supports various operating environment (windows, UNIX, Linux,


mac)
- Selenium supports various browsers (chrome, IE, Firefox, opera, Safari)
- Selenium supports various programing and scripting languages (Java,
python, Ruby, C#, Perl)
- It supports parallel test execution
- It uses less hardware resources

Disadvantage of Selenium:

- Since it is open source tool, No reliable technical support


- No Other tool integration for test management
- Difficult to use
- New features may not work properly
- Deployment of selenium is difficult then UFT and RFT tools e.g. installation
and maintenance

Selenium supporting platforms/Environments

- Application environment

- It does not support command user interface based application


- It does not support I – tier, ii-tier (desktop applications or windows
based)
- It supports only web applications
- Mobile applications which are having web forms
- Operating Environment

- It support windows, UNIX, LINUX, MAC operating environment

- Web Browsers
- IE, Mozilla fire fox, Chrome, opera, Safari

Selenium Suite of Tools:

- Selenium IDE (Integrated development Environment), it is a Firefox


add on, it is a prototyping tool

Feature:

- Record and play back


- Edit Test cases
- Execute a test case
- Execute a test suite (test batch)
- Write or type test scripts using User interface elements locators and
selenium commands
- Debugging test cases
- Export test cases to other programing and scripting languages

Limitations:

- It supports only on Firefox browser


- Data driven testing is not possible
- No Flow control
- No detailed results report

Difference between Selenium and UFT

Selenium UFT
Open Source, No License Vendor , HP , Cost
Support Web based applications only Supports Desktop and Web
Applications
Using elements Locators Based on Add ins only it supports
Supports Java, C# ,PHP ,Ruby, VB script only
Python ,Perl to create and enhance
tests
Supports windows , UNIX , Mac etc. Only windows operating system
operating environments
Supports web browser e.g. IE, It supports only IE for designing and
Chrome ,Opera , Firefox ,Safari for execution Firefox , chrome
Limited support for image testing Rich support for image testing
Difficult to use Easy to use
No reliable technical Support HP provides support
New features may not work properly New features will work properly
No Object repository , No centralized Centralized maintenance of Objects
maintenance of objects e.g. shared object repository
No authorized Certification HP conducts certification
No other tools integration ALM/QC can be integrated for test
management tool

Other tools or adds INS for Selenium:

- Firebug: It is Firefox add on used to inspect UI elements


- FirePath: It is an extension of Firebug, used to get xpaths

Frameworks:

- Junit
It is framework for unit testing and it can be used for Selenium functional
testing
Junit is used to execute test batches and generating reports

- TestNG (more powerful then Junit)

It is used to execute test batches and generating reports


It is has built in HTML, XML reports
What are frameworks?

Frameworks are generally created if you have to execute the test case which
are in 100’s or 1000’ in number and all those test cases are created by the
team members and if all the team members are adopting their own strategy
then there will be a different approaches altogether and that could lead to
duplication of work or no work. In order to avoid all those things, we need to
lay down the framework that who will do what things e.g. first writing the
test cases and after that layout those test cases in a automation framework
by creating methods and calling those methods etc.

- It lays the strategy that how we will be performing test activities by


selenium or any automation activities.
Selenium Coding with explanation :

Pre-requisite to crate Automated Tests:

1. Import WebDriver Libraries and Firefox driver library.


2. Create driver Object.
3. Using web element (object) locators (properties) and methods to write
object call statements.
4. Insert Java programmatic statements to enhance the scripts.

WeDriver driver= new FireFoxDriver();

- Meaning of the line is creating a firefox driver object in webDriver interface


- Left side webdriver interface and right side firefox driver class
- Launches firefox browser with blank url

WeDriver driver= new FireFoxDriver();


// WebDriver- Webdriver is itself is an interface (or programming
interface);
FirefoxDriver()- create firfoxdriver in webdriver interface ;
driver – it is an object (Creating a firefox driver object in webdriver
interface) and it will allow driver to get access of methoods in webdriver and
firefoxdriver class
new – is a memory allocation operator and creates a memory for a driver
object

- Above line will launch Firefox browser with blank page

There are two methods to open up a web browser:

1st method to open the URL:


Driver.get(‘http://google.com’);

2nd method – When you want to use the functionality back, forward and
refresh then you need to use the navigate.to

Driver.navigate().to(http://www.google.com);
Driver.navigate().back();
Driver.navigate().forward();
Driver.navigate().refresh();
Simple Example:

Package WebDriversample;

Import org.openqa.selenium.by;
Import org.openqa.selenium.webdriver;
Import org.openqa.selenium.firefox.Firefoxdriver;

Public class GmailLogin{


Public static void main (String[] args){
Webdriver abcd – new FirefoxDriver(); // abcd is webDriver object
acd.get(“http:/www.gmail.com”); // get is a method name
abcd.findelement(by.id(“email”)).sendkeys(“username”); // findelement is
a method and sendkeys is method
abcd.findelement(by.id(“signin”)).click(); // by is a predefined library and
“id” is an element locator or property
}}

Selenium UFT
Element Object
locator Property
Locators

Introduction to Locators

 Locators help Selenium in finding the UI elements on Web pages.

 We can use these locators in our test automation code to locate the UI elements on the Web
pages.
 Demonstrate the usage of Locators in locating the UI Elements on the Web Pages using
Selenium IDE

Different types of Locators

The below are the different types of locators which can be used for locating the UI elements on the
Web Pages:
HTML Basics for Locators

Having knowledge of below HTML basics will help you in


understanding the locators better:

1. Take any simple web page


say  http://compendiumdev.co.uk/selenium/basic_web_pag
e.html and inspect it to find its html code
2. Let's decode the above to create our own web page similar
to above
1. Title
2. Paragraphs
3. Now, lets learn the HTML code for displaying different types
of UI elements:
1. Adding Rulers using <hr/>
2. Adding Hyperlink (Requires href attribute with value
and target attribute with value '_blank')
3. Adding a Button (Using button tags and id attribute)
4. Inspect different UI elements on Omayo to identify the HTML
code behind it
1. Radio options having name attributes
2. Drop down option having class attribute
3. Image having src attribute
4. Text Area field having some random attributes

Demonstrating Different types of Locators using Selenium


IDE

Install Selenium IDE in any supported browser.

With the help of Selenium IDE's Target Text box field,


demonstrate all the below different types of locators:

Note: class and dom locators won't work in Selenium IDE. 

 id locator - Example: 'Button2' button in omayo blog -


Syntax: id=but2
 name locator - Example: 'Locate using name attribute' text
box field in omayo blog - Syntax: name=textboxn
 class locator - Example: text box "locate using class" in
omayo blog - Syntax: class=classone
o I will demonstrate using this locator during Selenium
WebDriver sessions. 
 link locator - Example: link 'compendiumdev' in omayo blog
- Syntax: link=compendiumdev
 css locator - Example: 'Button2' button in omayo blog -
Syntax: css=#but2
 xpath locator -  Example: 'Button2' button in omayo blog -
Syntax: xpath=//*[@id='but2']
 dom locator - Example: 'Button2' button in omayo blog -
Syntax: dom=document.getElementById("but2")

Locators Priority

Though there are different types of locators available for locating


the UI elements on the Web Pages, we need to use any one of
them based on their priority.

The below is the priority order in which we need to select and use
the locators :

 'id' locator needs to be given the first priority. i.e. If the


same UI element can be located with the help of different
locators like id, name and so on, we need to choose id
locator locating it.
 Similarly second priority goes for 'name' locator. i.e. If the
UI element cannot be located by id locator, then we will
prefer to choose 'name' locator as second priority. 
 Third priority goes for 'class' locator.
 Forth priority goes for 'link text' locator.
 Fifth priority goes for 'cssSelector' locator.
 Sixth priority goes for 'xpath expressions' locator.
 Last priority goes for 'dom' locator.

ChroPath for Auto-generating the XPath Expressions and


CSS Selectors

1. Installing ChroPath in any supported browser


2. Inspect any element and go to ChroPath tab to auto-
generate the XPath Expressions and CSS Selectors
3. Confirm its accuracy using Selenium IDE

Web element and element locators:


1- Web elements:
Browser, page  we can take care by using driver object

Examples of web elements are as follows:


1- Edit box
2- Link
3- Button
4- Image (general image, image link and image button)
5- Text area
6- Check box
7-Radio button
8- Drop down box
9- List box
10– Combo box
11- Web table / HTML table
12 – Web frame
Note: there may be challenges that how to locate web elements
1) Operation on browser: Important operations on browser object

- Launch Browser
- Navigate to specified URL
- Close focused browser
- Close all opened browser
- Navigate from one URL to another
- Navigate to back page
- Navigate to forward
- Refresh the browser
- Minimize the browser
- Maximize the browser

2) Page – Operations on page

- Get page title


- Get Page source
- Get page URL

3) Edit Box – Operations on edit box

- Enter some value


- Clear the value
- Check enabled status
- Check the existence
- Get the value

4) Link – operations on Link object (important)


- Click Link
- Check the existence
- Check enabled status
- Return link name

5) Image – operations on image

a) General Image
- Check the existence
- Check enabled or disabled status

b) Image button:
- Image button (submits)

c) Image Link
- Click, Redirects to another URL
6) Check Box – Operations on check box
- Check If the check box is displayed or not
- Check If the check box is enabled or not
- Check If the check box is select or not
- Check If the check box is un-select or not
Two ways of finding an element:

1)-Absolute xpath  it will show from the starting of the document meaning
from the very beginning (hierarchical structure)

2) - Relative xpath it is not hierarchical and find the exact element

Locator Techniques: There are 7 locator’s techniques

1-Xpath
2-ID
3-ClassName
4- Name
5- LinkText
6-CSS Selector
7- Partial Link
Writing customized xpaths:

e.g. (From Facebook) <input id =”email” class=”inputtext” type=”text”


tabtext=”1” value = “” name = “email”

Tagname = input
Attribute = ID
Value = email

Attributes Value
Id email
Class input text
Type text
Tabindex 1
Value “ “ – blank
Name email

Syntax: //tagname[@attribut=’value’]

Customized xpath will be:

//input[@name=’email’]

OR – If you are not sure about tag name then go for below syntax

//*[@name=’email’] --* is a regular expression and can be written if you


are not sure about tag name and tis is valid for xpath only.

Note: but make a habit of writing a tag name as values can be added so in
that case it can identify another value but if you have given tagname then it
will be unique.

Another Example: (Facebook ‘log in ‘button)

<input id=”u_0_n” type=”submit” tabindex=”4” value=”Log In”/>

Xpath will be : //input[@value=’Log in’]

Note: all the letters are case sensitive so make sure copy the exact words
and copy in xpath

Another Example: (Salesforce ‘log in ‘button)


e.g. <button id =”login” class=”button” name=”Login”>
Xpath will be: //button[@id=’Login’] or //*[@id=’Login’]
CSS will be: button[id=’login’] or .[id=’login’] or “#Login” (# is for ID only)

Another example by traversing the tagname for xpaths : traversing


from “reg_Form_box”

Customized xpath will be:

//div[@id=reg form box’]/div[1]/div[1]/div/div/input

For writing a Dynamic xpath:

Dynamic xpath are used for where the elements properties are continuous
changes e.g. when you search in the google and same thing searched in the
google there xpath will change.

We can use two functions of web driver:

Driver.findelement(by.xpath(”//* Starts-with(………)”);
Driver.findelement(by.xpath(”//* Contains(………)”);

and after that we need to see that how many elements are present in the
web page and in order to do that we need to do the following:

List<WebElement> list = Driver.findelement(by.xpath(”//*


Contains(………)”);
System.out.println(list.size()); --- get to know that how much elements
are present in the page and once we get the numbers then we can choose
the desired option from search result by giving the index of that search list.
List.get(0).click();  As we are looking for a search result which is on
first is on the list.

For writing customized Xpath:

. (Dot) is by default
/ -- is for the first element in the page
// -- meaning it can be present anywhere in the page

For xpath where there is no unique id and traversing by some other element
id to that main element:

Commands are:

- Preceding – sibling ::
- Following –sibling ::

Customize xpath:
.//Div[@class=’’]

For writing an Advance xpath by using webDriver functions

-/a[Starts-with(@id,’ ’)] – starts with is a function if element is dynamic


and changing the properties
 //a[contains(@id,’b_7’)] --- contains is a function of webdriver and
contains the value starting before the ‘b’ and any value after ‘7’
//div[@id=’leftcol’]/a[text]90=’Learn CSS’] – by function text
//div[@id=’leftcol’]/a[starts-with(text(),’learn boots()] --- two functions
in one xpath
//*[@id=’manicol’]/div[1/div[2]/a)[last()] --- It will click on the last link
(insisted of taking as a index)
//*[@id=’manicol’]/div[1/div[2]/a)[last()-1] --- It will click on the second
last link (insisted of taking as a index)
//*[@id=’manicol’]/div[1/div[2]/a)[position()=’1’] --- It will click on the
first link (insisted of taking as a index)

Writing the Customized CSS: (CSS is faster then XPATH)

Syntax: tagname [attribute=’value’] - No // (slash), No @ as compared to


xpaths, OR
[attribute=’value’] -if you are not sure about the tagname then do not
write tagname.

For finding an element by CSS: e.g. input[id=’login1][name=’login’] – over


here giving a double properties to find an element e.g. [][]

-- Shortest way to write the CSS locator path is for above login example is
#login1
-- In CSS instead of ‘/’ we need to give the space
-- In CSS instead of class we can use dot (.) and if there is any space
between values then use dot (.)
--In CSS starts with is written as ^ sign (carrot sign) instead of an whole
word like in xpath e.g. input[id^=’logi’
-- In CSS contains written as * instead of writing whole word contains like in
xpath e.g. input[id*=’ogin’]

Close and Quit

Driver.close(); ---close the browser which is currently focused meaning


let’s say if google.com is opened and by the google.com , one pop-up
window is also opened and when we try to close the google.com then only
google.com will be closed and not the pop-up window.

Driver.Quit(); --- Closes all the browser opened by driver and destroys the
driver object.
What is the difference between implicit wait and explicit wait?

Webdriverwait wd = new WebDriverWait(driver,5) --Webdriverwait


is a class
Wd.until(ExpectedConditions.******reason as per requirement) OR,
Wd.until(ExpectedConditions.visibilityofelementlocated(by.xpath(“./
/*[])));

Explicit Wait  explicit wait time is generally used and it is a best practice
e.g. when you pass the arguments as 5 seconds that means if Webdriver
gets the element in 2 seconds then it will not wait for another 3 seconds.it
will move on to the next line of code to execute but it will wait for 5 seconds
only and if the element does not appear then it will throw the error.
(Maximum and minimum time will vary on the condition and
element)

Implicit Wait-Thread.sleep(5000) This is not a best practice using this


option(use in worst case because it will decrease your performance) as this
will hold for 5 seconds unnecessary if the element will present in 2 seconds
but it will still wait for 3 more seconds to complete the 5 seconds
(Maximum and minimum time will remain same)

Radio Button:
WebDriver driver = new FirefoxDriver();
driver.get("http://www.echoecho.com/htmlforms10.htm");
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);

// Make a list of all the radio buttons and put it into list (object)
List<WebElement> list =
driver.findElements(By.xpath("//input[@name='group1']"));
//Print the size of the list
System.out.println(list.size());
//loop to identify the value
for(WebElement e: list)
{
//get attribute meaning getting the names of all the values of radio button
System.out.println(e.getAttribute("value"));
// get to know that which button is selected and it will give the value in
boolean
System.out.println(e.isSelected());
// if condition for cheese meaning if you find cheese text then click on that
text
if(e.getAttribute("value").equals("Cheese"))
{
e.click();
}
}
// condition to see which value is checked or unchecked
System.out.println("-----------------------------------");
for(WebElement e: list){
System.out.println(e.getAttribute("value"));
System.out.println(e.isSelected());
}
}

Ctrl+shift+o(‘orange’) -- for inserting all the necessary libraries


WebDriver methods:

We will look in detail for each of the webdriver methods that we have. The
first that we use is 'driver.get(url)' after starting the browser.
When we get the driver object, the below are the methods that we can
perform operation on a driver. In IDE like eclipse, when we enter driver. and
click on space bar, it will show all the below methods.
get()
getCurrentUrl();
getTitle()
findElements()
findElement()
getPageSource()
close()
quit()
Method Name :- get()
Syntax: get(url)
Example: driver.get();
Purpose: It will load a new web page in the current browser window. This is
done using an http get operation, and the method will block until the load is
complete.
Parameters: URL - The URL to load and it should be a fully qualified URL
Method Name: getCurrentUrl()
Syntax: getCurrentUrl()
Example: driver.getCurrentUrl();
Purpose: Gets a string representing the current URL that the browser is
opened.
Returns: The URL of the page currently loaded in the browser
Method Name: getTitle()
Syntax: getTitle()
Example: driver.getTitle();
Purpose: Gets the title of the current web page.
Returns: The title of the current page, with leading and trailing white space
stripped, or null if one is not already set
Method Name: findElements()
Syntax: findElements(By by)
Example: driver.findElements(By.xpath("//");
Purpose: Find all elements within the current page using the given
mechanism.
Parameters: By - The locating mechanism to use
Returns: A list of all WebElements, or an empty list if nothing matches
Method Name: findElement()
Syntax: WebElement findElement(By by)
Example: driver.findElements(By.xpath("//");
Purpose: Find the first WebElement using the given method.
Parameters: By - The locating mechanism
Returns: The first matching element on the current page
Throws: NoSuchElementException - it will return exception if no matching
elements are found
Method Name: getPageSource()
Syntax: getPageSource()
Example: driver.getPageSource();
Purpose: Get the source of the currently loaded page. If the page has been
modified after loading (for example, by Javascript) there is no guarantee
that the returned text is that of the modified page.
Returns: The source of the current page
Method Name: close()
Syntax: void close()
Example: driver.close();
Purpose: Close the current window, if there are multiple windows, it will
close the current window which is active and quits the browser if it's the last
window opened currently.
Method Name: quit()
Syntax: void quit()
Example: driver.quit();
Purpose: Quits this driver instance, closing every associated window which is
opened.
Method Name: getWindowHandles()
Syntax: Set getWindowHandles()
Example: driver.getWindowHandles();
Purpose: Return a set of window handles which can be used to iterate over
all the open windows of this Webdriver instance by passing them to
switchTo().WebDriver.Options.window()
Returns: A set of window handles which can be used to iterate over all the
open windows.
Method Name: getWindowHandle()
Syntax: String getWindowHandle()
Example: driver.getWindowHandle();
Parameter: Return an opaque handle to this window that uniquely identifies
it within this driver instance. This can be used to switch to this window at a
later date
switchTo
WebDriver.TargetLocator switchTo()
The next future commands will be performed to a different frame or window.
Returns: A Target Locator which can be used to switch or select a frame or
window
Method Name: navigate()
Syntax: WebDriver.Navigation navigate()
Example: driver.navigate.to("");
Purpose: An abstraction allowing the driver to access the browser's history
and to navigate to a given URL.
Returns: A WebDriver.Navigation that allows the selection of what to do next
Method Name: manage()
Syntax: WebDriver.Options manage()
Purpose: Gets the Option interface
Returns: An option interface

IsElementPresent/Text Present  function in Selenium WebDriver


1. Finding elements by using function that take argument of By
classprivate boolean isElementPresent(WebDriver driver, By by)
try{
driver.findElement(by);
return true;
}
catch(Exception e)
{
return false;
}
}
2. Using the size to decide whether element is there or not
if(driver.findElements(Locator).size()>0
{
return true
}else
{
return false
}
}
3. Finding the text using the PageSource
driver.PageSource.Contains("TEXT that you want to see on the page");

Finding WebElement  by using various locators in WebDriver


1. Using ID  WebElement welement = driver.findElement(By.id("Id from
webpage"));
2. Using Name  WebElement welement =
driver.findElement(By.name("Name of WebElement"));
3. Using Tag Name  WebElement welement =
driver.findElement(By.tagName("tag name"));
4. Using Xpath  WebElement welement =
driver.findElement(By.xpath("xpath of  webElement"));
5. Using CSS  WebElement welement = driver.findElement(By.CSS("CSS
locator path"));
6. Using LinkText  WebElement welement =
driver.findElement(By.LinkText("LinkText"));

1. Fetching pop-up message in Selenium-WebDriver


this is the function that would help you in fetching the message

public static String getPopupMessage(final WebDriver driver) {


String message = null;
try {
Alert alert = driver.switchTo().alert();
message = alert.getText();
alert.accept();
} catch (Exception e) {
message = null;
}
System.out.println("message"+message);
return message;
}
2. Canceling pop-up in Selenium-WebDriver
public static String cancelPopupMessageBox(final WebDriver
driver) {
String message = null;
try {
Alert alert = driver.switchTo().alert();
message = alert.getText();
alert.dismiss();
} catch (Exception e) {
message = null;
}
return message;
}
1. Inserting string in Text Field in Selenium-WebDriver
public static void insertText(WebDriver driver, By locator, String value)
{
WebElement field = driver.findElement(locator);
field.clear();
field.sendKeys(value);
}
2. Reading ToolTip text in in Selenium-WebDriver
public static String tooltipText(WebDriver driver, By locator){
String tooltip = driver.findElement(locator).getAttribute("title");
return tooltip;
}
3. Selecting Radio Button in Selenium-WebDriver

public static void selectRadioButton(WebDriver driver, By locator, String


value){ List select = driver.findElements(locator);
for (WebElement element : select)
{
if (element.getAttribute("value").equalsIgnoreCase(value)){
element.click();
}
}
4.  Selecting CheckBox in Selenium-WebDriver

public static void selectCheckboxes(WebDriver driver, By locator,String


value)
{
List abc = driver.findElements(locator);
List list = new ArrayListArrays.asList(value.split(",")));
for (String check : list){
for (WebElement chk : abc){
if(chk.getAttribute("value").equalsIgnoreCase(check)){
chk.click();
}}}}
5. Selecting Dropdown in Selenium-WebDriver
public static void selectDropdown(WebDriver driver, By locator, String
value){
new Select (driver.findElement(locator)).selectByVisibleText(value); }
6. Selecting searched dropdown in Selenium-WebDriver
public static void selectSearchDropdown(WebDriver driver, By locator,
String value){
driver.findElement(locator).click();
driver.findElement(locator).sendKeys(value);
driver.findElement(locator).sendKeys(Keys.TAB);
}
7. Uploading file using  Selenium-WebDriver
public static void uploadFile(WebDriver driver, By locator, String path){
driver.findElement(locator).sendKeys(path);
}
8. Downloading file in Selenium-WebDriver
Here we will click on a link and will download the file with a predefined
name at some specified location.
public static void downloadFile(String href, String fileName) throws
Exception{
URL url = null;
URLConnection con = null;
int i;
url = new URL(href);
con = url.openConnection();
// Here we are specifying the location where we really want to save the
file.
File file = new File(".//OutputData//" + fileName);
BufferedInputStream bis = new
BufferedInputStream(con.getInputStream());
BufferedOutputStream bos = new BufferedOutputStream(
new FileOutputStream(file));
while ((i = bis.read()) != -1) {
bos.write(i);
}
bos.flush();
bis.close();
}
9. Handling multiple Pop ups 
read  Handling Multiple Windows in WebDriver
10. Wait() in Selenium-WebDriver
1. Implicit Wait :
driver.manage.timeouts().implicitlyWait(10,TimeUnit.SECONDS);
2. Explicit Wait:WebDriverWait wait = new
WebDriverWait(driver,10);
wait.until(ExpectedConditons.elementToBeClickable(By.id/xpath/n
ame("locator"));
3.  Using Sleep method of java
Thread.sleep(time in milisecond)

11. Navigation method of WebDriver Interface


1. to() method (its a alternative of get() method)
driver.navigate().to(Url);
This will open the URL that you have inserted as argument
2. back() – use to navigate one step back from current position in
recent history syntax == driver.navigate().back();
3. forward() – use to navigate one step forward in browser
history driver.navigate().forward();
4. refresh() – This will refresh you current open
url driver.navigate().refresh();
12. Deleting all Cookies before doing any kind of action
driver.manage().deleteAllCookies();
This will delete all cookies

1. Pressing any Keyboard key using Action builder class of


WebDriver
WebDriver has rewarded us with one class Action to handle all keyboard
and Mouse action. While creating a action builder its constructor takes
WebDriver as argument. Here I am taking example of pressing Control
key
Actions builder = new Actions(driver);
builder.keyDown(Keys.CONTROL).click(someElement).click(someOtherE
lement).keyUp(Keys.CONTROL).build().perform();When we press
multiple keys or action together then we need to bind all in a single
command by using build() method and perform() method intend us to
perform the action.
In the same way you can handle other key actions.

2. Drag and Drop action in Webdriver


In this we need to specify both WebElement  like Source and target and
for draganddrop Action class has a method with two argument so let
see how it normally look like
WebElement element = driver.findElement(By.name("source"));
WebElement target = driver.findElement(By.name("target"));
(new Actions(driver)).dragAndDrop(element, target).perform();
Questions and answers: --

 What is the parent class of all the classes in java?

Ans. Object class

You might also like