You are on page 1of 82

Java Quick Tutorial for Selenium

Java Environment Setup & Verify

A) Java Fundamentals

i) Comments in Java

ii) Java Data Types

iii) Java Modifiers

iv) Variables

v) Operators

vi) Conditional Statements

vii) Loop Statements

viii) String Handling in Java

ix) Arrays in Java

x) Java IO Operations and File Handling

xi) Java Built-in Methods

xii) Java User defined Methods

xiii) Java Exception Handling

B) Java OOPS (Object Oriented Programming System)

i) Inheritance

ii) Polymorphism

iii) Abstraction

iv) Encapsulation

———————————-

Java Environment Setup & Verify

Steps:

> Download Eclipse IDE and extract

> Download Java and Install


————————-

> Launch Eclipse IDE

> Create Java Project

> Create Java Package

> Create Java Class

Write Java Program and Execute

———————————-

i) Comments in Java

Purpose of Comments in Computer Programming

> To make the Code Readable

> To make the Code disable from Execution.

Java supports Single line comment and multiple line comments.

———————-

Single line Comment- // before the Statement

Multiple lines comment/comment a block of statements

/* Statements

—————

——————

————*/

———————-

Example:

public static void main(String[] args) {

//It is a Sample Java Program

int a=10, b =20;

System.out.println(a+b);

/*if ( a > b){


System.out.println(“A is a Big Number”);

else {

System.out.println(“B is a Big Number”);

}*/

———————————-

ii) Data Types in Java

A Data Type is a classification of the type of data that a variable or object can hold in computer
programming.

Example for General Data Types:

Character,

Integer

String

Float

Boolean etc…

Java supports two categories of Data types.

a) Primitive Data Types

b) Reference Data Types.

Example:

int a=10;

char b =’A’;

double c = 123.234;

boolean d = true;

System.out.println(a);

System.out.println(b);

System.out.println(c);
System.out.println(d);

———————————-

iii) Java Modifiers

Modifiers are used to set access levels for Classes, Variables and Methods etc…

Two types of Modifiers in Java

1) Access Modifiers (default, public, private and protected)

2) Non Access Modifiers (static, final, abstract, synchronized etc…)

Example:

public class Class1 {

public int a =10, b =20;

public void add(){

int result = a +b;

System.out.println(result);

public static void main(String[] args) {

Class1 obj = new Class1();

obj.add();

———————————-

iv) Variables in Java

A named memory location to store temporary data within a program.

Three types of variables in Java

1) Local Variables

2) Instance Variables

3) Class / Static Variables


Example:

public class Class1 {

public static int a =100, b =20;

public static void main(String[] args) {

int c = 30;

System.out.println(a);

System.out.println(c);

if (a > b){

int d=40;

System.out.println(a + b + d);

System.out.println(d);

//System.out.println(d);

System.out.println(b);

———————————-

v) Operators in Java

Operators are used to perform Mathematical, Comparison and Logical Operations.

Categories of Operators in Java

1) Arithmetic Operators

2) Relational Operators

3) Assignment Operators

4) Logical Operators

Etc…

——————————–
1) Arithmetic Operators

a) Addition + (Addition, String Concatenation)

b) Subtraction – (Subtraction, Negation)

c) Multiplication *

d) Division /

e) Modules %

f) Increment ++

g) Decrement —

————————

2) Relational Operators

a) ==

b) !=

c) >

d) >=

e) <

f) <=

—————————

3) Assignment Operators

a) Assignment =

b) Add and Assign +=

c) Subtract and Assign -=

d) Multiply and Assign *=

————————

4) Logical Operators

a) Logical Not operator !

b) Logical And Operator &&

c) Logical Or operator ||
———————————-

Example:

public class Class1 {

public static void main(String[] args) {

int a=10, b=20, c =30;

System.out.println(a+b);

System.out.println(a*b);

System.out.println(a-b);

System.out.println(a > b);

System.out.println(a < b);

System.out.println(a+10);

if ((c > a) && (c > b)){

System.out.println(“C is a Big Number”);

else {

System.out.println(“C is Not a Big Number”);

———————————-

vi) Java Conditional Statements

1) Two types of statements

a) if statement

b) switch statement

———————–

2) Three types of Conditions

a) Single Condition (Positive/Negative)


b) Compound Condition (Positive/Negative)

c) Nested Condition (Positive/Negative)

———————————-

3) Usage of Conditional Statements

a) Execute a block of statements when a condition is true.

b) Execute a block of statements when a condition is true, otherwise execute another block of
statements.

c) Execute a block of statements when a Compound condition is true, otherwise execute another
block of statements.

d) Decide among several alternates (Else if)

e) Execute a block of statements when more than one condition is true (Nested if).

f) Decide among several alternates using Switch statement

—————————-

Example:

int a=100, b=20;

if (a > b){

System.out.println(“A is a Big Number”);

if (a > b){

System.out.println(“A is a Big Number”);

else {

System.out.println(“B is a Big Number”);

if (!(b > a)){

System.out.println(“A is a Big Number”);

else
{

System.out.println(“B is a Big Number”);

———————————-

vii) Loop Statements

Used for Repetitive execution.

Four types of loop structures in Java

1) for loop

2) while loop

3) do while loop

4) Enhanced for loop(Arrays)

————————-

Examples:

//Print 1 to 10 Numbers

for (int i=1; i<=10; i++){

System.out.println(i);

——————–

//Print 1 to 10 Numbers

int i=1;

while (i<=10){

System.out.println(i);

i++;

—————————-

//Print 1 to 5 Numbers Except 4

for (int i = 1; i <=5; i++){


if (i != 4){

System.out.println(i);

———————————-

viii) String handling in Java

> Sequence of characters written “”

> String may contain Alfa bytes or Alfa-numeric or Alfa-numeric and Special characters or only
numeric.

“ABCD”

“India123”

“India123$#@”

“123”

————————–

Example:

System.out.println(“India”);

System.out.println(“India123”);

System.out.println(“123”);

System.out.println(“$%^”);

System.out.println(“India123%^&*”);

———————————-

Creating Strings

String myTool = “UFT”;//String Variable

String [] myTools ={“UFT”, “RFT”, “Selenium”};//Array of Strings

System.out.println(myTool);//UFT

————————

Example 3:

String str1 =”Selenium”;


String str2 = ” UFT”;

System.out.println(str1 + str2);//Selenium UFT

System.out.println(str1.concat(str2));//Selenium UFT

System.out.println(“Selenium”+1+1);//Selenium11

System.out.println(1+1+”Selenium”);//2Selenium

———————————-

ix) Arrays in Java

> Generally, Array is a collection of similar type of elements.

> In Java, Array is an Object that contains elements of similar data type.

> Each item in an Array is called an Element.

—————————-

Example:

int a [];

a= new int[3];

a[0]=10;

a[1]=20;

a[2]=30;

System.out.println(a[1] + a[2]);

——————————–

int a [] = new int [3];

a[0]=10;

a[1]=20;

a[2]=3;

System.out.println(a[0] – a[2]);

——————————-

int a [] = {10, 20, 30, 40};

System.out.println(a[1] + a[3]);
——————————–

//Different Types of Arrays

char [] a = {‘A’, ‘B’, ‘C’, ‘d’};//Array of Characters

int [] b ={10, 20, 30, 40}; //Array of Integers

String [] c = {“UFT”, “RFT”, “Selenium”};//Array of Strings

boolean [] d ={true, false, false, true}; //Array of Boolean values.

double [] e ={1.234, 2.345, 5.6}; // Array of decimal point values

———————————-

x) Java IO Operations

Reading Data (Read Input, Read data from files)

—————————–

Using java.util.Scanner is the easier way and it includes many methods to check input is valid to read.

Examples:

1) Read Input:

Scanner scan = new Scanner(System.in); //System.in is an Input stream

System.out.println(“Enter Your Name”);

String name = scan.nextLine();

System.out.println(“Your Name is “+ name);

System.out.println(“Enter Your Number”);

int num = scan.nextInt();

System.out.println(“Your Number is “+ num);

—————————

2) Display Output on the Console

public static void main(String[] args) {

int a =10, b=20;

System.out.println(a);//10

System.out.println(“welcome to Selenium”);//welcome to Selenium


System.out.println(“Addition of a, b is “+ (a+b));//Addition of a, b is 30

System.out.println(“value of a is “+ a + ” Value of b is “+b);//Value of a is 10 value of b is 20”

———————————-

Java Quick Tutorial for Selenium

Java Environment Setup & Verify

A) Java Fundamentals

i) Comments in Java

ii) Java Data Types

iii) Java Modifiers

iv) Variables

v) Operators

vi) Conditional Statements

vii) Loop Statements

viii) String Handling in Java

ix) Arrays in Java

x) Java IO Operations and File Handling

xi) Java Built-in Methods

xii) Java User defined Methods

xiii) Java Exception Handling

B) Java OOPS (Object Oriented Programming System)

i) Inheritance

ii) Polymorphism

iii) Abstraction

iv) Encapsulation

———————————-
Java Environment Setup & Verify

Steps:

> Download Eclipse IDE and extract

> Download Java and Install

————————-

> Launch Eclipse IDE

> Create Java Project

> Create Java Package

> Create Java Class

Write Java Program and Execute

———————————-

i) Comments in Java

Purpose of Comments in Computer Programming

> To make the Code Readable

> To make the Code disable from Execution.

Java supports Single line comment and multiple line comments.

———————-

Single line Comment- // before the Statement

Multiple lines comment/comment a block of statements

/* Statements

—————

——————

————*/

———————-

Example:

public static void main(String[] args) {

//It is a Sample Java Program


int a=10, b =20;

System.out.println(a+b);

/*if ( a > b){

System.out.println(“A is a Big Number”);

else {

System.out.println(“B is a Big Number”);

}*/

———————————-

ii) Data Types in Java

A Data Type is a classification of the type of data that a variable or object can hold in computer
programming.

Example for General Data Types:

Character,

Integer, String, Float, Boolean etc…

Java supports two categories of Data types.

a) Primitive Data Types

b) Reference Data Types.

Example:

int a=10;

char b =’A’;

double c = 123.234;

boolean d = true;

System.out.println(a);

System.out.println(b);

System.out.println(c);
System.out.println(d);

———————————-

iii) Java Modifiers

Modifiers are used to set access levels for Classes, Variables and Methods etc…

Two types of Modifiers in Java

1) Access Modifiers (default, public, private and protected)

2) Non Access Modifiers (static, final, abstract, synchronized etc…)

Example:

public class Class1 {

public int a =10, b =20;

public void add(){

int result = a +b;

System.out.println(result);

public static void main(String[] args) {

Class1 obj = new Class1();

obj.add();

———————————-

iv) Variables in Java

A named memory location to store temporary data within a program.

Three types of variables in Java

1) Local Variables

2) Instance Variables

3) Class / Static Variables


Example:

public class Class1 {

public static int a =100, b =20;

public static void main(String[] args) {

int c = 30;

System.out.println(a);

System.out.println(c);

if (a > b){

int d=40;

System.out.println(a + b + d);

System.out.println(d);

//System.out.println(d);

System.out.println(b);

———————————-

v) Operators in Java

Operators are used to perform Mathematical, Comparison and Logical Operations.

Categories of Operators in Java

1) Arithmetic Operators

2) Relational Operators

3) Assignment Operators

4) Logical Operators

Etc…

——————————–
1) Arithmetic Operators

a) Addition + (Addition, String Concatenation)

b) Subtraction – (Subtraction, Negation)

c) Multiplication *

d) Division /

e) Modules %

f) Increment ++

g) Decrement —

————————

2) Relational Operators

a) ==

b) !=

c) >

d) >=

e) <

f) <=

—————————

3) Assignment Operators

a) Assignment =

b) Add and Assign +=

c) Subtract and Assign -=

d) Multiply and Assign *=

————————

4) Logical Operators

a) Logical Not operator !

b) Logical And Operator &&

c) Logical Or operator ||
———————————-

Example:

public class Class1 {

public static void main(String[] args) {

int a=10, b=20, c =30;

System.out.println(a+b);

System.out.println(a*b);

System.out.println(a-b);

System.out.println(a > b);

System.out.println(a < b);

System.out.println(a+10);

if ((c > a) && (c > b)){

System.out.println(“C is a Big Number”);

else {

System.out.println(“C is Not a Big Number”);

———————————-

vi) Java Conditional Statements

1) Two types of statements

a) if statement

b) switch statement

———————–

2) Three types of Conditions

a) Single Condition (Positive/Negative)


b) Compound Condition (Positive/Negative)

c) Nested Condition (Positive/Negative)

———————————-

3) Usage of Conditional Statements

a) Execute a block of statements when a condition is true.

b) Execute a block of statements when a condition is true, otherwise execute another block of
statements.

c) Execute a block of statements when a Compound condition is true, otherwise execute another
block of statements.

d) Decide among several alternates (Else if)

e) Execute a block of statements when more than one condition is true (Nested if).

f) Decide among several alternates using Switch statement

—————————-

Example:

int a=100, b=20;

if (a > b){

System.out.println(“A is a Big Number”);

if (a > b){

System.out.println(“A is a Big Number”);

else {

System.out.println(“B is a Big Number”);

if (!(b > a)){

System.out.println(“A is a Big Number”);

else{
System.out.println(“B is a Big Number”);

———————————-

vii) Loop Statements

Used for Repetitive execution.

Four types of loop structures in Java

1) for loop

2) while loop

3) do while loop

4) Enhanced for loop(Arrays)

————————-

Examples:

//Print 1 to 10 Numbers

for (int i=1; i<=10; i++){

System.out.println(i);

——————–

//Print 1 to 10 Numbers

int i=1;

while (i<=10){

System.out.println(i);

i++;

—————————-

//Print 1 to 5 Numbers Except 4

for (int i = 1; i <=5; i++){

if (i != 4){
System.out.println(i);

}}

———————————-

viii) String handling in Java

> Sequence of characters written “”

> String may contain Alfa bytes or Alfa-numeric or Alfa-numeric and Special characters or only
numeric.

“ABCD”

“India123”

“India123$#@”

“123”

————————–

Example:

System.out.println(“India”);

System.out.println(“India123”);

System.out.println(“123”);

System.out.println(“$%^”);

System.out.println(“India123%^&*”);

———————————-

Creating Strings

String myTool = “UFT”;//String Variable

String [] myTools ={“UFT”, “RFT”, “Selenium”};//Array of Strings

System.out.println(myTool);//UFT

————————

Example 3:

String str1 =”Selenium”;

String str2 = ” UFT”;

System.out.println(str1 + str2);//Selenium UFT


System.out.println(str1.concat(str2));//Selenium UFT

System.out.println(“Selenium”+1+1);//Selenium11

System.out.println(1+1+”Selenium”);//2Selenium

———————————-

ix) Arrays in Java

> Generally, Array is a collection of similar type of elements.

> In Java, Array is an Object that contains elements of similar data type.

> Each item in an Array is called an Element.

—————————-

Example:

int a [];

a= new int[3];

a[0]=10;

a[1]=20;

a[2]=30;

System.out.println(a[1] + a[2]);

——————————–

int a [] = new int [3];

a[0]=10;

a[1]=20;

a[2]=3;

System.out.println(a[0] – a[2]);

——————————-

int a [] = {10, 20, 30, 40};

System.out.println(a[1] + a[3]);

——————————–

//Different Types of Arrays


char [] a = {‘A’, ‘B’, ‘C’, ‘d’};//Array of Characters

int [] b ={10, 20, 30, 40}; //Array of Integers

String [] c = {“UFT”, “RFT”, “Selenium”};//Array of Strings

boolean [] d ={true, false, false, true}; //Array of Boolean values.

double [] e ={1.234, 2.345, 5.6}; // Array of decimal point values

———————————-

x) Java IO Operations

Reading Data (Read Input, Read data from files)

—————————–

Using java.util.Scanner is the easier way and it includes many methods to check input is valid to read.

Examples:

1) Read Input:

Scanner scan = new Scanner(System.in); //System.in is an Input stream

System.out.println(“Enter Your Name”);

String name = scan.nextLine();

System.out.println(“Your Name is “+ name);

System.out.println(“Enter Your Number”);

int num = scan.nextInt();

System.out.println(“Your Number is “+ num);

—————————

2) Display Output on the Console

public static void main(String[] args) {

int a =10, b=20;

System.out.println(a);//10

System.out.println(“welcome to Selenium”);//welcome to Selenium

System.out.println(“Addition of a, b is “+ (a+b));//Addition of a, b is 30
System.out.println(“value of a is “+ a + ” Value of b is “+b);//Value of a is 10 value of b is 20”}

———————————-

Selenium Test Life Cycle

Selenium Test Process / Selenium Test Life Cycle

Phases:

i) Planning

ii) Generate Basic Tests/Test Cases

iii) Enhance Tests

iv) Run & Debug Tests

v) Analyze Test Results and Report Defects

—————————————–

Software Test Process / Software Test Life Cycle

Phases in STLC:

i) Test Planning

ii) Test Design

iii) Test Execution

iv) Test Closure

—————————————–

i) Test Planning

a) References / Input

Test Requirements (SRS (srs, frs) /CRS/FRS ….)

Project Plan

Test Strategy

—————————-

Corporate standards doc/s

Design docs

Prototypes etc…
b) Tasks

i) Understanding and Analyzing Test Requirements

ii) Risk Analysis

iii) Test Strategy Implementation

iv) Test Estimations (Scope of the AUT, Available Resources, Time, Budget etc…)

v) Team Formation

vi) Test Plan Documentation

vii) Configuration Management Planning

viii) Traceability Metrics Documentation

ix) Define Test Environment Setup

Output:

Test Plan Document

—————————————–

ii) Test Design

a) References / Input

Requirements

Test Plan

—————–

Test Case Template

Test Data Template

————————-

Corporate standards doc/s

Design docs

Prototypes etc…

———————————

b) Tasks

i) Understanding Test Requirements


ii) Derive / Create Test Scenarios

iii) Test Case Documentation

iv) Test Data Collection

c) Output

Test Case docs

Test Data

—————————————–

iii) Test Execution

a) References / Input

Test Requirements

Test Plan

Test Case Docs

Test Data

————————-

Readiness of AUT

Readiness of Test Environment

————————

Defect Report

———————–

b) Tasks

Verify Test Environment Setup

Create Test Batches

Test Execution

Smoke Testing

Comprehensive Testing

Reporting Defects

Tracking Defects
Select Test Cases for Regression Testing Cycle 1

Sanity Testing

Regression Testing Cycle 1

Reporting Defects

Tracking Defects

Select Test Cases for Regression Testing Cycle 2

Sanity Testing

Regression Testing Cycle 1

Reporting Defects

Tracking Defects

Final Regression

Output:

Opened and Closed Defect Reports

Tested Software

—————————————–

iv) Test Closure

a) References/Input

Test Requirements

Test Plan

——————-

Opened and closed Defect Reports

etc…

———————

Test Summary Report Template———————


b) Tasks

Evaluating the Exit Criteria

Collect all documents

Prepare Test Summary Report

Send Test Deliverables to Customer

Improvement suggestions for future projects.

—————————————–

Selenium Test Process / Selenium Test Life Cycle

i) Planning

ii) Generate Basic Tests

iii) Enhance Tests

iv) Run & Debug Tests

v) Analyze Test Results & Report Defects

—————————————–

i) Planning

> Get Environment (AUT) details form development team

> Analyze the AUT in terms Object Identification / Element Identification

> Page Inspector in Firefox Browser, Developer Tools in Chrome or IE

> Select Test Cases for Automation

i) Tests that we have to execute on every modified build (Sanity Tests)

ii) Tests that we have to execute on every modified build (Regression Tests)

iii) Tests that we have execute using multiple sets of Test Data (Data Driven Tests)

> Select Selenium Tools and Configure

If you Select Selenium WebDriver, Java, TestNG etc…

Download Eclipse IDE and Extract

Download Java Software and Install

Download Selenium WebDriver Java language binding and Add WebDriver jar files to Java Project in
Eclipse.
Download TestNG from Eclipse and Install

—————————————–

ii) Generate Basic Tests

Selenium IDE

By Recording user Actions on AUT Or Type Test Steps using Element Locators and Selenese
Commands

Selenium RC – * Out Dated

Selenium WebDriver

Type Test Steps using Element Locators and WebDriver API Commands

Selenium Grid – NA

—————————————–

iii) Enhance Tests

Selenium IDE:

Using Verify and Assert Commands, Add Comments, Synchronization etc…

Selenium WebDriver

Using Java Flow Control Statements insert Verification points

Add comments

Synchronization

Using Text files or Excel files with the help of Java conduct Data driven Testing

Uusing Java features handle Errors etc…

Or

Using TestNG Framework Assertion methods insert verification points

—————————————–

iv) Run & Debug Test Cases

Debugging Tests:

What is Debugging?

Locating and isolating errors thru step by step execution.

When Debugging is Required?


Scenario 1: Test is not showing any errors and providing correct output – Not required

Scenario 2: Test is showing errors- Debugging is optional

Scenario 3: Test is not showing any errors and Not providing correct output – Debugging is
Mandatory

Note: Whenever Test is not showing any error and not providing correct output then Debugging is
required.

Run / Execute Tests:

Run Single Test

Batch Testing

Selenium IDE supports batch testing

Selenium WebDriver supports batch testing

—————————————–

v) Analyze Test Result and Report Defects

Selenium WebDriver doesn’t have built in Result Reporter

Using Java you can define Test Results

Or

Using JUnit or TestNG we can define Test Results.

Report Defects

Functional Test Automation Defect Management

———————————————

Selenium Manual

———————————————

Selenium Bugzilla / Jira etc…

———————————————

Java Quick Tutorial for Selenium

Java Environment Setup & Verify

A) Java Fundamentals
i) Comments in Java

ii) Java Data Types

iii) Java Modifiers

iv) Variables

v) Operators

vi) Conditional Statements

vii) Loop Statements

viii) String Handling in Java

ix) Arrays in Java

x) Java IO Operations and File Handling

xi) Java Built-in Methods

xii) Java User defined Methods

xiii) Java Exception Handling

B) Java OOPS (Object Oriented Programming System)

i) Inheritance

ii) Polymorphism

iii) Abstraction

iv) Encapsulation

———————————-

Java Environment Setup & Verify

Steps:

> Download Eclipse IDE and extract

> Download Java and Install

————————-

> Launch Eclipse IDE

> Create Java Project

> Create Java Package


> Create Java Class

Write Java Program and Execute

———————————-

i) Comments in Java

Purpose of Comments in Computer Programming

> To make the Code Readable

> To make the Code disable from Execution.

Java supports Single line comment and multiple line comments.

———————-

Single line Comment- // before the Statement

Multiple lines comment/comment a block of statements

/* Statements

—————

——————

————*/

———————-

Example:

public static void main(String[] args) {

//It is a Sample Java Program

int a=10, b =20;

System.out.println(a+b);

/*if ( a > b){

System.out.println(“A is a Big Number”);

else {

System.out.println(“B is a Big Number”);

}*/}
}

———————————-

ii) Data Types in Java

A Data Type is a classification of the type of data that a variable or object can hold in computer
programming.

Example for General Data Types:

Character, Integer, String, Float, Boolean etc…

Java supports two categories of Data types.

a) Primitive Data Types

b) Reference Data Types.

Example:

int a=10;

char b =’A’;

double c = 123.234;

boolean d = true;

System.out.println(a);

System.out.println(b);

System.out.println(c);

System.out.println(d);

———————————-

iii) Java Modifiers

Modifiers are used to set access levels for Classes, Variables and Methods etc…

Two types of Modifiers in Java

1) Access Modifiers (default, public, private and protected)

2) Non Access Modifiers (static, final, abstract, synchronized etc…)

Example:

public class Class1 {

public int a =10, b =20;


public void add(){

int result = a +b;

System.out.println(result);

public static void main(String[] args) {

Class1 obj = new Class1();

obj.add();

———————————-

iv) Variables in Java

A named memory location to store temporary data within a program.

Three types of variables in Java

1) Local Variables

2) Instance Variables

3) Class / Static Variables

Example:

public class Class1 {

public static int a =100, b =20;

public static void main(String[] args) {

int c = 30;

System.out.println(a);

System.out.println(c);

if (a > b){

int d=40;

System.out.println(a + b + d);

System.out.println(d);
}

//System.out.println(d);

System.out.println(b);

———————————-

v) Operators in Java

Operators are used to perform Mathematical, Comparison and Logical Operations.

Categories of Operators in Java

1) Arithmetic Operators

2) Relational Operators

3) Assignment Operators

4) Logical Operators

Etc…

——————————–

1) Arithmetic Operators

a) Addition + (Addition, String Concatenation)

b) Subtraction – (Subtraction, Negation)

c) Multiplication *

d) Division /

e) Modules %

f) Increment ++

g) Decrement —

————————

2) Relational Operators

a) ==

b) !=
c) >

d) >=

e) <

f) <=

—————————

3) Assignment Operators

a) Assignment =

b) Add and Assign +=

c) Subtract and Assign -=

d) Multiply and Assign *=

————————

4) Logical Operators

a) Logical Not operator !

b) Logical And Operator &&

c) Logical Or operator ||

———————————-

Example:

public class Class1 {

public static void main(String[] args) {

int a=10, b=20, c =30;

System.out.println(a+b);

System.out.println(a*b);

System.out.println(a-b);

System.out.println(a > b);

System.out.println(a < b);

System.out.println(a+10);

if ((c > a) && (c > b)){


System.out.println(“C is a Big Number”);

else {

System.out.println(“C is Not a Big Number”);

———————————-

vi) Java Conditional Statements

1) Two types of statements

a) if statement

b) switch statement

———————–

2) Three types of Conditions

a) Single Condition (Positive/Negative)

b) Compound Condition (Positive/Negative)

c) Nested Condition (Positive/Negative)

———————————-

3) Usage of Conditional Statements

a) Execute a block of statements when a condition is true.

b) Execute a block of statements when a condition is true, otherwise execute another block of
statements.

c) Execute a block of statements when a Compound condition is true, otherwise execute another
block of statements.

d) Decide among several alternates (Else if)

e) Execute a block of statements when more than one condition is true (Nested if).

f) Decide among several alternates using Switch statement

—————————-
Example:

int a=100, b=20;

if (a > b){

System.out.println(“A is a Big Number”);

if (a > b){

System.out.println(“A is a Big Number”);

else {

System.out.println(“B is a Big Number”);

if (!(b > a)){

System.out.println(“A is a Big Number”);

else

System.out.println(“B is a Big Number”);

———————————-

vii) Loop Statements

Used for Repetitive execution.

Four types of loop structures in Java

1) for loop

2) while loop

3) do while loop

4) Enhanced for loop(Arrays)

————————-
Examples:

//Print 1 to 10 Numbers

for (int i=1; i<=10; i++){

System.out.println(i);

——————–

//Print 1 to 10 Numbers

int i=1;

while (i<=10){

System.out.println(i);

i++;

—————————-

//Print 1 to 5 Numbers Except 4

for (int i = 1; i <=5; i++){

if (i != 4){

System.out.println(i);

———————————-

viii) String handling in Java

> Sequence of characters written “”

> String may contain Alfa bytes or Alfa-numeric or Alfa-numeric and Special characters or only
numeric.

“ABCD”

“India123”

“India123$#@”

“123”
————————–

Example:

System.out.println(“India”);

System.out.println(“India123”);

System.out.println(“123”);

System.out.println(“$%^”);

System.out.println(“India123%^&*”);

———————————-

Creating Strings

String myTool = “UFT”;//String Variable

String [] myTools ={“UFT”, “RFT”, “Selenium”};//Array of Strings

System.out.println(myTool);//UFT

————————

Example 3:

String str1 =”Selenium”;

String str2 = ” UFT”;

System.out.println(str1 + str2);//Selenium UFT

System.out.println(str1.concat(str2));//Selenium UFT

System.out.println(“Selenium”+1+1);//Selenium11

System.out.println(1+1+”Selenium”);//2Selenium

———————————-

ix) Arrays in Java

> Generally, Array is a collection of similar type of elements.

> In Java, Array is an Object that contains elements of similar data type.

> Each item in an Array is called an Element.

—————————-

Example:
int a [];

a= new int[3];

a[0]=10;

a[1]=20;

a[2]=30;

System.out.println(a[1] + a[2]);

——————————–

int a [] = new int [3];

a[0]=10;

a[1]=20;

a[2]=3;

System.out.println(a[0] – a[2]);

——————————-

int a [] = {10, 20, 30, 40};

System.out.println(a[1] + a[3]);

——————————–

//Different Types of Arrays

char [] a = {‘A’, ‘B’, ‘C’, ‘d’};//Array of Characters

int [] b ={10, 20, 30, 40}; //Array of Integers

String [] c = {“UFT”, “RFT”, “Selenium”};//Array of Strings

boolean [] d ={true, false, false, true}; //Array of Boolean values.

double [] e ={1.234, 2.345, 5.6}; // Array of decimal point values

———————————-

x) Java IO Operations

Reading Data (Read Input, Read data from files)

—————————–

Using java.util.Scanner is the easier way and it includes many methods to check input is valid to read.
Examples:

1) Read Input:

Scanner scan = new Scanner(System.in); //System.in is an Input stream

System.out.println(“Enter Your Name”);

String name = scan.nextLine();

System.out.println(“Your Name is “+ name);

System.out.println(“Enter Your Number”);

int num = scan.nextInt();

System.out.println(“Your Number is “+ num);

—————————

2) Display Output on the Console

public static void main(String[] args) {

int a =10, b=20;

System.out.println(a);//10

System.out.println(“welcome to Selenium”);//welcome to Selenium

System.out.println(“Addition of a, b is “+ (a+b));//Addition of a, b is 30

System.out.println(“value of a is “+ a + ” Value of b is “+b);//Value of a is 10 value of b is 20”

———————————-

Core Java Quick Tutorial for Selenium Part 2

In Java Quick Tutorial Part 1, I explained,

Java Environment Setup & Verify

A) Java Fundamentals

i) Comments in Java

ii) Java Data Types

iii) Java Modifiers


iv) Variables

v) Operators

vi) Conditional Statements

vii) Loop Statements

viii) String Handling in Java

ix) Arrays in Java

x) Java IO Operations

—————————————-

Java for Selenium Part 2

xi) File Handling

xii) Java Built-in Methods

xiii) Java User defined Methods

xiv) Java Exception Handling

B) Java OOPS (Object Oriented Programming System)

i) Inheritance

ii) Polymorphism

iii) Abstraction

iv) Encapsulation

—————————————-

xi) File Handling in Java

Using File Class we can handle Computer files.

Example:

1) Create a Folder

File fileObject = new File(“C:/Users/gcreddy/Desktop/ABC”);

fileObject.mkdir();

—————————————-

xii) Java Methods


A Java Method is a set of statements that are grouped together to perform an operation.

Methods are also known as Functions.

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)

—————————————-

When we choose Methods?

Whenever we want perform any operation multiple times then we choose methods.

Advantages of Methods

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

Code Maintenance is easy.

—————————————

ii) Types Methods in Java

Two types of Methods

1) Built in /Pre-defined Methods

2) User defined Methods

—————————————-

Examples for Built in Methods

equals() Method

Compares two strings and supports 2-way comparison

Example:

public static void main(String[] args) {

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

—————————————

round()

Rounds the value to nearest integer.

public static void main(String[] args) {

double a =10.234;

double b =-10.784;

.System.out.println(Math.round(a));//10

System.out.println(Math.round(b));//-11

—————————————

isAlphabetic()

Checks weather the value is alfa byte or not?

public static void main(String[] args) {

char a =’Z’;

char b =’1';

System.out.println(Character.isAlphabetic(a));//true

System.out.println(Character.isAlphabetic(b));//false

System.out.println(Character.isAlphabetic(‘B’));//true

System.out.println(Character.isAlphabetic(‘a’));//true

System.out.println(Character.isAlphabetic(‘*’));//false

—————————————-

xiii) User Defined methods in Java

Two types of user defined methods

1) Method without returning any value

a) Calling Methods by invoking Object

b) Calling methods without invoking Object


2) Method with returning a Value

a) Calling Methods by invoking Object

b) Calling methods without invoking Object

Examples:

//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);

———————————

//Create a method without returning any value

public static void studentRank(int marks){

if (marks >= 600){

System.out.println(“Rank A”);

else if (marks >=500){

System.out.println(“Rank B”);

else{

System.out.println(“Rank C”);

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

//Call Methods

JavaMethods.studentRank(650);

—————————————-

xiv) Java Exception Handling

> An Exception is an event that occurs during execution of a program when normal execution of a
program is interrupted.

> Exception handling is a mechanism to handle exceptions.

Common Scenarios where exceptions may occur

1) Scenario where ArithemeticException occurs

2) Scenario where NullPointerException occurs.

3) Scenario where NumberFormatException occurs

4) Scenario where ArrayIndexOutofBounds exception occurs

Example:

public static void main(String[] args) {

int a =10;

int b =0;

int result = a/b;

System.out.println(result);

System.out.println(“Hello Java”);

System.out.println(“Hello Selenium”);

—————————————-

B) Java Object Oriented Programming

Four fundamentals of OOPS:

i) Inheritance
ii) Polymorphism

iii) Abstraction

iv) Encapsulation

—————————————-

i) Inheritance

> It is a process of Inheriting (reusing) the class members (Variables and Methods) from one class to
another.

> Non static class members only can be inherited.

> The Class where the class members are getting inherited is called as Super Class/parent Class/Base
Class.

> The Class to which the class members are getting inherited is called as Sub Class/Child
Class/Derived Class.

> The Inheritance between Super class and Sub class is achieved using “extends” keyword.

—————————–

Example

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 extends 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

objB.add();//300

—————————————-

ii) Polymorphism

Existence of Object behavior in many forms

There two types of Polymorphism

1) Compile Time Polymorphism / Method Overloading

2) Run Time Polymorphism / Method Overriding

—————————————

1) Compile Time Polymorphism / Method Overloading

If two or more methods with same name in the same class but they differ in following ways.

a) Number of Arguments

b) 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){

System.out.println(a+b+c);

public void add(double a, double b){

System.out.println(a+b);

public static void main(String[] args) {

Class1 obj = new Class1();

obj.add(1.23, 2.34);

obj.add(10, 20);

obj.add(1, 5, 9);

—————————————-

iii) Abstraction

> It is a process of hiding implementation details and showing only functionality to the user.

Two types of Methods in Java

1) Concrete Methods (The methods which are having body)

2) Abstract Methods (The methods which are not having body)

> If we know the method name but don’t know the method functionality then we go for Abstract
methods.

> Java Class contains 100% concrete methods.

> Abstract class contains one or more abstract methods.

—————————————-

Example for Abstract Class:


public abstract class Bikes {

public void handle(){

System.out.println(“Bikes have handle”);

public void seat(){

System.out.println(“Bikes have Seats”);

public abstract void engine();

public abstract void wheels();

public static void main(String[] args) {

//Bikes obj = new Bikes();

—————————————-

iv) Encapsulation

It is a process of wrapping code and data into 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.

> It provides control over the data

> By providing setter and getter methods we can make a class read only or write only.

—————————————-

Example:

Class 1:

public class Class1 {

private String name =”Test Automation”;

public String getName(){

return name; }
public void setName(String newName){

name = newName;

public static void main(String[] args) {

Class1 obj = new Class1();

System.out.println(obj.getName());

—————————————-

Class 2:

public class Class2 extends Class1{

public static void main(String[] args) {

Class2 abc = new Class2();

//abc.setName(“Selenium Testing”);

System.out.println(abc.getName());

—————————————-

Selenium WebDriver Quick Tutorial

i) Introduction to Selenium WebDriver

ii) Selenium WebDriver Environment Setup

iii) Web Elements and Operations

iv) Element Locators

v) WebDriver API Commands

————————————-

i) Introduction to Selenium WebDriver

> Selenium WebDriver is a programming Interface, no IDE


> Selenium WebDriver supports various Programming Languages to write programs (Test Scripts)

> Selenium WebDriver supports various Operating Environments.

> Selenium WebDriver supports various Browsers to create and execute Test Cases.

> Using Element Locators and WebDriver Commands we can create Test Cases.

> Its support Batch Testing, Cross Browser Testing and Data Driven Testing

——————————–

Drawbacks of Selenium WebDriver

> It doesn’t have IDE, so difficult to create Test cases and takes more time.

> It doesn’t have built-in Result Reporting facility.

> No Tool integration for Test Management.

————————————-

ii) Selenium WebDriver Environment Setup

Steps:

i) Download and install Java (JDK) software. – To create and execute programs (Test scripts)

ii) Download Eclipse IDE and extract. – To write and execute Java programs.

————————————-

iii) Download Selenium WebDriver Java Language binding (from www.seleniumhq.org) and add
WebDriver jar files to Java project in Eclipse IDE.

————————————-

v) Firefox Driver is default driver in Selenium Webdriver, for IE, Chrome and Safari etc… Browsers we
need to download browser drivers and set path.

————————————-

Manual Test Case:

Test Case ID: gcrshop_admin_TC001

Test Case Name: Verify Admin Login in GCR Shop web portal

Test Steps:

i) Launch the Browser and navigate to “www.gcrit.com/build3/admin”

ii) Enter User name


iii) Enter Password

iv) Click “Login” Button

Input Data / Test Data:

User name =admin

Password = admin@123

Verification Point:

Capture the Url (Actual) after Login to Application and Compare with Expected.

Expected URL: “www.gcrit.com/build3/admin/index.php”

Test Result:

————————————-

1) Element Locators – To Identify the Elements

Example for Elements: Link, edit box, Button etc…

Examples for Operations on Elements: Click, Enter a Value, Check, select etc…

2) WebDriver Commands – Perform Operations on Elements

3) Java Programming – To enhance Test cases

————————————-

Object / Element Property/Locator Value

Man name Santosh

height 6

————————————-

Object name abc

Dog color white

weight 5

————————————-

Edit box name Email

Button id tdb1

————————————-
Selenium WebDriver Test Case:

public static void main(String[] args) {

WebDriver driver = new FirefoxDriver();//Launches Firefox Browser with blank url.

driver.get(“http://www.gcrit.com/build3/admin/login.php”);//Naviage to Admin home page

driver.findElement(By.name(“username”)).sendKeys(“admin”);

driver.findElement(By.name(“password”)).sendKeys(“admin@123”);

driver.findElement(By.id(“tdb1”)).click();

String url = driver.getCurrentUrl();

if (url.equals(“http://www.gcrit.com/build3/admin/index.php”)){

System.out.println(“Login Successful – Passed”);

else {

System.out.println(“Login Unsuccessful – Failed”);

driver.close();//Closes the Browser

————————————-

iii) Web Elements and Operations on Elements

a) WebElements

Browser

Page

—————-

Edit box

Link

Button

Image, Image Link, Image Button


Text Area

Check box

Radio Button

Drop down box

List box

Combo box

Web Table/ HTML Table

Frame

Etc..

——————————-

b) Operations on Elements

i) Browser

(Launch Browser, Navigate to specified URL, Navigate back, Navigate forward, refresh, close
Browser….)

ii) Page

(Return Page Title, Return Page URL…)

iii) Link

(Click, Check the existence, Check Enabled status ….)

iv) Button

(Click, Check Displayed status, Enabled status, return button name ….)

v) Image

a) General Image (Return Image Title etc…

b) Image Button (Click, Check Displayed status, Enabled status, return button name ….)

c) Image Link (Click, Check the existence, Check Enabled status ….)

vi) Text Area / Error Message

(Return Text Area/ Return Error Message etc…)

vii) Radio Button

(Check Displayed status, Enabled status, Select….)


viii) Check box

(Check Displayed status, Enabled status, Select, Unselect, check Selected status….)

ix) Drop down box

(Check Displayed status, Enabled status, Select an Item, Get Items Count ….)

x) List Box

(Check Displayed status, Enabled status, Select one or more Items, Get Items Count ….)

xi) Combo box

(Check Displayed status, Enabled status, Select an Item, Enter an Item, Get Items Count ….)

xii) Web Table

(Return specified Cell value, Return Rows Count, Column Count etc…)

xiii) Frame

(Switch from Top window to specified frame, Frame to Top window

inLine Elements

————————————-

iv) Element Locators

What is Locator?

> It is an address that identifies a Web element uniquely within the page.

Selenium supports 8 Element locators to recognize elements in web pages.

id, name, className, tagName, linkText, partialLinkText, cssSelector, xpath

————————————-

Syntax:

By.elementLocator(“element locator value”)

Example:

driver.findElement(By.id(“Email”))

————————————-

driver -Browser Object

findElement- WebDriver Method / Command


By – Built in Class

id – Locator

Email – Value

sendKeys -WebDriver Method / Command

India – Input Data

————————————-

Examples:

driver.findElement(By.name(“Email”)).sendKeys(“India”);

driver.findElement(By.className(“textboxcolor”)).sendKeys(“India”);

driver.findElement(By.tagName(“input”)).sendKeys(“India123”);

driver.findElement(By.linkText(“Gmail”)).click();

driver.findElement(By.partialLinkText(“Gma”)).click();

driver.findElement(By.cssSelector(“#next”)).click();

driver.findElement(By.xpath(“.//*[@id=’Email’]”)).sendKeys(“abcd123”);

————————————-

v) WebDriver Commands / Methods

> Selenium WebDriver methods/commands are used to perform operations on Web Elements.

> Using Element Locators and WebDriver Methods we create Test Cases.

Element Locators – To recognize / Identify Elements

WebDriver Methods – To perform operations on Elements

————————————-

Important WebDriver API Commands

1) get() – Opens a specified URL in the Browser window.

driver.get(“https://www.google.com”);

————————————-

2) getTitle() – Returns the Browser Title.

String Title = driver.getTitle();


3) getCurrentUrl() – Returns Current URL of the Browser

String Url = driver.getCurrentUrl();

————————————-

4) navigate().to() – Loads a new page in the current browser window.

driver.navigate().to(“https://in.yahoo.com”);

————————————-

5) navigate().back() – It moves a single item back in the Browser history.

driver.navigate().back();

————————————-

6) navigate().forward() – It moves single item forward in the browser history.

driver.navigate().forward();

————————————-

7) navigate().refresh() – Refreshes the Current web page

driver.get(“https://www.google.com”);

————————————-

8) close() – Closes the focused Browser.

driver.close();

————————————-

9) findElement() – Finds the first Element within the current page using given locator.

driver.findElement(By.id(“Email”)).sendKeys(“India123”);

————————————-

10) sendKeys() – Enters a value into Edit box/Text box.

driver.findElement(By.id(“Email”)).sendKeys(“India@123”);

————————————-

11) clear() – It clears the value from Edit box

driver.findElement(By.id(“Email”)).clear();

————————————-
12) click() – Clicks an Element (Buttons, Links etc…)

driver.findElement(By.id(“next”)).click();

————————————-

13) isEnabled() – Checks weather the Element is in Enabled state or not?

boolean a = driver.findElement(By.id(“next”)).isEnabled();

————————————-

14) isDisplayed() – Checks weather the Element is displayed or not?

boolean a = driver.findElement(By.linkText(“Gmail”)).isDisplayed();

————————————-

15) isSelected() – Checks weather the Element is selected or not?

boolean after = driver.findElement(By.xpath(“html/body/input[3]”)).isSelected();

————————————-

Selenium WebDriver Quick Tutorial Part 2

i) Writing Selenium Test Cases

ii) Cross Browser Testing

iii) Batch Testing

iv) Data Driven Testing

———————————-

Prerequisites for Writing Selenium WebDriver Test Cases

1) Test Scenario or Manual Test Case

2) Element Locators – To Locate/Indentify/Recognize Elements

3) Selenium WebDriver Commands or Methods – To perform operations on Elements

4) Programming features – To enhance Test Cases

5) JUnit / TestNG Testing Framework Annotations – To group Test Cases, Batch Testing, and
generating Test Reports.

———————————-

ii) Cross Browser Testing

Manual Test Case:


Test Case Name: Verify Launch Application (Google)

Test Steps:

i) Launch the Browser

ii) Navigate to https://www.google.com

Verification Point:

Capture the Page Title (Actual) and compare with Expected.

Expected: Google

Result:

———————————-

a) Selenium Test Case for Mozilla Firefox Browser

WebDriver driver = new FirefoxDriver();

driver.get(“https://www.google.com”);

String PageTitle = driver.getTitle();

if (PageTitle.equals(“Google”)){

System.out.println(“Google Application Launched – Passed”);

else {

System.out.println(“Google Application Not Launched – Failed”);

driver.close();

———————————-

b) Selenium Test Case for Google Chrome Browser

System.setProperty(“webdriver.chrome.driver”, “E:/chromedriver.exe”);

WebDriver driver = new ChromeDriver();

driver.get(“https://www.google.com”);

String PageTitle = driver.getTitle();


if (PageTitle.equals(“Google”)){

System.out.println(“Google Application Launched – Passed”);

else {

System.out.println(“Google Application Not Launched – Failed”);

driver.close();

———————————-

c) Selenium Test case for IE Browser

System.setProperty(“webdriver.ie.driver”, “E:/IEDriverServer.exe”);

WebDriver driver = new InternetExplorerDriver();

driver.get(“https://www.google.com”);

String PageTitle = driver.getTitle();

if (PageTitle.equals(“Google”)){

System.out.println(“Google Application Launched – Passed”);

else {

System.out.println(“Google Application Not Launched – Failed”);

driver.close();

———————————-

iii) Batch Testing

Test Case 1: Verify Admin Login in gcrShop Admin Interface

Test Case 2: Verify Redirect Functionality in gcrShop (From Admin Interface to user Interface)

Test Case 3: Verify the “Manufacturers” Link existence in gcrShop web portal after Admin Login——
—————————-
Selenium Test Batch:

public class BatchTesting {

public static WebDriver driver;

//Launch Browser

public void launchBrowser(){

driver = new FirefoxDriver();

//Admin Login

public void adminLogin(String Username, String Password){

driver.get(“http://www.gcrit.com/build3/admin/”);

driver.findElement(By.name(“username”)).sendKeys(Username);

driver.findElement(By.name(“password”)).sendKeys(Password);

driver.findElement(By.id(“tdb1”)).click();

//Close Browser

public void closeBrowser(){

driver.close();

public static void main(String[] args) {

BatchTesting obj = new BatchTesting();

//Test Case 1: Verify Admin Login in gcrShop Admin Interface

obj.launchBrowser();

obj.adminLogin(“admin”, “admin@123”);

String url = driver.getCurrentUrl();

if (url.equals(“http://www.gcrit.com/build3/admin/index.php”)){

System.out.println(“Test Case 1: Admin Login Successful – Passed”);

} else{
System.out.println(“Test Case 1: Admin Login Unsuccessful – Failed”);

obj.closeBrowser();

//——————————–

//Test Case 2: Verify Redirect Functionality in gcrShop (From Admin Interface to user Interface)

obj.launchBrowser();

obj.adminLogin(“admin”, “admin@123”);

driver.findElement(By.linkText(“Online Catalog”)).click();

String url2 = driver.getCurrentUrl();

if (url2.equals(“http://www.gcrit.com/build3/”)){

System.out.println(“Test Case 2: Redirected from Admin Interface to User Interface – Passed”);

else {

System.out.println(“Test Case 2: Not Redirected from Admin Interface to User Interface – Failed”);

obj.closeBrowser();

//——————————–

//Test Case 3: Verify the “Manufacturers” Link existence in gcrShop web portal after Admin Login

obj.launchBrowser();

obj.adminLogin(“admin”, “admin@123”);

try {

boolean linkExistence = driver.findElement(By.linkText(“Manufacturers”)).isDisplayed();

if (linkExistence == true){

System.out.println(“Test Case 3: Manufacturers Link Exists on Index Page – Passed”);

catch (NoSuchElementException e){


System.out.println(“Link not Exists”);

obj.closeBrowser();

//————————-

———————————-

iv) Data Driven Testing

What is Data Driven Testing?

Testing the Same Functionality with multiple sets of Test Data

Why Data Driven Testing?

Positive and Negative Testing

How to conduct Data driven Testing?

1) By Dynamic submission of Test Data

2) By Reading Test Data from a Text File

3) By Reading Test Data from an Excel file

Etc…

———————————-

Data Driven Test Case: Admin Login Functionality with valid and Invalid inputs

Test Steps:

1) Launch the Browser

2) Navigate to “http://www.gcrit.com/build3/admin” URL

3) Enter Username

4) enter Password

5) Click Login Button

Test Data: Read test data from a Text File (Input.txt)

Verification Point:
Capture the URL after Login and Compare with expected

Expected: http://www.gcrit.com/build3/admin/index.php

———————————-

Selenium Data Driven Test Case:

public class DataDriven {

public static String line;

public static int Iteration;

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

FileReader file = new FileReader(“C:/Users/gcreddy/Desktop/Input.txt”);

BufferedReader br = new BufferedReader(file);

int count =0;

Iteration =0;

while ((line = br.readLine()) != null){

count = count +1;

if (count > 1) {

Iteration = Iteration + 1;

String [] InputData = line.split(“, “, 2);

WebDriver driver = new FirefoxDriver();

driver.get(“http://www.gcrit.com/build3/admin”);

driver.findElement(By.name(“username”)).sendKeys(InputData[0]);

driver.findElement(By.name(“password”)).sendKeys(InputData[1]);

driver.findElement(By.id(“tdb1”)).click();

String url = driver.getCurrentUrl();

if (url.equals(“http://www.gcrit.com/build3/admin/index.php”)){

System.out.println(“Iteration-“+Iteration+ ” – Admin Login Successful – Passed”);

else {
System.out.println(“Iteration-“+Iteration+ ” – Admin Login Unsuccessful – Failed”);

driver.close();

file.close();

br.close();

———————————-

TestNG Framework Quick Tutorial for Selenium

i) Introduction to TestNG Framework

ii) Install TestNG and write first TestNG Program

iii) Create multiple Test cases and prioritize Test Cases.

iv) Execute multiple Classes / Programs using XML

v) Grouping Test Cases

—————————–

i) Introduction to TestNG Framework

> In Selenium using Java there are two Frameworks available,

1) JUnit

2) TestNG

> TestNG is a Testing Framework designed to simplify a broad range of Testing activities from Unit
Testing to System Testing.

> Initially developed for Unit Testing, now used for all kinds of Testing

> TestNG is an open source Framework where NG Stands for Next Generation.

> TestNG inspired from JUnit (Java platform and NUnit (.NET platform), but introduced some new
functionality.

—————————–
Advantages of TestNG

> TestNG Annotations are easy to create Test Cases

> Test Cases can be grouped and prioritized more easily.

> Supports Parameterization

> Execute Test Batches

> Parallel Test Execution

> Generate HTML Test Reports.

—————————–

ii) Install TestNG and write first TestNG Program

In Eclipse IDE,

> Help Menu

> Install New Software

> Click Add

> Enter name as “TestNG”

> Enter URL as : “http://beust.com/eclipse/”

> Select “TestNG”

> Next > Next > accept License Agreement > finish

—————————–

Write first TestNG Test Case

Manual Test Case: Verify the Title of Gmail Home Page

Test Steps:

i) Launch the Browser

ii) Navigate to “https://www.gmail.com”

Verification Point:

Capture the Page Title and Compare with expected.

Expected: Gmail

Input Data: None—————————–


public class VerifyTitle {

@Test

public void verifyTitle(){

WebDriver driver = new FirefoxDriver();

driver.get(“https://www.gmail.com”);

String pageTitle = driver.getTitle();

Assert.assertEquals (pageTitle, “Gmail”);

driver.close();

—————————–

Note:

1) main method is not used for TestNG programs.

2) TestNG Program contains only methods that contain @Test Annotations

3) If we don’t write @Test Annotation then the method is not going to be executed.

—————————–

iii) Create multiple Test cases and prioritize Test Cases.

public class VerifyTitle {

@Test

public void logout(){

Assert.assertEquals(“Gmail”, “Gmail”);

@Test

public void abcd(){

Assert.assertEquals(“abcd”, “abcd”);

@Test
public void xyz(){

Assert.assertEquals(“Yahoo”, “Yahoo”);

@Test

public void login(){

Assert.assertEquals(“Google”, “Google”);

—————————–

Test Execution Flow as per the Program:

logout

abcd

xyz

login

—————————–

abcd

login

logout

xyz

Note: TestNG Test Cases are executed in Alphabetical Order.

If you want control the Test Execution then use priority attribute or dependsOnMethods attribute

—————————–

Required Flow:

login

abcd

xyz

logout
Using priority attribute

public class VerifyTitle {

@Test(priority = 4)

public void logout(){

Assert.assertEquals(“Gmail”, “Gmail”);

@Test(priority = 2)

public void abcd(){

Assert.assertEquals(“abcd”, “abcd”);

@Test(priority = 3)

public void xyz(){

Assert.assertEquals(“Yahoo”, “Yahoo”);

@Test(priority = 1)

public void login(){

Assert.assertEquals(“Google”, “Google”);

—————————–

Using dependsOnMethods attribute

import org.testng.Assert;

import org.testng.annotations.Test;

public class VerifyTitle {

@Test(dependsOnMethods = {“xyz”})

public void logout(){

Assert.assertEquals(“Gmail”, “Gmail”);
}

@Test(dependsOnMethods = {“login”})

public void abcd(){

Assert.assertEquals(“abcd”, “abcd”);

@Test(dependsOnMethods = {“abcd”})

public void xyz(){

Assert.assertEquals(“Yahoo”, “Yahoo”);

@Test

public void login(){

Assert.assertEquals(“Google”, “Google”);

—————————–

login -Pre condition for every Test case

logout -Post Condition for Evey Test Case

Required Flow:

login

abcd

logout

login

xyz

logout

—————————–

public class VerifyTitle {

@AfterMethod
public void logout(){

System.out.println(“Logout Successful”);

@Test

public void abcd(){

System.out.println(“abcd Successful”);

@Test

public void xyz(){

System.out.println(“xyz Successful”);

@BeforeMethod

public void login(){

System.out.println(“Login Successful”);

—————————–

login -Pre condition for all Test cases in the Program

logout -Post Condition for all Test cases in the Program

Required Flow:

login

xyz

abcd

logout

—————————–

public class VerifyTitle {

@AfterClass
public void logout(){

System.out.println(“Logout Successful”);

@Test(priority = 2)

public void abcd(){

System.out.println(“abcd Successful”);

@Test(priority = 1)

public void xyz(){

System.out.println(“xyz Successful”);

@BeforeClass

public void login(){

System.out.println(“Login Successful”);

—————————–

iv) Execute multiple Classes / Programs using XML

XML file for executing multiple Classes/Programs.

<suite name =”SuiteName”>

<test name = “TestName” >

<classes>

<class name = “Package.Class1Name” />

<class name = “Package.Class2Name” />

<class name = “Package.Class3Name” />

</classes>

</test name = “TestName” >


</suite name =”Suite Name”>

Tags

suite

test

classes

class

—————————–

Navigation to create XML file

Select Java Package > Right Click > New > Others…

> Enter “TestNG” and Select TestNg Class

> Enter source and Package names

> Enter XML file name

> Finish

—————————–

Test Cases:

login

addVendor

addCurrency

addProduct

logout

—————————–

XML File

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

<suite name=”Ecommerce” parallel=”false”>

<test name=”Smoke Tests”>

<classes>

<class name=”abcd.Class1?/>
<class name=”abcd.Class2?/>

</classes>

</test> <!– Test –>

</suite> <!– Suite –>

—————————–

Class 1

public class Class1 {

@BeforeTest

public void login() {

System.out.println(“Login Successful”);

@AfterTest

public void logout() {

System.out.println(“Logout Successful”);

@Test(priority = 1)

public void addVendor() {

System.out.println(“Add Vendor Successful”);

@Test(priority = 3)

public void addProduct() {

System.out.println(“Add product Successful”);

@Test(priority = 2)

public void addCurrency() {

System.out.println(“Add Currency Successful”);

} } --------------------------------------------------------------—————————–
Class 2:

public class Class2 {

/*@BeforeClass

public void login() {

System.out.println(“Login Successful”);

@AfterClass

public void logout() {

System.out.println(“Logout Successful”);

}*/

@Test(priority = 1)

public void deleteVendor() {

System.out.println(“Delete Vendor Successful”);

@Test(priority = 3)

public void deleteProduct() {

System.out.println(“Delete Product Successful”);

@Test(priority = 2)

public void deleteCurrency() {

System.out.println(“Delete Currency Successful”);

—————————–

v) Grouping Test Cases

XML file for grouping Test Cases

<suite name =”Suite Name”>


<test name =”Test Name”>

<groups>

<run>

<include name =”GroupName”/>

</run>

</groups>

<classes>

<class name = “Package.Class1?/>

<class name = “Package.Class1?/>

</classes>

</test name =”Test Name”>

</suite name =”SuiteName”>

—————————–

Tags

suite

test

groups

run

include

classes

class

—————————–

Sanity group

login

search

prepaidRecharge

logout
Regression group

login

advancedSearch

prepaidRecharge

billPayments

logout

—————————–

XML File

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

<suite name=”Suite” parallel=”false”>

<test name=”Test”>

<groups>

<run>

<include name =”Regression”/>

</run>

</groups>

<classes>

<class name=”abcd.Class3?/>

</classes>

</test> <!– Test –>

</suite> <!– Suite –>

—————————–

Class File

public class Class3 {

@Test(groups = {“Sanity”, “Regression”}, priority=1)

public void login() {

System.out.println(“Login Successful”);
}

@Test(groups = {“Sanity”, “Regression”}, priority=10)

public void logout() {

System.out.println(“Logout Successful”);

@Test(groups = {“Sanity”}, priority=2)

public void search() {

System.out.println(“Search Successful”);

@Test(groups = {“Regression”}, priority=2)

public void advancedSearch() {

System.out.println(“Advanced Search Successful”);

@Test (groups = {“Sanity”, “Regression”}, priority=3)

public void prepaidRecharge() {

System.out.println(“Prepaid Recharge Successful”);

@Test (groups = {“Regression”}, priority=4)

public void billPayments() {

System.out.println(“Bill Payments Successful”);

—————————–

Selenium Webdriver Test Cases

1) Launch Browser

2) Verify Gmail Home Page

3) Verify Yahoo Home Page


4) Close Browser

—————————–

TestNG Program:

public class Sample {

public WebDriver driver;

@BeforeClass

public void launchBrowser(){

driver = new FirefoxDriver();

@AfterClass

public void closeBrowser(){

driver.close();

@Test(priority=1)

public void verifyGmailpage(){

driver.get(“https://www.gmail.com”);

Assert.assertEquals(“Gmail”, driver.getTitle());

@Test(priority=2)

public void verifyYahoopage(){

driver.get(“https://in.yahoo.com”);

Assert.assertEquals(“Yahoo”, driver.getTitle());

—————————–

You might also like