Anda di halaman 1dari 292

Day 1 - Basic Java Tutorials For Selenium WebDriver

1. Datatypes In Java
2. String Class In Java
3. if, if else and nested if else In Java
4. for loop In Java
5. while, do while loops In Java
6. One and two dimensional array In Java
7. Methods In Java
8. Access Modifiers In Java
9. Return Type Of Method In Java
10. Static, Non Static Methods, Variables In Java
11. Object In Java
12. Variable Types In Java
13. Constructor In Java
14. Inheritance In Java
15. Interface In Java
16. ArrayList In Java
17. Hashtable In Java
18. Read-Write Text File In Java
19. Exception handling, try-catch-finally, throw and throws In Java
Day 2 - WebDriver Installation And Configuration
1. Introduction of Selenium WebDriver
2. Downloading and installation Of Selenium Webdriver with Eclipse
3. Creating And Running First Webdriver Script
--3.1 Running WebDriver In Google Chrome
Day 3 - Configure JUnit With WebDriver
4. Downloading and installation Of JUnit with Eclipse
--5.1 Creating and running webdriver test with junit
--5.2 Creating and running junit test suite with webdriver
--6.1 Using JUnit Annotations in webdriver
--6.2 @Before/@After VS @BeforeClass/@AfterClass Difference
--6.3 Ignoring JUnit Test from execution
--6.4 Junit Timeout And Expected Exception Test
Day 4 - Generate Test Report Using JUnit
7. Selenium WebDriver Test report Generation using JUnit - 3 Steps
Day 5 - Element Locators In WebDriver
8. Different Ways Of Locating Elements In WebDriver
Day 5 - WebDriver Basic Action Commands With Example

9. WebDriver Basic Action Commands And Operations With Examples


* Open Firefox Browser
* Maximizing Browser Window
* Open URL In Browser
* Clicking On Button
* Submitting Form Using .submit() Method
* Store Text Of Element
* Typing Text In To Text box
* Get Page Title
* Get Current Page URL
* Get Domain Name
* Generating Alert Manually
* Selecting Value From Dropdown Or Listbox
* Deselecting Value From Dropdown Or Listbox
* Navigating Back And Forward
* Verify Element Present
* Capturing Entire Page Screenshot
* Generating Mouse Hover Event
* Handling Multiple Windows
* Verify Element Is Enabled Or Not
* Enable/Disable Element
* Handling Alert, Confirmation and Prompt popup
* Handle Unexpected Alert
Day 6 - WebDriver Wait For Examples Using JUnit And Eclipse
10. How to apply implicit wait in selenium WebDriver script
11. WebDriver Examples * Wait For Element
* Wait For Text
* Wait For Alert
* Wait For Title
* Wait For Element Visible
* Wait For Element Invisible
Day 7 - WebDriver Other Examples
12. WebDriver Other Examples * findElement() And findElements() Difference
* Generating Log In WebDriver
* Creating Object Repository Using Properties File
* Extracting All Links From Page
* Extracting/Reading Table Data
* Handle Dynamic Web Table
* Create And Use Custom Firefox Profile In Selenium WebDriver Test
* Downloading Files Using Selenium WebDriver
* Handling Ajax Auto Suggest Drop List

13. Parameterization/Data Driven Testing


14. Selenium WebDriver Test
Day 8 - TestNG Framework Tutorials
15. Introduction Of TestNG
16. TestNG Installation Steps
17. Similarities and Difference Between TestNG and JUnit
18. Create And Run First TestNG-WebDriver Test
19. TestNg annotations with examples
20. Creating And Running WebDriver Test Suit Using testng.xml File
--20.1 Creating Single Or Multiple Tests For Multiple Classes
--20.2 Creating Test Suite Using Class From Different Packages
--20.3 Creating Test Suite Using Selected Or All Packages
--20.4 Including Only Selected Test Methods In Selenium WebDriver-TestNg
Test
--20.5 testng.xml - Include/Exclude Selenium WebDriver Test Package
--20.6 testng.xml - Using Regular Expression To Include/Exclude Test
Method
--20.7 testng.xml - Skip Test Intentionally Using SkipException()
--20.8 Data driven Testing using @DataProvider Annotation Of TestNG
--20.9 Parallel test execution In multiple browsers using @Parameters
annotation
Day 9 - WebDriver Assertions With TestNG
Hard Assertions
20.1 assertEquals Assertion With Example
20.2 assertNotEquals Assertion With Example
20.3 assertTrue Assertion With Example
20.4 assertFalse Assertion With Example
20.4 assertNull Assertion With Example
20.4 assertNotNull Assertion With Example
Soft Assertion
20.4 Applying TestNG Soft Assertion With Example
Day 10 Common Functions To Use In WebDriver Test
20.1 Common Function To Compare Two Strings
20.2 Common Function To Compare Two Integers
20.3 Common Function To Compare Two Doubles

1. Datatypes In Java
1.Data types - Basic Java Tutorials For Selenium WebDriver
I have received many requests from my blog readers for posting some
basic java tutorials which are really required in selenium webdriver. So
now I have planned to post some basic java tutorial posts which are really
required in selenium webdriver learning and implementation in your
project.
These
tutorials
will
help
you for selenium webdriver interview preparation too. Let we start from
different data types In java which we can use in our selenium webdriver
test preparation.
In java or any other programming languages, data types represents that
which type of values can be stored and what will be the size of that value
or how much memory will be allocated. There are nearest eight different
data types in java like byte, short, int, long, float, double, char, Boolean.
byte and short datatypes are not much more useful in selenium webdriver
so I am skipping them here to decrease your confusions.
int datatype

int data type is useful to store 32 bit integer (Example : 4523) values only.
We can not store decimal (Example 452.23) values in int data type.
Example :
int i = 4523;
long datatype
long datatype is useful to store 64 bit integer(Example : 652345) values.
You can use it when your value is more larger and can not hold it in int.
Same as int datatype, we can not store decimal (Example 452.23) values
in long datatype
Example :
long l = 652345;
double datatype
double datatype is useful to store 64 bit decimal(Example : 56.2354)
values. We can store integer (Example 12456) values too in double
datatype.
Example :
double d1 = 56.2354;
double d2 = 12456;
char datatype
char datatype is useful to store single character(Example : 'd'). It can not
store more than one (Example 'dd') character in it.
Example :
char c = 'd';
boolean datatype
boolean datatype is useful to store only boolean(Example : true) values.
Example :
boolean b = true;
String Class
String is not a data type but it is a class which is useful to store string in
variable.
Example :
String str = "Hello World";
VIEW DIFFERENT FUNCTIONS OF STRING CLASS
Created bellow given example for all these datatypes. Run it in your

eclipse and verify results.


public class datatypes {
public static void main(String[] args) {
int i = 4523; //Can store 32 bit integer values only.
long l = 652345; //Can store 64 bit integer values only.
double d1 = 56.2354;
//Can store 64 bit decimal values.
double d2 = 12456; //We can use it for integer values too.
char c = 'd'; //Can store single character only.
boolean t = true; //Can store only boolean values like true or false.
String str = "Hello World"; //Can store any string values.
System.out.println("Integer Var Is --> "+i);
System.out.println("Long Var Is --> "+l);
System.out.println("double Var d1 Is --> "+d1);
System.out.println("double Var d2 Is --> "+d2);
System.out.println("char Var c Is --> "+c);
System.out.println("boolean Var b Is --> "+t);
System.out.println("boolean Var str Is --> "+str);
}
}
Bellow given result will display in your console at the end of execution.
Integer Var Is --> 4523
Long Var Is --> 652345
double Var d1 Is --> 56.2354
double Var d2 Is --> 12456.0
char Var c Is --> d
boolean Var b Is --> true
String Var str Is --> Hello World
2. String Class In Java
2.String In Java - Tutorials For WebDriver
We have learnt about DIFFERENT DATA TYPES IN JAVA In my past post.
Now, Many peoples are understanding that String Is also a data type. Let
me correct them -> String Is not data type. If string Is not data types then
what Is String? This question can be asked by Interviewer too. String Is an
Inbuilt class of
java. String class has many Inbuilt functions which we can use to perform
different actions on string.
If you don't know, Let me tell you that we have to work with strings very
frequently In selenium WebDriver tests. So you must have knowledge of
useful functions of String class to use them In your selenium webdriver

test development. Let us take simple example of String to understand


different methods of String class.

public class Strng_Example {


public static void main(String[] args) {
String st1 = "This World is Very Nice";
String st2 = " And Beautiful.";
//Comparing two strings. Return true If both match else return false.
System.out.println("st1 equals to st2? -> "+st1.equals(st2));
//Concatenates st2 with st1.
System.out.println("Concatenation of st1 and st2 Is ->
"+st1.concat(st2));
//Retrieve the 9th Indexed character from string.
System.out.println("Character at Index 9 Is -> "+st1.charAt(9));
//Find the length of string.
System.out.println("Length Of St1 -> "+st1.length());
//Converting whole string In lower case.
System.out.println("String In Lowercase -> "+st1.toLowerCase());
//Converting whole string In upper case.
System.out.println("String In uppercase -> "+st1.toUpperCase());
//Retrieve the Index of first 'i' character.
System.out.println("Index of 1st charater i Is -> "+st1.indexOf('i'));
//Retrieve the index of 2nd most 'i' character.
System.out.println("Index of 2nd charater i Is -> "+st1.indexOf('i', 3));
//Retrieve the Index of word 'Very' from string.
System.out.println("Index of word Very Is -> "+st1.indexOf("Very"));
//Converting value From int to string.
int j = 75;
String val2 = String.valueOf(j);
System.out.println("Value Of string val2 Is -> "+val2);
//Converting string to integer.
String val1="50";
int i = Integer.parseInt(val1);
System.out.println("Value Of int i Is -> "+i);

//Print the String starting from 5th Index to 12th Index.


System.out.println("Retrieving sub string from string ->
"+st1.substring(5, 13));
//Split string.
String splt[] = st1.split("Very");
System.out.println("String Part 1 Is -> "+splt[0]);
System.out.println("String Part 2 Is -> "+splt[1]);
//Trim String.
System.out.println("Trimmed st2 -> "+st2.trim());
}
}
If you will look at above example, I have prepared different examples of
string method to take some action or we can say operations on string.
Sort explanation of all above string methods are as bellow.
Two String Comparison
To compare two strings, we can use syntax like st1.equals(st2). It will
return True If both strings are same else It will return False.
Two String Concatenation
Syntax st1.concat(st2) will concatenate st1 with st2.
Retrieving Character from Index
Syntax st1.charAt(9)) will retrieve the character from string st1 located at
9th Index. Index Starts from 0.
Length Of String
st1.length() will return lenght of string st1.
Convert String In Lower Case Letters
st1.toLowerCase() will convert whole string letters In lower case.
Convert String In UpperCase Letters
st1.toUpperCase() will convert whole string letters In upper case.
Retrieving Index Of 1st most character
st1.indexOf('i') will retrieve Index of first most character 'i' from string.
Retrieving Index Of 2nd most character
st1.indexOf('i', 3)) will retrieve Index of second most character 'i' from
string. 3 described the from Index means It will start finding character 'i'
from Index 3. First 'i' has Index 2 so we need to use 3 to find 2nd most
character.
Retrieving Index Of specific word from string
st1.indexOf("Very") will retrieve index of word 'Very' from string.

Convert from Integer To String


String.valueOf(j) will convert value of 'j' from int to string.
Convert from String To Integer
Integer.parseInt(val1) will conver value of 'val1' from string to int.
Retrieving sub string from string
Syntax st1.substring(5, 13) will retrieve string from Index 5 To Index 13.
Split String
String splt[] = st1.split("Very") will split string st1 from word 'Very' and
store both strings In array.
Trim String
If string has white space at beginning or end of the string then you can
use trim function like st2.trim() to remove that white space.
3. if, if else and nested if else In Java

If Else Statement - Basic Java Tutorials For Selenium WebDriver


In my PREVIOUS POST, we have seen different data types in java. It is very
important to learn basic java tutorials If you wants to learn selenium
webdriver with Java. Because If you do not have knowledge of basic java
then you can not create single logical webdriver test case. And also you
can not pass any
company interview. So keep your eyes on these tutorials and I will take
you from basic to advanced java tutorials step by step. In this post, Let me
tell you the usage of If else conditional statements in java.
if, if else and nested if else statements are useful to take the decision
based on conditional match.When you wants to execute some part of code
if condition returns true then you need to use this kind of conditional
statements.
Simple If Statement
Part of code will be executed only if specified condition returns true. If
condition will return false then that code will be not executed.
Example :
if (i<j)
System.out.println("Value Of i("+i+") Is Smaller Than Value Of j("+j+")." );
In above given example, message will be printed only and only if value of
variable i is less than value of variable j.

If else Statement
If condition returns true then part of if block will be executed. If condition
returns false then part of else block will be executed.
Example :
if (i>=j)
{
System.out.println("Value Of i("+i+") Is Greater Than Or Equals To Value
Of j("+j+")." );
}else
{
System.out.println("Value Of i("+i+") Is Smaller Than Value Of j("+j+")." );
}
In above given example, if block's message will be printed if value of
variable i is greater than or equals to value of variable j. else block will be
executed if value of variable i is less than value of variable j.
Nested If Else Statements
You can use nested if else statement when you wants to check multiple
conditions and take decision based on it.
Example :
if (k<i)
{
System.out.println("Value Of k("+k+") Is Less Than Value Of i("+i+")" );
}else if (k>=i && k<=j)
{
System.out.println("Value Of k("+k+") Is In Between Value Of i("+i+") And
Value Of Value Of j("+j+")" );
}else
{
System.out.println("Value Of k("+k+") Is Greater Than Value Of
j("+j+")" );
}
In above given example, first (if) block will be executed if value of variable
k is less than the value of variable i. Second (else if) block will be executed
if value of variable k is greater than or equals to value of variable i and
less than or equals to value of variable j. Third (else) block will be
executed if value of variable k is greater than value of value of variable j.
You can make a chain of if else statement if you wants to check more
conditions.
This way, You can use any of above conditional statement based on your
requirement. Run bellow given example in your eclipse by changing the
values of variables.

public class IfStatements {


public static void main(String[] args) {
int i = 25;
int j = 50;
int k = 24;
//Simple If statement
System.out.println("***Simple If Statement Example***");
if (i<j) //Bellow given message will be printed only if value of variable i is
less than value of variable j.
System.out.println("Value Of i("+i+") Is Smaller Than Value Of
j("+j+")." );
//If Else Statement
System.out.println("");
System.out.println("***If Else Statement Example***");
if (i>=j)//Bellow given message will be printed if value of variable i is
greater than or equals to value of variable j.
{
System.out.println("Value Of i("+i+") Is Greater Than Or Equals To Value
Of j("+j+")." );
}else//Bellow given message will be printed if value of variable i is less
than value of variable j.
{
System.out.println("Value Of i("+i+") Is Smaller Than Value Of
j("+j+")." );
}
//Nested If Else Statement
System.out.println("");
System.out.println("***Nested If Else Statement Part***");
if (k<i)//Bellow given message will be printed if value of variable k is less
than value of variable i.
{
System.out.println("Value Of k("+k+") Is Less Than Value Of i("+i+")" );
}else if (k>=i && k<=j)//Bellow given message will be printed if value of
variable k is greater than or equals to value of variable i and less than or
equals to value of variable j.
{
System.out.println("Value Of k("+k+") Is In Between Value Of i("+i+")
And Value Of Value Of j("+j+")" );
}else //Bellow given message will be printed if value of variable k is
greater than value of variable j.
{

System.out.println("Value Of k("+k+") Is Greater Than Value Of j("+j+")"


);
}
}
}
Bellow given output will be printed in your eclipse console when you will
run above example.
***Simple If Statement Example***
Value Of i(25) Is Smaller Than Value Of j(50).
***If Else Statement Example***
Value Of i(25) Is Smaller Than Value Of j(50).
***Nested If Else Statement Part***
Value Of k(24) Is Less Than Value Of i(25)

4. for loop In Java


for Loop - Basic Java Tutorials For Selenium WebDriver
We have learnt different if else condition statements in my PREVIOUS
POST. Now let we move to loops in java. Loops(for loop, while loop, do
while loop) have very important role in selenium webdriver test case
development with java or any other languages. As you know, sometimes
you need to perform same action
multiple times(Example : 100 or more times) on your web page. Now if
you will write multiple lines of code to perform same action multiple times
then it will increase your code size. For the best practice, you need to use
loops in this kind of situations.
Let me describe you for loop in this post and you can view my NEXT POST
for reading about while loop.
for Loop
There are three parts inside for loop. 1. Variable Initialization, 2. Condition
To Terminate and 3. Increment/Decrements variable. for loop will be
terminated when condition to terminate will becomes false.
Example :
for(int i=0; i<=3; i++){
System.out.println("Value Of Variable i is " +i);
}
Bellow given example is simple example of for loop. run it in your eclipse

and verify the result.


public class forloop {
public static void main(String[] args) {
for(int i=0; i<=3; i++){ //This loop will be executed 4 times
System.out.println("Value Of Variable i is " +i);
}
System.out.println("");
int i=0;
int k = 200;
for(int j=3; j>=i; j--){ //This loop will be executed 4 times
System.out.println("Value Of Variable j is " +j);
k = k-10;
}
System.out.println("");
System.out.println("Value Of Variable k is " +k);
}
}
When you will run above given example, you will get bellow given output.
Value
Value
Value
Value

Of
Of
Of
Of

Variable
Variable
Variable
Variable

i
i
i
i

is
is
is
is

0
1
2
3

Value
Value
Value
Value

Of
Of
Of
Of

Variable
Variable
Variable
Variable

j
j
j
j

is
is
is
is

3
2
1
0

Value Of Variable k is 160


5. while, do while loops In Java
while, do while Loops - Basic Java Tutorials For Selenium WebDriver
As we have learnt in my PREVIOUS POST, loops(for loop, while loop) in
java or any other programming languages are useful to execute block of
code multiple times. You will have to use loops in your selenium webdriver
test very frequently. We have already learnt for loop with different
examples in my previous post.
Now let me describe you while loop and do while loop with practical
examples.
while Loop

Block of code which is written inside while loop will be executed till the
condition of while loop remains true.
Example :
int i = 0;
while(i<=3){
System.out.println("Value Of Variable i Is "+i);
i++;
}
In above given example, while loop will be executed four times.
do while Loop
Same as while loop, do while loop will be executed till the condition
returns true.
Example :
int j=0;
do{
System.out.println("Value Of Variable j Is "+j);
j=j-1;
}while(j>0);
In above given example, while loop will be executed only one time.
Difference between while and do while loop
There is one difference between while and do while loop.

while loop will check condition at the beginning of code block so It


will be executed only if condition (while(i<=3)) returns true.

do while loop will check condition at the end of code block so It will
be executed minimum one time. After 1st time execution, it will
check the condition and if it returns true then code of block will be
executed once more or multiple time.

Disadvantage of while or do while loop


If you will forget to Increment or decrements variable value inside while
loop block then block of code will be executed infinite time.
Example :
int i = 0;
while(i<=3){
System.out.println("Value Of Variable i Is "+i);
}
Above given while loop will be executed infinite time because variable is
not incremented inside while loop block.
Bellow given full example of while and do while loops will clear out your all
doubts. Simple run it in your eclipse and verify result.
public class Whileloop {

public static void main(String[] args) {


//while loop - will be executed till condition returns true.
System.out.println("***while loop example***");
int i = 0; //Variable initialization
while(i<=3){
System.out.println("Value Of Variable i Is "+i);
i++;//Incrementing value of i by 1.
}
//do while loop - will be executed minimum one time without considering
condition.
System.out.println("");
System.out.println("***do while loop example***");
int j=3; //Variable initialization
do{
System.out.println("Value Of Variable j Is "+j);
j=j-1;//Decrementing value of j by 1;
}while(j>=0);
}
}
Output of above given example will be as bellow.
***while loop example***
Value Of Variable i Is 0
Value Of Variable i Is 1
Value Of Variable i Is 2
Value Of Variable i Is 3
***do
Value
Value
Value
Value

while loop example***


Of Variable j Is 3
Of Variable j Is 2
Of Variable j Is 1
Of Variable j Is 0

6. One and two dimensional array In Java


Arrays - Basic Java Tutorials For Selenium WebDriver
What is Array?
As we have learnt in my post about DIFFERENT DATA TYPES, We can store
values in variables based on type of data like int i=5; double d = 12.254;
etc. Now if you wants to store multiple values (10 or 15 or more different
values) in different variables then it will be overhead for you to create and
initialize different
variables for each value. In this situation, you can use array to store
multiple different values in array. An array can store multiple value of

same data type(int, char, String) at the same time and each stored data
location has unique Index. There are two types of array as bellow.
One Dimensional Array

Above given Image describes one dimensional array having one row of
data. One dimensional array is just like spreadsheet with data in one row.
As shown in above Image, Index of array Is starting from 0. Means value
10 has Index 0, 12 has Index 1 and so on and each value can be Identified
by Its Index. We can create and Initialize values In array as shown In
bellow given example.
public class Array_Example {
public static void main(String[] args) {
int a[] = new int[6]; //Array declaration and Creation. 6 is length of array.
a[0] = 10; //initialize 1st array element
a[1] = 12; //initialize 2nd array element
a[2] = 48; //initialize 3rd array element
a[3] = 17; //initialize 4th array element
a[4] = 5; //initialize 5th array element
a[5] = 49; //initialize 6th array element
for(int i=0; i<a.length; i++){
System.out.println(a[i]);
}
}
}
In above example, Length of array a[] is 6 and data type of array is int.
Means we can store max 6 integer values in this array. for loop helps to
print value of each array cell. a.length will return length of array. When
you will run above example in eclipse, You will get bellow given result in
console.
a[0] Holds 10
a[1] Holds 12
a[2] Holds 48
a[3] Holds 17
a[4] Holds 5
a[5] Holds 49
Another way of creating and initializing same one dimensional array is as
shown bellow.
int a[] = {10,12,48,17,5,49};

Two Dimensional Array

Tow dimensional array is just like spreadsheet with multiple rows and
columns having different data in each cell. Each cell will be Identified by
it's unique row and column Index combination(Example str[5][3]). We can
use two dimensional array to store user id and password of different users
as shown in above Image. For above given example Image, We can create
and initialize values in two dimensional array as shown in bellow given
example.
public class Twodimarray {
public static void main(String[] args) {
String str[][] = new String[3][2]; //3 rows, 2 columns
str[0][0]="User1";
str[1][0]="User2";
str[2][0]="User3";
str[0][1]="Password1";
str[1][1]="Password2";
str[2][1]="Password3";
for(int i=0; i<str.length; i++){//This for loop will be total executed 3
times.
for(int j=0; j<str[i].length; j++){//This for loop will be executed for 2
time on every iteration.
System.out.println(str[i][j]);
}
}
}
}
When you will run this example in eclipse, It will return bellow given result
in console.
User1
Password1
User2
Password2
User3
Password3
Other way of creating and initializing same two dimensional array is as
shown bellow.

String str[][] = {{"User1","Password1"},{"User2","Password2"},


{"User3","Password3"}};
7. Methods In Java
Methods In Java - Tutorials For Selenium WebDriver
What Is Method?
In Selenium webdriver test suite, You need to perform some actions
multiple time or in multiple test cases like Login in to Account, Place Order
or any other action. If you will write this kind of (same repeated) actions In
all the test cases then It will becomes overhead for you and will Increase
size
of
your
code.
Instead of that, If you create methods for this kind of operations and then
call that method whenever required then It will be very easy to maintain
your test cases.
Method Is group of statements which is created to perform some actions
or operation when your java code call it from main method. Code written
Inside methods can not be executed by It self. To execute that method
code block, You need to call that method inside main method block. Let
me give you simple example of how to create a method and how to call It
from main method block.
Simple Method Example :
public class Methodexample {
public static void main(String[] args) {
Test1(); //Test1() method called inside main method.
}
public static void Test1(){ //Simple Method - Called from main method.
System.out.println("Test1 Method Executed.");
}
public static void Test2(){ //Simple Method - Not called from main
method.
System.out.println("Test2 Method Executed.");
}
}
If you will run above example then console output will looks like bellow.
Test1 Method Executed.
As per the console output, We can say that Test1() method is executed but
Test2() method is not executed because It Is not called from main method.

Methods will have bellow given different components.


1. Visibility Of Method : You can set your method's visibility by providing
access modifier keywords like public, private, protected at beginning of
method.
VIEW
DETAILED
EXAMPLE.
Example
:
public static void Testing_Nomod(){ //public method
//Block of code
}
2. Return Type Of Method : Any method can have return types like int,
String, double etc.. based on returning value's data type. void means
method
is
not
returning
any
value.
VIEW EXAMPLE OF RETURN TYPE
Example
:
public int Return_Type(){ //This method has int return type.
int i=10;
return i;
}
3. Static or non static method : Method can be static or non static. If you
wants to keep your method as static then you need to use static keyword
with method. If you wants to create non static method then do not write
static keyword with method. VIEW FULL DESCRIPTION ON STATIC AND
NON
STATIC.
Example
:
public void My_Method1(){ //Non static Method
//Block of code
}
public static void My_Method2(){ //Static Method
//Block of code
}
4. Method Name : You can give any name to your method. Always use
method name relative to its functional work.
Example
:
public static void Login(String user, String Pass){ //Login is the method
name.
//Block of code
}
5. Input Parameters To Method : We can pass Input parameters to any

method. Need to write parameter with its data type.


VIEW EXAMPLE OF INPUT PARAMETERS
Example :
public static void Student_Details(int Rollno, String Name){ //Rollno and
Name are input parameters preceded by their data types
//Block of code
}
8. Access Modifiers In Java
Access Modifiers In Java - Java Tutorials For Selenium WebDriver
Access modifiers are the keywords in java by which we can set the level of
access for class, methods, variables and constructors. There are 4
different access modifiers available in java. Now let me try to describe you
how can we use them to set the access for the methods and variables.
First of all let me tell you
meaning of each access modifier keyword and then will give you examples
for them.

public : We can access public methods or variables from all class of


same package or other package.

private : private methods and variables can be accessed only from


same class. We can not access It from other classes or sub classes
of even same package.

protected : protected methods can be accessed from classes of


same package or sub classes of that class.

No Access Modifier : If method have not any access modifier then


we can access It Inside all class of same package only.

Now let me show you practical difference between all these 4 access
modifiers. I have created 3 classes as bellow. Two(Accessmodif, Access) of
them are in same package Test_Package1 and one class (Accessing) is in
other package named Test_Package2 of same project. Class Accessing is
child class of Accessmodif class.
package Test_Package1;
public class Accessmodif {
public static int i=10;
private static String str="Hello";
protected static double d=30.235;

static char c='g';


public static void main(String[] args) {
Testing_pub();
Testing_pri();
Testing_pro();
Testing_Nomod();
}
//Method with public access modifier. Can be accessible by any class.
public static void Testing_pub(){
System.out.println("Testing_pub() Executed");
System.out.println("Value Of i Is "+i);
System.out.println("Value Of str Is "+str);
System.out.println("Value Of d Is "+d);
System.out.println("Value Of c Is "+c);
}
//Method with private access modifier. Can be accessible from same class
only.
private static void Testing_pri(){
System.out.println("Testing_pri() Executed");
}
//Method with protected access modifier. Can be accessible from any
class of same package or sub class of this class.
protected static void Testing_pro(){
System.out.println("Testing_pro() Executed");
}
//Method with no access modifier. Can be accessible by all classes of
same package Only.
static void Testing_Nomod(){
System.out.println("Testing_Nomod() Executed");
}
}
package Test_Package1;
public class Access {
public static void main(String[] args) {
Accessmodif.Testing_pub(); //Can access public methods outside the class
or package.
//Accessmodif.Testing_pri(); - Can not access private methods outside the
class
Accessmodif.Testing_pro(); //Can access protected methods inside same
package class.

Accessmodif.Testing_Nomod(); //Can access no modifier methods inside


same package class.
System.out.println();
System.out.println("Value Of i Is "+Accessmodif.i); //Can access public
variables outside the class or package.
//System.out.println("Value Of str Is "+Accessmodif.str); - Can not access
private variables outside the class
System.out.println("Value Of d Is "+Accessmodif.d); //Can access
protected variables inside same package class.
System.out.println("Value Of c Is "+Accessmodif.c); //Can access no
modifier variables inside same package class.
}
}
package Test_Package2;
import Test_Package1.Accessmodif;
public class Accessing extends Accessmodif{
public static void main(String[] args) {
Testing_pub(); //Can access public methods outside the package.
//Testing_pri(); - Can not access private methods outside the class.
Testing_pro(); //Can access protected methods inside child class.
//Testing_Nomod(); - Can not access no access modifier methods outside
the package.
System.out.println();
System.out.println("Value Of i Is "+i); //Can access public variables
outside the package.
//System.out.println("Value Of str Is "+str); - Can not access private
variables outside the class.
System.out.println("Value Of d Is "+d); //Can access protected variables
inside child class.
//System.out.println("Value Of c Is "+c); - Can not access no access
modifier variables outside the package.
}
}
As per above example, Now its clear that based on access modifiers, we
can access variables, methods, etc.. in any other package or class. If you
will un comment the commented methods or variables from above given
classes, It will show you error related to access level.
9. Return Type Of Method In Java
Return Type Of Method In Java - Tutorials For Selenium WebDriver

We have learnt METHOD IN JAVA and different METHOD ACCESS


MODIFIERS in my previous posts. Now let me introduce you with different
return types of methods in java. You can use two kind of return types with
methods. 1. Void and 2. Any data types. Void means returning nothing and
when your
method is returning some values like Integer, String, double, etc.., You
need to provide return type with method according to returning value's
data types.

int, String, double etc..Data types - If method is returning any value


then you need to provide return type with method like int, String,
Double etc..

void - If method is not returning any value then you can give void as
return type. void means method returning nothing.

Let me give you simple example of int, double and void return type.
package Test_Package1;
public class Return_Types {
static int c;
static double d;
public static void main(String[] args) {
Mul(2,3);
Div(7,3);
System.out.println("Value of c Is "+c);
System.out.println("Value of d Is "+d);
Message();
}
//This method is returning integer value. It's return type is int.
public static int Mul(int a, int b){
c=a*b;
return c;
}
//This method is returning double value. It's return type is double.
public static double Div(double a, double b){
d=a/b;
return d;
}
//This method is returning nothing so there is used void return type.
public static void Message(){
System.out.println("Test Message");
}
}
If you see in above example, I have used three methods (Mul, Div and
Message) and called all three methods in main method to execute them.

Method Mul is returning multiplied integer value in variable c so I


have used int data type as return type with Mul method.

Method Div is returning division of two values in variable d so I have


used double data type as return type with Div method.

Method Message is returning nothing so I need to use void return


type with It.

10. Static, Non Static Methods, Variables In Java


Java Tutorials For Selenium WebDriver - Static And Non Static Methods
Right now we are learning different components of methods in java as
described in THIS POST. You can read about use of different ACCESS
MODIFIERS and RETURN TYPES of method If you are not aware about it.
One another component of method Is It can be static or non static. Static
keyword with
method Is describes that this method Is static and If method do not have
static keyword then that method Is non static. Same rule Is applied for
variables too. Static means stable and non static means unstable in
common words. There are several difference between static and not static
methods In java as described bellow.
Main Difference Between Static And Non Static Methods In Java

We can call static methods directly while we can not call non static
methods directly. You need to create and instantiate an object of
class for calling non static methods. VIEW THIS POST to learn about
object In Java.

Non static stuff (methods, variables) can not be accessible Inside


static methods Means we can access only static stuff Inside static
methods. Opposite to It, Non static method do not have any such
restrictions. We can access static and non static both kind of stuffs
Inside non static methods

Static method Is associated with the class while non static method Is
associated with an object.

Now Let us look at one simple example of static and non static methods
and variables. Bellow given example describes you how to access static
and non static stuff Inside static and non static methods of same class or
different class.
Created Two different class as bellow.
package Test_Package1;

public class static_nonstatic {


static int wheel = 2;
int price = 25000;
public static void main(String[] args) { //static method.
//Can access static methods directly Inside static method.
byke1();
//Can access static variables directly Inside static method.
System.out.println("Main static method : wheels = "+wheel);
//Can not access non static variables directly inside static method.
//System.out.println("Main static method : wheels = "+price);
//Can not access non static methods directly inside static method.
//byke2();
//Created object of class to access non static stuff Inside static method.
static_nonstatic sn = new static_nonstatic();
//Now We can access non static methods of class Inside static methods
using object reference.
sn.byke2();
//Now We can access non static variables of class Inside static methods
using object reference.
System.out.println("Main static method : price = "+sn.price);
}
public static void byke1(){ //static method.
//Can access static variables directly Inside static method.
System.out.println("byke1 static method : wheels = "+wheel);
//Can not access non static variables directly inside static method.
//System.out.println(price);
}
public void byke2(){ //non static method.
//Can access static variable directly inside non static method.
System.out.println("byke2 Non static method : wheels = "+wheel);
//Can access non static variable directly inside non static method.
System.out.println("byke2 Non static method : price = "+price);
//Can access static methods directly Inside non static method.
byke1();
}
}

package Test_Package1;
public class static_ousideclass {
public static void main(String[] args) { //static method.
//Can call static function from other class directly using class name.
static_nonstatic.byke1();
//Can call static variables from other class directly using class name.
System.out.println("Using static variable of other
class"+static_nonstatic.wheel);
//Created object of class static_nonstatic to access non static stuff from
that class.
static_nonstatic oc = new static_nonstatic();
//Now We can access non static variables of other class Inside static
methods using object reference.
System.out.println("Accessing non static variable outside the class :
"+oc.price);
//Now We can access non static methods of other class Inside static
methods using object reference.
oc.byke2();
}
}
As you can see in above examples, we can access only static stuff Inside
any static methods directly. If you wants to access static method or
variable Inside different class then you can access It using simply class
name as shown In above example. You must have to create object of class
to access non static method or variable Inside static method (byke1) of
same class or different class(main method of 2nd class).
On other side, we can access static and non static methods and variables
directly inside non static method (byke2). There is not any such access
restrictions.
11. Object In Java
Selenium WebDriver Java Tutorials - Object In Java
What Is An Object In Java?

If Interviewer ask you this question then your answer should be like this :
Object Is an Instance of class. In other words we can say object Is bundle
of related methods and variables. Every object has Its own states and
behavior. Objects are generally used with constructors In java.
Understanding of object Is very
Important for Selenium WebDriver learner because we have to create and
use objects In our test case development. We can create multiple objects
for the same class having Its own property.
Let us take one real world scenario to understand object clearly. Simplest
example Is bicycle Is an object of vehicle class having Its own states and
behavior. Same way, motorcycle Is another object of vehicle class. Few
properties for both the objects are same like wheels=2, handle=1. Few
properties for both the objects are different like price, color, speed etc..
How to create object?
You can create object of class vehicle using new keyword as bellow.
public class vehicle {
public static void main(String[] args) {
//Created object for vehicle class using new keyword.
//bicycle is the reference variable of this object.
vehicle bicycle = new vehicle("Black");
}
//Constructor with color parameter passed. It will retrieve value from
object vehicle.
public vehicle(String color){
//Retrieved value will be printed.
System.out.println("Color Of vehicle Is "+color);
}
}
Console Output will looks like bellow when you will run above example.
Color Of vehicle Is Black
In above example, Used one constructor to pass the value of object. We
will look about constructor In my upcoming post. Please remember here
one thing - bicycle Is not an object. It Is reference variable of object
vehicle. Based on this example, Now we can say that object has three
parts as bellow.

Declaration : Variable declaration for object. In this example, bicycle


is the reference variable for object.

Instantiation : Object creation using new keyword Is called


as Instantiation.

Initialization : Call to a constructor Is known as object initialization.

As described In PREVIOUS POST, You can use object of class to access non
static variables or methods of class in different class too. This way you can
use object of class and also you can create multiple objects of any class.
Bellow given example will show you how to create multiple object of class
to pass different kind of multiple values In constructor.
public class vehicle {
public static void main(String[] args) {
//Create 2 objects of class. Both have different reference
variables.
vehicle bicycle = new vehicle("black", 2, 4500, 3.7);
vehicle motorcycle = new vehicle("Blue", 2, 67000, 74.6);
}
public vehicle(String color, int wheels, int price, double speed){
System.out.println("Color = "+color+", Wheels = "+wheels+", Price =
"+price+", Speed = "+speed);
}
}
Output of above program will looks like bellow.
Color = black, Wheels = 2, Price = 4500, Speed = 3.7
Color = Blue, Wheels = 2, Price = 67000, Speed = 74.6
12. Variable Types In Java
Variable Types In Java - WebDriver Tutorials With Java
Before learning about variable types In java, I recommend you to read my
posts related to variable's DATA TYPES, ACCESS MODIFIERS and STATIC
AND NON STATIC VARIABLES. As you know, Variable provide us a memory
space (based on type and size of declared variable) to store a value. There
are different three types of variables available In java as bellow.
1. Local Variables

Variables which are declared Inside methods or constructor are


called as local variables for that method or constructor.

Variables declared Inside method or constructor are limited for that


method or constructor only. You can not access to It outside that
method or constructor.

You can not use access modifiers with local variables because they
are limited to that method or constructor block only.

Need to initialize the value of local variables before using It because


there Is not any default value assigned to local variables.

2. Instance Variables (Non Static)

Instance variables are declared on class level which is parallel to


methods or constructors (outside the method or constructor block).

Instance variables are generally used with objects. So they are


created and destroyed with object creation and destruction.

Instance(non static) variables are accessible directly by all the non


static methods and constructors of that class.

If you wants to access Instance(non static) variables Inside static


method, You needs to create object of that class.

Instance variables are always Initialized with Its default values


based on Its data types.

You can access Instance variable directly (by Its name) Inside same
class. If you wants to access It outside the class then you have to
provide object reference with variable name.

Vast usage of Instance variables in java programs and selenium


webdriver tests.

3. Class Variables (Static)

Same as Instance variables, Class variables are declared on class


level (outside the method or constructor block). Only difference
Is class variables are declared using static keyword.

Class variables are used In rare case like when It Is predefined that
value of variable will never change. In that case we can use class
variables.

Class variables are created on program start and destroyed on


program end.

Class variables are visible to all methods and constructors of class.


Class variables are visible to other class based on Its access
modifiers. Generally they are public.

We can access class variables directly using Its name Inside same
class. If you wants to access It outside the class then you need to
use class name with variable.

Bellow given example will give you some Idea about all three types of
variables. Created two class to show you how to access class variable
inside other class. Both these class will show you the access levels of all
three types of variables.
public class Collage1 {
//Class Variables - Collage name will be same for both departments so
declared as class(static) variable.
public static String Collage_Name = "A1 Collage";
//Instance Variables
private String Department = "Computer Engineering";
private String name;
private double percentile;
public static void main(String[] args) {//Static Method
//Can access class variable directly If needed. i.e. Collage_Name
Collage1 student1 = new Collage1("Robert");
student1.setPercentage(67.32);
student1.print_details();
//Can access Instance variable using object reference If needed.
//Example : student1.name = "Robert";
Collage1 student2 = new Collage1("Alex");
student2.setPercentage(72.95);
student2.print_details();
}
public Collage1(String student_name){//Constructor
//Can access Instance variable directly Inside constructor.
name = student_name;
}
public void setPercentage(double perc){
//Can access Instance variable directly Inside non static method.
percentile = perc;
}
public void print_details(){
int Year = 2014; //Local Variable - Can not access It outside this method.
System.out.println("Resultg Of Year = "+Year);
System.out.println("Student's Collage Name = "+Collage_Name);
System.out.println("Student's Department = "+Department);
System.out.println("Student's Name = "+name);
System.out.println("Student's percentile = "+percentile+"%");
System.out.println("**********************");
}
}

Console output will looks like bellow.


Resultg Of Year = 2014
Student's Collage Name = A1 Collage
Student's Department = Computer Engineering
Student's Name = Robert
Student's percentile = 67.32%
**********************
Resultg Of Year = 2014
Student's Collage Name = A1 Collage
Student's Department = Computer Engineering
Student's Name = Alex
Student's percentile = 72.95%
**********************
public class Collage2 {
private String Department = "Mechanical Engineering";
private String name;
private double percentile;
public static void main(String[] args) {
Collage2 student1 = new Collage2("Smith");
student1.setPercentage(57.35);
student1.print_details();
}
public Collage2(String student_name){
name = student_name;
}
public void setPercentage(double perc){
percentile = perc;
}
public void print_details(){
int Year = 2014;
System.out.println("Resultg Of Year = "+Year);
//Can access other class's class variable using that class name.
System.out.println("Student's Collage Name =
"+Collage1.Collage_Name);
System.out.println("Student's Department = "+Department);
System.out.println("Student's Name = "+name);
System.out.println("Student's percentile = "+percentile+"%");
System.out.println("**********************");
}
}
Console output will looks like bellow.

Resultg Of Year = 2014


Student's Collage Name = A1 Collage
Student's Department = Mechanical Engineering
Student's Name = Smith
Student's percentile = 57.35%
**********************

13. Constructor In Java


Selenium WebDriver Java Tutorials : Constructors
What Is Constructor In Java?
If interviewer asks you a definition of constructor then you can give him
answer like : Constructor Is a code block which Is Called and executed at
the time of object creation and constructs the values (i.e. data) for object
and that's why It Is known as constructor. Each class have default no
argument constructor In Java If
you have not specified any explicit constructor for that class.In java,
Constructor looks like methods but bellow given properties of constructor
are differentiate them from the methods. You can VIEW TUTORIALS OF
METHODS IN JAVA.
Constructor Creation Rules

Name of the constructor must be same as class name. Means If your


class name Is Student then constructor name must be Student.

Constructor must have not any return types.

Same as methods, We can pass parameters to constructors. Let me show


you simple example of parameterized cunstructor In java. You can also
view my PREVIOUS POST to see the example of constructor.
public class Student {
public static void main(String[] args) {
//Two different objects created with value.
Student stdn1 = new Student("Michael");
Student stdn2 = new Student("Robert");
}
//Constructor with parameter to pass values of object
//Name of constructor Is same as class name.
public Student(String name){
String stdnname = name;
System.out.println("Student's Name Is "+stdnname);
}

}
Console output will looks like bellow.
Student's Name Is Michael
Student's Name Is Robert
In above example, Constructor will be called at the time of objects
creation. Constructor will pass the values of objects one by to print them.
Constructor Overloading
As we know, Constructors name must be same as class name, When you
create more than one constructors with same name but different
parameters In same class Is called constructor overloading. So question Is
why constructor overloading Is required? Constructor overloading Is useful
when you wants to construct your object In different way or we can say
using different number of parameters. You will understand It better when
we will look at simple example but before that let me tell some basic rules
of constructor overloading.

Two constructors with same arguments are not allowed for


constructor overloading.

You need to use this() keyword to call overloaded constructor.

If you are calling constructor from overloaded


using this() keyword, It must be first statement.

It is best practice to call constructor from overloaded constructor to


make It easy to maintain.

constructor

Bellow given example shows best example of constructor overloading.


public class Student {
String finame;//Instance variable
String miname;//Instance Variable
public static void main(String[] args) {
Student stdn1 = new Student("Jim");
Student stdn2 = new Student("Mary", "Elizabeth");
}
//Constructor with one argument.
public Student(String fname){
finame = fname;//Local Variable
System.out.println("1. First Name Is "+finame);
}
//Overloaded Constructor with two arguments.
public Student(String fname, String mname){
finame = fname;

miname = mname;
System.out.println("2. First Name Is "+finame);
System.out.println("2. Middle Name Is "+miname);
}
}
Console output will looks like bellow.
1. First Name Is Jim
2. First Name Is Mary
2. Middle Name Is Elizabeth
We can do same thing using single object creation too using this()
keyword as bellow.
public class Student {
String finame;
String miname;
public static void main(String[] args) {
Student stdn2 = new Student("Mary", "Elizabeth");
}
//Constructor with one argument.
public Student(String fname){
finame = fname;
System.out.println("1. First Name Is "+finame);
}
//Overloaded Constructor with two arguments.
public Student(String fname, String mname){
this("Jim"); //1st constructor Is called using this keyword.
finame = fname;
miname = mname;
System.out.println("2. First Name Is "+finame);
System.out.println("2. Middle Name Is "+miname);
}
}
If you will run above example then console's output will be same but you
can see we have created only one object Inside main method. Used this
keyword In overloaded constructor to call another constructor.
14. Inheritance In Java
Inheritance In Java : Tutorials For Selenium WebDriver
Till now we have learnt many tutorials on java like Methods, Access
Modifiers, Static and Non Static, Object, Constructor, and Many More
Tutorials On Java... All these java object oriented concept tutorials are very

much useful in selenium webdriver test case development. That's why I


recommend you all
to learn them very carefully. All these tutorials will also helps you to pass
selenium webdriver Interview. Now let me take you one step ahead to
Inheritance In java.
What Is Inheritance In Java?
Inheritance(parent-child) Is very useful concept of java object oriented
programming language by which we can reuse the code of parent class.
Inheritance Is providing us a mechanism by which we can inherit the
properties of parent class In to child class. Example : Audi class Is child
class of Car class then Audi class can access/use all the non
private properties
(methods,
variables..etc)
of
Car class.
Using
Inheritance, we can reuse the code of parent class In to child class so that
size of code will decrease. Maintenance of code will be also very easy.
VIEW EXAMPLE OF USING INHERITANCE IN SELENIUM WEBDRIVER
extends keyword Is used to Inherit child class from parent class. Let me
show you very simple example of Inheritance In java. In this example, Car
class Is parent class of Audi class so all the non private properties of Car
class are Inherited and able to use In Audi class.
Parent Class
public class Car {//Car Class Is Parent Class Of Audi Class
private String type="Vehicle";
public static int wheels = 4;
public String color = "blue";
String fuel = "Petrol";
public String getfuel(){
return fuel;
}
protected void Seats(){
int seat = 4;
System.out.println("Car Seats = "+seat);
}
}
Child Class or Sub Class
public class Audi extends Car{//Audi Is child Class Of Car Class.
public int speed=150;
public static void main(String[] args) {
Audi A = new Audi();
A.printdetails();

//Can access instance variable of parent class using object reference of


child class Inside static methods.
System.out.println("Color Of Audi = "+A.color);
//Can access non static method of parent class using object reference of
child class Inside static methods.
System.out.println("Fuel Of Audi = "+A.getfuel());
}
public void printdetails(){
//Can access class variables of parent class directly Inside child class non
static methods.
System.out.println("Wheels Of Audi = "+wheels);
System.out.println("Speed Of Audi = "+speed);
//Can access non static methods of parent class directly Inside child class
non static methods.
Seats();
//Can not access private variable of parent class In child class.
//System.out.println("Wheels Of Audi = "+type);
}
}
Output of above example will looks like bellow.
Wheels Of Audi = 4
Speed Of Audi = 150
Car Seats = 4
Color Of Audi = blue
Fuel Of Audi = Petrol
If you will study above example carefully, You can understand It easily that
In child class, we can access only non private members of parent class.
This Is just basic example of Inheritance In Java.
Overriding
In sub class, When you create a method with same signature, return types
and arguments of parent class's method then that sub class's method Is
known as overridden method and It Is called as overriding In java.
Overriding Is useful to change to the behavior of parent class methods.
Let me show you simple example of method overriding In java.
Consider same above given example. Generally all cars have 4 seats so
we have created Seats() method with 4 seat variable. But supposing ford
car has 6 seats and I wants to print 6 seats for Ford car. In this case we
can use method overriding In Ford class as bellow. For this example,
Consider Car class of above example as parent class of Ford class. Here
method Seats() Is overridden In sub class.
public class Ford extends Car{//Ford Is child Class Of Car Class.
public static void main(String[] args) {

Car C = new Ford();//Created Ford Class object with Car Class reference.
C.Seats();
}
//Parent class method Seats Is overridden In child class.
protected void Seats(){
int seat = 6;
System.out.println("Audi Seats = "+seat);
}
}
Output of above example will looks like bellow.
Audi Seats = 6
Here, method of sub class Is called at place of parent class. Another main
thing to notice here Is we have created object of child class but reference
Is given of parent class.
15. Interface In Java
Interface In Java : Tutorials For Selenium Webdriver
I described about Inheritance and method overriding In my PREVIOUS
POST so I am suggesting you to read that post, Specially method
overriding concept before learning about Interface In Java. If you will go
for selenium webdriver Interview then Interviewer will ask you first
question : What Is WebDriver? Peoples
will give different different answers but right answer Is WebDriver Is an
Interface. So It Is most Important thing for all selenium webdriver learner
to understand an Interface properly.
What Is An Interface And Why To Use It?
Using Interface, We can create a contract or we can say set of rules for
behavior of application. Interface Is looks like class but It Is not class.
When you implements that Interface In any class then all those Interface
rules must be applied on that class. In sort, If you Implement an Interface
on class then you must have to override all the methods of Interface In
your class. Interface will create Rules To Follow structure for class where It
Is Implemented. This way, If you look at the code of Interface, You can get
Idea about your program business logic. When you are designing big
architecture applications like selenium webdriver, You can use Interface to
define business logic at Initial level.
Interface can be Implemented with any class using implements keyword.
There are set of rules to be followed for creating an Interface. Let me tell
you all these rules first and then give you an example of an Interface.

Interface can not hold constructor.

Interface can not hold instance fields/variables.

Interface can not hold static methods.

You can not instantiate/create object of an Interface.

Variables Inside Interface must be static and mandatory to initialize


the variable.

Any class can Implement Interface but can not extend Interface.

Can write body less methods Inside Interface.

By default all the methods and variables of Interface are public so


no need to provide access modifiers.

How To Add Interface In Your Project


To add Interface In your project, Right click on package and go to -> New
-> Interface. It will open New java Interface popup. Give any name to
Interface(Example : College) and click on save button. It will add
College.java Interface file under your package.

Now let us look at simple example of Interface.

Create One Interface file with name = College.java as shown In


bellow example.

Create 3 class file with name = Computer.java, Mechanical.java


and TestCollege.java as shown In bellow example.

College.java
public interface College {//Interface file
//Initialized static variable.
//No need to write static because It Is by default static.
String Collegename = "XYZ";
//Created non static methods without body.
void StudentDetails();
void StudentResult();
}
Computer.java
//Class file Implemented with Interface file using implements keyword.
public class Computer implements College {
//@Override annotation describes that methods are overridden on
interface method.
//Methods name, return type are same as methods of an Interface.
@Override
public void StudentDetails() {
System.out.println("Computer Dept. Student Detail Part");
}
@Override
public void StudentResult() {
System.out.println("Computer Dept. Student Result Part");
}
}
Mechanical.java
//Class file Implemented with Interface file using implements keyword.
public class Mechanical implements College{
@Override
public void StudentDetails() {
System.out.println("Mechanical Dept. Student Detail Part");
}
@Override
public void StudentResult() {

System.out.println("Mechanical Dept. Student Result Part");


}
}
TestCollege.java
public class TestCollege {//Class file. No need to implement Interface.
public static void main(String[] args) {
//Can access Interface variable directly using Interface name.
System.out.println(College.Collegename+" Collage student details.");
//Created Computer class object with reference of interface College.
College compdept = new Computer();
//Methods will be called from Computer class.
compdept.StudentDetails();
compdept.StudentResult();
//Created Mechanical class object with reference of interface College.
College mecdept = new Mechanical();
//Methods will be called from Mechanical class.
mecdept.StudentDetails();
mecdept.StudentResult();
}
}
Now If you will run TestCollege.java file, Output will looks like bellow.
XYZ Collage student details.
Computer Dept. Student Detail Part
Computer Dept. Student Result Part
Mechanical Dept. Student Detail Part
Mechanical Dept. Student Result Part
Selenium WebDriver And Interface
Simple example of Interface In selenium WebDriver Is WebDriver
Interface. When you are Initializing any browser using selenium
WebDriver, You are writing statements like bellow.
WebDriver driver = new FirefoxDriver();
Or
WebDriver driver = new ChromeDriver();
You can view more examples of selenium WebDriver on THIS PAGE.
Here, WebDriver Is Interface and FirefoxDriver and ChromeDriver are the
class files where WebDriver Interface Is Implemented.
16. ArrayList In Java

WebDriver Tutorial : ArrayList Class In Java


In THIS POST, I have described about one and two dimensional array In
Java. Then question Is what Is arraylist In java and why we need It?
Interviewer can ask you this question then you can give him answer like :
arraylist Is a class that Implements list Interface In java which supports
dynamic array means size of
array can grow as needed. As you know, We can create only fixed size
array to store values Inside It and that Is the limitation/drawback of array
because when you don't know how many values you needs to store In
array then how can you provide/define size of array? ArrayList helps us to
overcome this limitation of array because It can re-size automatically by
Itself.
So finally we can say that when you don't know how many values you
have to store In array, You can use ArrayList at place of simple array. We
have to use arraylist many times In our selenium webdriver test case
development. Example : Store all links from page, store all buttons Id from
page etc.. In all such case, You will not aware about how many values you
have to store.
VIEW NEXT POST to learn about hashtable In Java for selenium webdriver
Bellow given example will show you how to create and work with arraylist
class In java. Same thing we will use In selenium WebDriver test case
development to store values.
//Import ArrayList class header file
import java.util.ArrayList;
public class ArrayList_Example {
public static void main(String[] args) {
//Create object of ArrayList class. It will store only string values.
ArrayList<String> Sample = new ArrayList<String>();
//Now you can store any number of values In this arraylist as bellow. Size
constrain will comes never.
Sample.add("button1"); //Putting an Item In arraylist at Index = 0.
Sample.add("button2"); //Putting an Item In arraylist at Index = 1.
Sample.add("button3"); //Putting an Item In arraylist at Index = 2.
Sample.add("button4"); //Putting an Item In arraylist at Index = 3.
for(int i=0; i<Sample.size();i++){//loop will execute till size of arraylist.
System.out.println(Sample.get(i)); //print arraylist values one by one.
}
System.out.println("*************************");
//To get the Index of an Item from arraylist.
int ItemIndex = Sample.indexOf("button3");

System.out.println("Index Of button3 Item = "+ItemIndex);


System.out.println("*************************");
Sample.remove(1);//To remove an Item from arraylist.
for(int i=0; i<Sample.size();i++){
System.out.println(Sample.get(i));
}
System.out.println("*************************");
Sample.set(2, "Button8");//To reset value of an arraylist item.
for(int i=0; i<Sample.size();i++){
System.out.println(Sample.get(i));
}
}
}
In above example, I have described how to created arraylist object, how to
add values In arraylist, How to get Index of arraylist Item, How to remove
arraylist Item, How to reset arraylist Item. You can do many more actions
on arraylist object.
17. Hashtable In Java
WebDriver Java Tutorials : Hashtable
As we have learnt In my PREVIOUS POST, Using ArrayList Is very good
alternative of array when you don't know how many values you have to
store In array because ArrayList Is automatic dynamic growing array by
Index. One more thing we needs to use In selenium webdriver Is
Hashtable. We will learn only
basic thing about Hashtable to use It In our selenium WebDriver Test case
development.
What Is Hashtable?
Hashtable Is a class In java and provides us a structure to store key and its
value as a pair In table format. Means we can store value with Its key and
can access that value using Its key. There Is not any Index of value In
Hashtable. Key's Hashcode will be used to map the value with key In
Heshtable. Let me show you very simple example of Hashtable.
//Import Hashtable header file.
import java.util.Hashtable;
public class Hash {
public static void main(String[] args) {
//Created hashtable class object to use Its different properties.
Hashtable<String, Integer> t1 = new Hashtable<String, Integer>();

t1.put("Legs", 4); //Store value 4 In key = Legs


t1.put("Eyes",2); //Store value 2 In key = Eyes
t1.put("Mouth",1); //Store value 1 In key = Mouth
//Accessing hash table values using keys.
System.out.println("Animal Legs = " +t1.get("Legs"));
System.out.println("Animal Eyes = " +t1.get("Eyes"));
System.out.println("Animal Mouth = " +t1.get("Mouth"));
}
}
Need More Tutorials On Java And Selenium WebDriver? VISIT THIS PAGE
As you see In above example, I have created object of Java Hashtable
class and then store values with Its unique keys. Then I have used keys to
access and print Its values. This way we can store and access values from
hash table whenever required.
18. Read-Write Text File In Java
Read-Write Text File In Java - Tutorials For WebDriver
We have learnt about String class and Its different functions In my
PREVIOUS POST. Now our next topic Is How to write In to text file or How
to read text file In java. Many times you will need reading or writing text
file In your selenium webdriver test case development. For Example, You
are reading some large data
from web page and wants to store It In text file to use It somewhere else
In future. Same way, You have to read data from file for some purpose.
It Is very easy to Create, Write and read text file In java. We can use java
built in class File to create new file, FileWriter and BufferedWriter class to
write In to file, FileReader and BufferedReader class to read text file.
Bellow given example will first of all create temp.txt file In D: drive and
then write two line In to It. Then It will read both lines one by one from
text file using while loop and print In console. You can use bellow given
example code for reading or writing text file In your selenium webdriver
test case whenever needed.
import
import
import
import
import
import

java.io.BufferedReader;
java.io.BufferedWriter;
java.io.File;
java.io.FileReader;
java.io.FileWriter;
java.io.IOException;

public class RW_File {

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


//Create File In D: Driver.
String TestFile = "D:\\temp.txt";
File FC = new File(TestFile);//Created object of java File class.
FC.createNewFile();//Create file.
//Writing In to file.
//Create Object of java FileWriter and BufferedWriter class.
FileWriter FW = new FileWriter(TestFile);
BufferedWriter BW = new BufferedWriter(FW);
BW.write("This Is First Line."); //Writing In To File.
BW.newLine();//To write next string on new line.
BW.write("This Is Second Line."); //Writing In To File.
BW.close();
//Reading from file.
//Create Object of java FileReader and BufferedReader class.
FileReader FR = new FileReader(TestFile);
BufferedReader BR = new BufferedReader(FR);
String Content = "";
//Loop to read all lines one by one from file and print It.
while((Content = BR.readLine())!= null){
System.out.println(Content);
}
}
}
This way we can read and write text file In java for your selenium
webdriver test case development.
19. Exception handling, try-catch-finally, throw and throws In Java
How To Handle Exception In Java : Tutorials For Selenium WebDriver
Anyone don't like exceptions and at the same time, anyone can not hide
himself from exceptions when running webdriver tests because (What Is
An Exception? :->) exception Is an error event generated during the
execution of webdriver test case or java program which disrupts test
execution In between. Exception
can arise due to the many reasons like, network connection or hardware
failure, Invalid data entered by user, DB server down etc.. So all these
things can happens any time when you run your selenium webdriver test
case and we can not stop It. So Instead of thinking about stopping
exception(Which Is not possible) during run time, Think about handling
exceptions. Java provides very good exception handling mechanism to
recover from this kind of errors. Let us learn different ways of handling
exception In java.
There are two types of exceptions In java as bellow.

1. Checked Exception :
Checked exceptions are those exceptions which are checked during
compile time and needs catch block to caught that exception during
compilation. If compiler will not find catch block then It will throw
compilation error. Very simple example of checked exception Is using
Thread.sleep(5000); statement In your code. If you will not put this
statement Inside try catch block then It will not allow you to compile your
program.
2. Unchecked Exceptions :
Unchecked exception are those exception which are not checked during
compile time. Generally checked exceptions occurred due to the error In
code during run time. Simplest example of unchecked exception Is int i =
4/0;. This statement will throws / by zero exception during run time.
Handling exceptions using try-catch block
We need to place try catch block around that code which might generate
exception. In bellow given example, System.out.println(a[9]); Is written
Intentionally to generate an exception. If you see, that statement Is
written Inside try block so If that statement throw an exception - catch
block can caught and handle It.
public class Handle_exce {
public static void main(String[] args) {
int a[] = {3,1,6};
try { //If any exception arise Inside this try block, Control will goes to
catch block.
System.out.println("Before Exception");
//unchecked exception
System.out.println(a[9]);//Exception will arise here
because we have only 3 values In array.
System.out.println("After Exception");
}catch(Exception e){
System.out.println("Exception Is "+e);
}
System.out.println("Outside The try catch.");
}
}
If you will run above example In your eclipse, try block will be
executed. "Before Exception" statement will be printed In console and
Next statement will generate an exception so "After Exception" statement
will be not printed In console and control will goes to catch block to handle
that exception.
Always use try catch block to log your exception In selenium webdriver
reports.

Handling exceptions using throws keyword


Another way of handling exception Is using throws keyword with method
as shown In bellow given example. Supposing you have a throwexc
method which Is throwing some exception and this method Is called from
some other method catchexc. Now you wants to handle exception of
throwexc method In to catchexc method then you need to use throws
keyword with throwexc method.
public class Handle_exce {
public static void main(String[] args) {
catchexc();
}
private static void catchexc() {
try {
//throwexc() Method called.
throwexc();
} catch (ArithmeticException e) { //Exception of throwexc() will be
caught here and take required action.
System.out.println("Devide by 0 error.");
}
}
//This method will throw ArithmeticException divide by 0.
private static void throwexc() throws ArithmeticException {
int i=15/0;
}
}
In above given example, Exception of throwexc() Is handled Inside
catchexc() method.
Using throw Keyword To Throw An Exception Explicitly
Difference between throw and throws In java :
As we learnt, throws keyword Is useful to throw those exceptions to calling
methods which are not handled Inside called methods. Throw keyword has
a different work - throw keyword Is useful to throw an exception explicitly
whenever required. This Is the difference between throw and throws In
java. Interviewer can ask this question. Let us look at practical example.
public class Handle_exce {
public static void main(String[] args) {
catchexc();
}
private static void catchexc() {
try {
//throwexc() Method called.

throwexc();
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Array Index out of bound exception.");
}
}
private static void throwexc() {
//This statement will throw ArrayIndexOutOfBoundsException exception.
throw new ArrayIndexOutOfBoundsException();
}
}
In above example, ArrayIndexOutOfBoundsException exception will be
thrown by throw keyword of throwexc method.
finally keyword and Its use
finally keyword Is used with try catch block at the end of try catch block.
Code written Inside finally block will be executed always regardless of
exception Is occurred or not. Main intention of using finally with try catch
block Is : If you wants to perform some action without considering
exception occurred or not. finally block will be executed In both the cases.
Let us see simple example of finally.
public class Handle_exce {
public static void main(String[] args) {
try{
int i=5/0; //Exception will be thrown.
System.out.println("Value Of i Is "+i);//This statement will be not
executed.
}catch (Exception e)//Exception will be caught.
{
System.out.println("Inside catch."+e);//print the exception.
}finally//finally block will be executed.
{
System.out.println("Inside finally. Please take appropriate action");
}
try{
int j=5/2; //Exception will be not thrown.
System.out.println("Value Of j Is "+j);//This statement will be executed.
}catch (Exception e)//No exception so catch block code will not execute.
{
System.out.println("Inside catch."+e);
}finally//finally block code will be executed.
{
System.out.println("Inside finally. Please take appropriate action");
}
}

}
In above example, 2 try-catch-finally blocks used. Run above example and
observe result.
1st try block will throw an error and catch will handle and then finally
block will be executed. 2nd try block will not throw any error so catch will
be not executed but finally block will be executed. So In both the cases
finally block will be executed.
So all these things about exception and ways of handling them will helps
you In your webdriver test exception handling.
Posted by P
Email ThisBlogThis!Share to TwitterShare to FacebookShare to Pinterest

1. Introduction of Selenium WebDriver


What is selenium webdriver
What is selenium webdriver and how it help us in software testing
process?
Webdriver in selenium (http://docs.seleniumhq.org/projects/webdriver/) is
an Interface and it is designed to overcome some limitations of selenium
RC software testing tool. However selenium WebDriver's development is in
process so still there are few limitations and known issues available in

selenium WebDriver. Selenium WebDriver is also known as Selenium 2 and


used for web as well mobile
applications testing. It is freeware software testing tool and mostly used
as a regression testing tool for web and mobile applications.
Selenium 2 supports most of all browsers to run your test cases and many
programming languages like C#, Java, Python, Ruby, .Net, Perl, PHP, etc..
to create and modify your test scripts. Selenium 2(WebDriver) controls
browser directly from operating system level so it is interacting very fast
and with more realistic way with browsers. Major people in world using
Selenium webdriver with java.
Difference between WebDriver and selenium RC
WebDriver

Selenium WebDriver do not require selenium server for running test.

WebDriver is using native automation from each and every


supported language for running automation scripts on browsers.

WebDriver supports web as well mobile application testing so you


can test mobile applications (iPhone or Android).

Supporting latest versions of almost all browsers.

WebDriver controls the browser itself.

Selenium RC

Required selenium server for running test.

Selenium RC is using JavaScripts to drive automation with browser.

Selenium RC supports only web application testing.

Supporting all browsers but not supporting latest versions.

Selenium RC is using javascript to interact and operate on web page

You can share if you know any limitations or advantages of Selenium


WebDriver by posting comments bellow.
Click here to read more about WebDriver. You can read my next post
about selenium webdriver download install.
selenium web driver, selenium webdriver documentation, selenium

testing, webdriver selenium, selenium testing tool, selenium driver,


selenium tool, automated testing tools, software testing tools, selenium
automation, selenium webdriver vs remote control, selenium online
training, selenium training, selenium test, selenium test tool, webdriver,
automated testing tools, web testing tools, test automation
tools, selenium firefox webdriver
2. Downloading and installation Of Selenium Webdriver with Eclipse
List of Selenium Commands With Examples Part - 1
Selenium
IDE
commands
with
examples
There are many commands available in selenium IDE. I have prepared one
selenium commands list and linked some selenium ide command with its
examples. So you can click on command link(From bellow given selenium
ide commands list table) to view how to and where to use that command
with example. This full selenium command list will help you to learn
selenium
IDE
on
beginning
level.
(Do you wants to be master of selenium IDE in just 7 days? If yes then
Read this Selenium IDE tutorials)
Pending command's(Which are not linked) example creation is in process.
you can subscribe via email for
new post update or you can bookmark this page in your browser to visit it
again.
SUBSCRIBE VIA EMAIL TO GET ALL COMMAND EXAMPLES VIA EMAIL
Complete List of Selenium IDE Commands
(Click here to view part 2)
addLocationStrategy
addLocationStrategyAndWait
addScript
addScriptAndWait
addSelection
addSelectionAndWait
allowNativeXpath
allowNativeXpathAndWait
altKeyDown
altKeyDownAndWait
altKeyUp
altKeyUpAndWait
answerOnNextPrompt
assertAlert
assertAlertNotPresent
assertAlertPresent

assertAllButtons
assertAllFields
assertAllLinks
assertAllWindowIds
assertAllWindowNames
assertAllWindowTitles
assertAttribute
assertAttributeFromAllWindows
assertBodyText
assertChecked
assertConfirmation
assertConfirmationNotPresent
assertConfirmationPresent
assertCookie
assertCookieByName
assertCookieNotPresent
assertCookiePresent
assertCursorPosition
assertEditable
assertElementHeight
assertElementIndex
assertElementNotPresent
assertElementPositionLeft
assertElementPositionTop
assertElementPresent
assertElementWidth
assertEval
assertExpression
assertHtmlSource
assertLocation
assertMouseSpeed
assertNotAlert
assertNotAllButtons
assertNotAllFields
assertNotAllLinks
assertNotAllWindowIds
assertNotAllWindowNames
assertNotAllWindowTitles
assertNotAttribute
assertNotAttributeFromAllWindows
assertNotBodyText
assertNotChecked
assertNotConfirmation
assertNotCookie
assertNotCookieByName
assertNotCursorPosition
assertNotEditable
assertNotElementHeight

assertNotElementIndex
assertNotElementPositionLeft
assertNotElementPositionTop
assertNotElementWidth
assertNotEval
assertNotExpression
assertNotHtmlSource
assertNotLocation
assertNotMouseSpeed
assertNotOrdered
assertNotPrompt
assertNotSelectOptions
assertNotSelectedId
assertNotSelectedIds
assertNotSelectedIndex
assertNotSelectedIndexes
assertNotSelectedLabel
assertNotSelectedLabels
assertNotSelectedValue
assertNotSelectedValues
assertNotSomethingSelected
assertNotSpeed
assertNotTable
assertNotText
assertNotTitle
assertNotValue
assertNotVisible
assertNotWhetherThisFrameMatchFrameExpression
assertNotWhetherThisWindowMatchWindowExpression
assertNotXpathCount
assertOrdered
assertPrompt
assertPromptNotPresent
assertPromptPresent
assertSelectOptions
assertSelectedId
assertSelectedIds
assertSelectedIndex
assertSelectedIndexes
assertSelectedLabel
assertSelectedLabels
assertSelectedValue
assertSelectedValues
assertSomethingSelected
assertSpeed
assertTable
assertText

assertTextNotPresent
assertTextPresent
assertTitle
assertValue
assertVisible
assertWhetherThisFrameMatchFrameExpression
assertWhetherThisWindowMatchWindowExpression
assertXpathCount
assignId
assignIdAndWait
break
captureEntirePageScreenshot
captureEntirePageScreenshotAndWait
check
checkAndWait
chooseCancelOnNextConfirmation
chooseOkOnNextConfirmation
chooseOkOnNextConfirmationAndWait
click
clickAndWait
clickAt
clickAtAndWait
close
contextMenu
contextMenuAndWait
contextMenuAt
contextMenuAtAndWait
controlKeyDown
controlKeyDownAndWait
controlKeyUp
controlKeyUpAndWait
createCookie
createCookieAndWait
deleteAllVisibleCookies
deleteAllVisibleCookiesAndWait
deleteCookie
deleteCookieAndWait
deselectPopUp
deselectPopUpAndWait
doubleClick
doubleClickAndWait
doubleClickAt
doubleClickAtAndWait
dragAndDrop
dragAndDropAndWait
dragAndDropToObject
dragAndDropToObjectAndWait
dragdrop

dragdropAndWait
echo
fireEvent
fireEventAndWait
focus
focusAndWait
goBack
goBackAndWait
highlight
highlightAndWait
ignoreAttributesWithoutValue
ignoreAttributesWithoutValueAndWait
keyDown
keyDownAndWait
keyPress
keyPressAndWait
keyUp
keyUpAndWait
metaKeyDown
metaKeyDownAndWait
metaKeyUp
metaKeyUpAndWait
mouseDown
mouseDownAndWait
mouseDownAt
mouseDownAtAndWait
mouseDownRight
mouseDownRightAndWait
mouseDownRightAt
mouseDownRightAtAndWait
mouseMove
mouseMoveAndWait
mouseMoveAt
mouseMoveAtAndWait
mouseOut
mouseOutAndWait
mouseOver
mouseOverAndWait
mouseUp
mouseUpAndWait
mouseUpAt
mouseUpAtAndWait
mouseUpRight
mouseUpRightAndWait
mouseUpRightAt
mouseUpRightAtAndWait
open

openWindow
openWindowAndWait
pause
refresh
refreshAndWait
removeAllSelections
removeAllSelectionsAndWait
removeScript
removeScriptAndWait
removeSelection
removeSelectionAndWait
rollup
rollupAndWait
runScript
runScriptAndWait
select
selectAndWait
selectFrame
selectPopUp
selectPopUpAndWait
selectWindow
sendKeys
setBrowserLogLevel
setBrowserLogLevelAndWait
setCursorPosition
setCursorPositionAndWait
setMouseSpeed
setMouseSpeedAndWait
setSpeed
setSpeedAndWait
setTimeout
shiftKeyDown
shiftKeyDownAndWait
shiftKeyUp
shiftKeyUpAndWait
store
storeAlert
storeAlertPresent
storeAllButtons
storeAllFields
storeAllLinks
storeAllWindowIds
storeAllWindowNames
storeAllWindowTitles
storeAttribute
storeAttributeFromAllWindows
storeBodyText
storeChecked

storeConfirmation
storeConfirmationPresent
storeCookie
storeCookieByName
storeCookiePresent
storeCursorPosition
storeEditable
storeElementHeight
storeElementIndex
storeElementPositionLeft
storeElementPositionTop
storeElementPresent
storeElementWidth
storeEval
storeExpression
storeHtmlSource
storeLocation
storeMouseSpeed
storeOrdered
storePrompt
storePromptPresent
storeSelectOptions
storeSelectedId
storeSelectedIds
storeSelectedIndex
storeSelectedIndexes
storeSelectedLabel
storeSelectedLabels
storeSelectedValue
storeSelectedValues
storeSomethingSelected
storeSpeed
storeTable
storeText
storeTextPresent
storeTitle
storeValue
storeVisible
storeWhetherThisFrameMatchFrameExpression
storeWhetherThisWindowMatchWindowExpression
storeXpathCount
submit
submitAndWait
type
typeAndWait
typeKeys
typeKeysAndWait
uncheck

How to download and install Selenium Webdriver with Eclipse and Java
Step By Step
Download selenium webdriver and install selenium webdriver is not much
more hard. Actually there is nothing to install except JDK. Let me describe
you step by step process of download, installation and configuration of
web driver and other required components. You can view my post about
"What is selenium webdriver" if you wants to know difference
between WebDriver and selenium RC software tool.
(Note : I am suggesting you to take a tour of Basic selenium commands
tutorials with examples before going ahead for webdriver. It will improve
your basic knowledge and helps you to create webdriver scripts very
easily. )
Steps To Setup and configure Selenium Webdriver With Eclipse and Java
(Note : You can View More Articles On WebDriver to learn it step by step)
Step 1 : Download and install Java in your system
First of all you need to install JDK (Java development kit) in your system.
So your next question will be "how can i download java" Click here to
download Java and install it in your system as per given installation guide
over there.
Step 2 : Download and install Eclipse
Download Eclipse for Java Developers and extract save it in any drive. It is
totally free. You can run 'eclipse.exe' directly so you do not need to install
Eclipse in your system.
Step 3 : Download WebDriver Java client driver.
Selenium webdriver supports many languages and each language has its
own client driver. Here we are configuring selenium 2 with java so we
need 'webdriver Java client driver'. Click here to go on
WebDriver Java client driver download page for webdriver download file.
On that page click on 'Download' link of java client driver as shown in
bellow image.

(language-specific client driver's version is changing time to time so it

may be different version when you will visit download page. )


Downloaded 'webDriver Java client driver' will be in zip format. Extract and
save it in your system at path D:\selenium-2.33.0. There will be 'libs'
folder, 2 jar files and change log in unzipped folder as shown in bellow
figure. We will use all these files for configuring webdriver in eclipse.

Step 4 : Start Eclipse and configure it with selenium 2 (webdriver)

Select WorkSpace on eclipse start up

Double click on 'eclipse.exe' to start eclipse. First time when you start
eclipse, it will ask you to select your workspace where your work will be
stored as shown in bellow image. Create new folder in D: drive with name
'Webdriverwork' and select it as your workspace. You can change it later
on from 'Switch Workspace' under 'file' menu of eclipse.

After selecting workspace folder, Eclipse will be open.

Create new project

Create new java project from File > New > Project > Java Project and give
your project name 'testproject' as shown in bellow given figures. Click on
finish button.

Now your new created project 'testproject' will display in eclipse project
explorer as bellow.

Create new package

Right click on project name 'testproject' and select New > Package. Give
your package name = 'mytestpack' and click on finish button. It will add
new package with name 'mytestpack' under project name 'testproject'.

Create New Class

Right click on package 'mytestpack' and select New > Class and set class
name = 'mytestclass' and click on Finish button. It will add new class
'mytestclass' under package 'mytestpack'.

Now your Eclipse window will looks like bellow.

Add external jar file to java build path

Now you need to add selenium webdriver's jar files in to java build path.

Right click on project 'testproject' > Select Properties > Select Java
build path > Navigate to Libraries tab

Click on add external JARs button > select both .jar files
from D:\selenium-2.33.0.

Click on add external JARs button > select all .jar files
from D:\selenium-2.33.0\libs

Now your testproject's properties dialogue will looks like bellow.

That's all about configuration of WebDriver with eclipse. Now you are
ready to write your test in eclipse and run it in WebDriver.
You can Read My Post about how to write and run your first test
in WebDriver.
download selenium webdriver, install webdriver, download webdriver
selenium, selenium testing, selenium testing tool, how to download
selenium webdriver, what is selenium webdriver, webdriver download,
selenium webdriver download, selenium automation, selenium download,
selenium install, install selenium webdriver, install selenium webdriver in
eclipse, eclipse and selenium, java and selenium, how to install a server,
selenium driver, how to setup selenium webdriver, download webdriver
selenium, selenium webdriver tutorial java

3. Creating And Running First Webdriver Script

Create And Run First Webdriver Script With Eclipse

Run First Webdriver Script


You need to install webdriver with eclipse to run your script in webdriver.
After installation of webdriver, You need to write a java code in eclipse for
your test case of software web application. Let me give you one simple
example of creating simple webdriver script. First of all you need to write
code as bellow in your
'mytestclass.java' file. You can request(if you wish) this sample code file
by submitting comment bellow with your email id.

Now you are ready to run your script from Run menu as shown bellow.

Script Explanation
Above script will

open Firefox browser.

Then
driver.get
syntax
will
blog.blogspot.in/' in firefox browser.

Then driver.getCurrentUrl() will get the current page URL and it will
be stored in variable 'i'. You can do same thing using "storeLocation"
command in selenium IDE

And at last, it will print value of variable in console as shown bellow.

open

'http://only-testing-

So this is the simple webdriver script example. You can create it for your
own software web application too by replacing URL in above script. We will
learn more scripts in detail in my upcoming posts.
--3.1 Running WebDriver In Google Chrome
Running Selenium Webdriver Test In Google Chrome
You can read my THIS POST to know how to run selenium webdriver test of
software application in Mozilla Firefox browser. As you know, webdriver
support Google Chrome browser too. You need to do something extra for
launching webdriver test in in Google chrome browser. Let me describe
you steps to launch
webdriver test in Google Chrome.
Download ChromeDriver server
First of all, download latest version of ChromeDriver server for webdriver.
You
can
download
it
directly
from
http://code.google.com/p/chromedriver/downloads/list.
Current
latest
version for win32 is chromedriver_win32_2.3 as shown bellow.

Click on that link. It will take you to download page.

Click on link shown above to download chrome driver zip file. On


completion of download, extract zip file to D:/ drive.
Now in eclipse, create new project with name = 'chromeproject' and
create new class with name = 'chromebrowser'. Don't forget to select
'public static void main(String[] args)' method during new java class
creation. Write code as shown bellow in class file. You can request this
copy of this code by submitting comment bellow this post.

Look in to above image. I set path for Google chrome driver as


System.setProperty("webdriver.chrome.driver", "D:\\chromedriver_win32_
2.3\\chromedriver.exe");
So now, your test will run in Google chrome browser.

Day 3 - Configure JUnit With WebDriver


4. Downloading and installation Of JUnit with Eclipse
How to download and install junit with eclipse step by step

We have already learn how to configure eclipse for webdriver, Creating


new project, new package and then adding new class in my one of the
previous post. In that post you can see how to add external jars of
webdriver in eclipse. Also you can view how to run your first webdriver
test in eclipse for better
understanding.
Generally you do not need to install junit with eclipse if you have already
added external jar files of webdriver with eclipse. Because required jar file
for junit will be already there with webdriver jar files.
How to verify that required jar file for junit is in my build path or not
For junit jar file verification, Right click on your project -> Build Path ->
Configure build path
It will open java build path window as shown in bellow image. In that
window, go to Libraries tab. Here you will see all your jar files. In jar file
tree view, look for the jar file name which is starting with junit.
Java build path window

If this kind of junit jar file is already there then you do not need to install
junit jar with eclipse and you are ready to use junit with eclipse. But if junit
jar file is not there then you need to add it.
Downloading junit jar file
Go to http://junit.org/ website -> Click on download and install guide link
will redirect the page at junit jar file download and install page. Here you
will find the link like "junit.jar". Click on it will redirect to junit jar file
downloading page. From this page download the latest version of junit jar
file.
Installing junit jar file with eclipse
Go to java build path window as shown in above figure. Now click on Add
External JARs button to add your downloaded junit jar file with eclipse.

After adding junit jar file, click on OK button to close java build path
window.
Now you are ready to use junit with eclipse for your webdriver test of
software application. Click here to view all articles on webdriver.
--5.1 Creating and running webdriver test with junit
Creating and running webdriver test with junit and eclipse step by step
We have already discussed about how to download and install junit in
eclipse to run webdriver test in my previous post. Please note that you
need to add junit jar file only if it is not available in webdriver jar file
folder. If it is already there with webdriver jar file folder then you not need
to do anything to create and run
junit test. Now let me describe you how to create webdriver test case
using junit.
Webdriver test case creation using junit and eclipse
You are already aware about how to create new project and package in
eclipse and if you are not aware then please visit this post page. To
create JUnit Test Case, you need to add JUnit Test Case at place of Class
inside your package. Look at bellow given image to know how to add JUnit
Test Case.

As shown in above image, Select JUnit Test Case from Select a wizard
dialog anf then click on Next button. On Next page, Enter your test case
name and click on Finish button.

When you add JUnit Test Case, your eclipse project explorer window will
looks like bellow given image.

Now replace bellow given code with your original code.


package Testjunit;
import org.junit.Test;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class Mytest {
WebDriver driver = new FirefoxDriver();
@Test
public void test() {

driver.manage().window().maximize();
System.out.print("Window maximise");
driver.get("http://only-testing-blog.blogspot.in/");
System.out.print("Site Open");
driver.quit();
System.out.print("End of Test");
}
}
Running webdriver test case using junit in eclipse
After replacing above code with your original code, click on Run button in
eclipse. It will show you Run As dialog as shown bellow.

Select JUnit Test from Run As dialog and click on Ok button. Eclipse will run
your test case using JUnit and on completion of execution, you can see
your result in JUnit pane as bellow.

VIEW THIS POST to know how to create and run junit test suite in eclipse.
--5.2 Creating and running junit test suite with webdriver

How To Create And Run JUnit Test Suit For WebDriver Test - Step By Step
If you are planning to perform regression testing of any application using
webdriver then obviously there will be multiple test cases or test classes
under your webdriver project. Example - There are 2 junit test cases under
your project's package. Now if you wants to run both of them then how
will
you
do
it?
Simple
and
easy solution is creating JUnit test suite. If your project has more than 2
test cases then you can create test suite for all those test cases to run all
test cases from one place.
Before creating junit test suite, you must have to read my post about
"How to download and install junit in eclipse" and "How to create and run
junit test in eclipse". Now let me describe you how to create junit test
suite in eclipse for your junit test case.
Step 1 - Create new project and package
Create new project in eclipse with name = junitproject and then add new
package = junitpack under your project. VIEW THIS POST to know how to
create new project and add package in eclipse. Add required external jar
files for selenium webdriver.
Step 2 - Create 1st Test Case
Now create JUnit test case under junitpack package with class name =
junittest1 as bellow. VIEW THIS post to know how to create junit test case
in eclipse.
package junitpack;
import
import
import
import

org.junit.Test;
org.openqa.selenium.By;
org.openqa.selenium.WebDriver;
org.openqa.selenium.firefox.FirefoxDriver;

public class junittest1 {


WebDriver driver = new FirefoxDriver();
@Test
public void test() throws InterruptedException {
driver.manage().window().maximize();
driver.get("http://only-testing-blog.blogspot.in/2013/11/new-test.html");
driver.findElement(By.xpath("//input[@name='fname']")).sendKeys("junitte
st1 executed");
Thread.sleep(2000);
System.out.print("junittest1 class is executed");
driver.quit();
}
}

Step 3 - Create 2nd test case


Same way, Create 2nd test class with name = junittest2 under package =
junitpack as bellow.
package junitpack;
import
import
import
import
import
import
import

org.junit.After;
org.junit.Before;
org.junit.Test;
org.junit.Ignore;
org.openqa.selenium.By;
org.openqa.selenium.WebDriver;
org.openqa.selenium.firefox.FirefoxDriver;

public class junittest2 {


WebDriver driver = new FirefoxDriver();
@Before
public void setup () {
driver.manage().window().maximize();
driver.get("http://only-testing-blog.blogspot.in/2013/11/new-test.html");
}
@After
public void aftertest() {
driver.quit();
}
@Test
public void test1() throws InterruptedException{
driver.findElement(By.xpath("//input[@name='fname']")).sendKeys("junitte
st2 class-test1");
System.out.print("\njunittest2 class-test1 method is executed");
Thread.sleep(2000);
}
@Test
public void test2() throws InterruptedException {
driver.findElement(By.xpath("//input[@name='fname']")).sendKeys("junitte
st2 class-test2");
Thread.sleep(2000);
System.out.print("\njunittest2 class-test2 method is executed");
}
}
Step 4 - Create test suite for both test cases

Now we have 2 test cases(junittest1.java and junittest2.java) under


package = junitpack.
To create test suite, Right click on junitpack package folder and Go to ->
New -> Other -> Java -> Junit -> Select 'JUnit Test Suite' as shown in
bellow image.

Now click on Next button.On next screen, add junit test suite name
= junittestsuite and select both test cases as shown bellow image and
then click on Finish button.

It will add new test suite class = junittestsuite.java under your package as
bellow.
package junitpack;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;

import org.junit.runners.Suite.SuiteClasses;
@RunWith(Suite.class)
@SuiteClasses({ junittest1.class, junittest2.class })
public class junittestsuite {
}
If you see in above suite class, there are 2 junit annotations added with
name = @RunWith and @SuiteClasses. @RunWith annotation will
references junit to run test in class and @SuiteClasses describes classes
included in that test suite.
Now your junit test suite is created and project structure will looks like
bellow.

Step 4 - Running test suite


Select junit test suite class = junittestsuite and run it in eclipse. When you
run junit test suite, eclipse will run both test cases (junittest1 and
junittest2) one by one. When execution completed, you will see bellow
given output lines in console.
junittest1
class
is
junittest2
class-test1
method
junittest2 class-test2 method is executed
junit test execution report will looks like bellow.

is

executed
executed

This way we can create junit test suite to run multiple test cases from one
place. You can view all Junit tutorial posts for webdriver on THIS LINK.
VIEW MY NEXT POST to know how to ignore test from execution.
--6.1 Using JUnit Annotations in webdriver
How to Use JUnit Annotations in webdriver test case with example
Unit testing framework JUnit has many annotations to control the flow and
activity of code execution. You must need to insert JUnit annotation inside
the java code to execute your test case as junit test case. You can look in
my previous post where i have used JUnit @Test annotation before test
method.
Let
me
describe
you mostly used 3 JUnit Annotations with example. You can view more
details on JUnit at http://junit.org/.
1. @Before
2. @Test
3. @After
2 other frequently used annotations are @BeforeClass and @AfterClass.
Depending on annotation names, JUnit framework will decide the code
execution flow. i.e. First JUnit framework will execute @Before method,
Second it will execute @Test method and at last it will execute @After
method.
1. @Before Annotation
As name suggest. method written under @Before annotation will be
executed before the method written under @Test annotation. Based on
@Before annotation, JUnit framework will execute that before method first.
Generally method under @Before annotation is used to initializing website
and other environment related setup. @Before annotation method will be
executed before each @Test annotation method means if there are two
@Test methods in your class then @Before method will be executed two
times.
2. @After

Method under @After annotation is known as after method and execution


of @After method will start as soon as completion of @Test method
execution completion. Same as @Before , @After annotation method will
be executed two times if there are two @Test methods in your class.
3. @Test
Method under @Test annotation is known as test method. Execution of
@Test method will start as soon as @Before method execution completed.
Generally we are writing all testing related activity under @Test. We can
use multiple @Test methods in single class too.
4. @BeforeClass
Methods under @BeforeClass annotation will be executed before the any
test method starts execution. It will be executed only once even if there
are
multiple @Test
methods
in
your
class.
5. @AfterClass
@AfterClass method will be run on completion of all the test method's
execution from that class. Same as @BeforeClass, @AfterClass method
will be executed once only.
VIEW EXAMPLE OF DIFFERENCE BETWEEN @Before vs @BeforeClass
AND @After VS @AfterClass ANNOTATIONS
Execute bellow given example in your eclipse as a debugging mode to
verify its execution.
package Testjunit;
import java.util.concurrent.TimeUnit;
import
import
import
import
import

org.junit.After;
org.junit.Before;
org.junit.Test;
org.openqa.selenium.*;
org.openqa.selenium.firefox.FirefoxDriver;

public class Mytest {


WebDriver driver = new FirefoxDriver();
@Before
public void beforetest() {
driver.manage().window().maximize();
driver.get("http://only-testing-blog.blogspot.in/2013/11/new-test.html");
}
@After
public void aftertest() {
driver.quit();

}
@Test
public void test() {
driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
driver.findElement(By.xpath("//input[@value='Bike']")).click();
boolean str1 =
driver.findElement(By.xpath("//input[@value='Bike']")).isSelected();
if(str1 = true) {
System.out.print("Checkbox is checked");
}
else
{
System.out.print("Checkbox is not checked");
}
}
}
Here @After method is written before @Test method but JUnit Framework
will tells eclipse to execute @Test method first and then @After method
--6.2 @Before/@After VS @BeforeClass/@AfterClass Difference
Example Of Difference Between @Before/@After VS
@BeforeClass/@AfterClass In JUnit With WebDriver
Many readers are asking me the difference between JUnit
annotations @Before VS @BeforeClass and @After VS @AfterClass in
webdriver test. If you have read my JUNIT ANNOTATIONS POST, I have
clearly described difference between @Before and @BeforeClass
annotations and @After and
@AfterClass annotations in bold text. Now let me describe once more and
then we will look at practical example for both of them.
Difference between @Before and @BeforeClass annotations

Test method marked with @Before annotation will be executed


before the each @Test method. Means if there are 5 @Test methods
in your class then @Before test method will be executed 5 times.

Test method marked with @BeforeClass annotation will be executed


just before the class. Means @BeforeClass method will be executed
only once before the class even if there are 5 @Test methods in your
class.

Difference between @After and @AfterClass annotations

Same
as @Before
annotation, Test
method
marked
with
@After annotation will be executed after the each @Test method.

@AfterClass annotation will be executed only once after last @Test


method executed.

Execute bellow given @Before and @After annotations example in your


eclipse and observe result in console.
package junitpack;
import
import
import
import
import
import
import
import

org.junit.After;
org.junit.AfterClass;
org.junit.Before;
org.junit.BeforeClass;
org.junit.Test;
org.openqa.selenium.By;
org.openqa.selenium.WebDriver;
org.openqa.selenium.firefox.FirefoxDriver;

public class junittest2 {


private static WebDriver driver;
@Before
public void openbrowser() {
System.out.print("\nBrowser open");
driver = new FirefoxDriver();
driver.manage().window().maximize();
driver.get("http://only-testing-blog.blogspot.in/2013/11/new-test.html");
}
@After
public void closebrowser() {
System.out.print("\nBrowser close");
driver.quit();
}
@Test
public void test1() throws InterruptedException{
driver.findElement(By.xpath("//input[@name='fname']")).sendKeys("junitte
st2 class-test1");
System.out.print("\njunittest2 class-test1 method is executed");
Thread.sleep(2000);
}

@Test
public void test2() throws InterruptedException {
driver.findElement(By.xpath("//input[@name='fname']")).clear();
driver.findElement(By.xpath("//input[@name='fname']")).sendKeys("junitte
st2 class-test2");
Thread.sleep(2000);
System.out.print("\njunittest2 class-test2 method is executed");
}
}
When you execute above example in eclipse, Bellow given result will be
displayed in console.
Console Output :
Browser open
junittest2 class-test1 method is executed
Browser close
Browser open
junittest2 class-test2 method is executed
Browser close
Based on above given console output, we can say each @Before method
is executed before each @Test method and each @After method is
executed after each @Test method. Now let we replace @Before
annotation with @BeforeClass and @After annotation with @AfterClass in
same example and then observe result. Replace bellow given
@BeforeClass and @AfterClass part with @Before and @After part in
above example as bellow.
@BeforeClass
public static void openbrowser() {
System.out.print("\nBrowser open");
driver = new FirefoxDriver();
driver.manage().window().maximize();
driver.get("http://only-testing-blog.blogspot.in/2013/11/new-test.html");
}
@AfterClass
public static void closebrowser() {
System.out.print("\nBrowser close");
driver.quit();
}
Now run above example and look at console result. Console result will be
as bellow.
Console Output :
Browser open
junittest2 class-test1 method is executed

junittest2 class-test2 method is executed


Browser close
As per console result, we can say @BeforeClass method is executed once
only. Same way @AfterClass annotation marked method is also executed
once only.
--6.3 Ignoring JUnit Test from execution
How To Ignore Test In WebDriver With JUnit
As described in my PREVIOUS POST, We can create junit test suite to
execute multiple test cases from one place. See example of my previous
post. junittest2 class have two @Test methods. Now If I wants to
exclude/Ignore 1st @Test method from execution and wants to execute
only 2nd @Test method then how
can I do It? Ignoring specific test in junit test is very easy.
@Ignore annotation
We can use JUnit's has inbuilt @Ignore annotation before @Test method to
Ignore that specific webdriver test from execution. Let we apply @Ignore
annotation practically in our test and then observe its execution result.
VIEW JUNIT EXAMPLE OF TIMEOUT AND EXPECTED EXCEPTION TEST
My scenario is to ignore 1st @Test method from execution so i need to put
@Ignore annotation in my test before 1st @Test method as bellow.
@Ignore
@Test
public void test1() throws InterruptedException{
}
Here, @Ignore annotation will exclude test1() method from execution.
Copy bellow given Ignoring @Test method(test1()) part with @Ignore
annotation and replace it will @Test method part given on Step 3 (Create
2nd test case) of THIS EXAMPLE (Note : @Test method part which needs to
replace is marked with pink color in that example post).
//To ignore this @Test method from execution
@Ignore
@Test
public void test1() throws InterruptedException{
driver.findElement(By.xpath("//input[@name='fname']")).sendKeys("junitte
st2 class-test1");
System.out.print("\njunittest2 class-test1 method is executed");

Thread.sleep(2000);
}
Now when you run full test suite(junittestsuite.java) then on completion of
junit test suite execution, you will get bellow given result in console.
junittest1 class is executed
junittest2 class-test2 method is executed
As per console result, ignored test(test1()) is not executed.
JUnit test execution report will looks like bellow.

This way, Junit's @Ignore annotation will help us to ignore specific test
from execution.
--6.4 Junit Timeout And Expected Exception Test
Example Of Junit Timeout And Expected Exception Test For WebDriver
Sometimes you need to set time out for your webdriver test or you need
to set expected exception condition for your test. Supposing you have
written test for one module and you wants to set timeout for your test.
Here timeout means allowed maximum time to complete full test. Same
way, You are expecting some
exception during your webdriver test execution and that exception is
acceptable.If you are using junit framework for your webdriver test then
you can do it very easily. We have seen example of - how to Ignore
specific webdriver test using junit's @Ignore annotation in THIS POST. Now
let me describe how to write timeout test and exception test in junit with
examples.
Timeout Test In JUnit For WebDriver
We can specify timeout time with junit's @Test annotation as shown
bellow. It will allow maximum 2000 milliseconds to complete the execution
of test1() method. After 2000 miliseconds, it will skip remaining execution
and test1() will be marked with error.
@Test(timeout=2000)
public void test1(){

}
Expected Exception Test In JUnit For WebDriver
We can specify expected exception condition with @Test annotation as
bellow. Here my expected exception is null pointer exception so my
expected condition is NullPointerException.class. You can write your
expected
exception
like IndexOutOfBoundsException.class,
ArithmeticException.class, ect.
@Test(expected = NullPointerException.class)
public void exceptiontest2() {
}
Junit Example Of Timeout And Expected Exception Test
-Go to THIS PAGE
-Copy example given on Step 3 - Create 2nd test case and paste it in your
eclipse.
-Remove all @Test methods from that example and paste bellow given
@Test methods and then run your test class (junittest2.java).
@Test(timeout=2000)
public void test1() throws InterruptedException{
driver.findElement(By.xpath("//input[@name='fname']")).sendKeys("junitte
st2 class-test1");
System.out.print("\njunittest2 class-test1 executed before sleep");
Thread.sleep(5000);
System.out.print("\njunittest2 class-test1 executed after sleep");
}
@Test
public void exceptiontest1() {
throw new NullPointerException();
}
@Test(expected = NullPointerException.class)
public void exceptiontest2() {
throw new NullPointerException();
}
On completion of execution, console will show bellow given out put.
Console Output :
Browser open
junittest2 class-test1 executed before sleep
Browser close
JUnit test result looks like bellow.

test1() method is display with error because test was time out after
2000 milisecond as per our condition.

exceptiontest2() pass successfully


expected exception condition with it.

exceptiontest1() display with error


any expected exception condition.

because
because

we

have

there

placed

was

not

Day 4 - Generate Test Report Using JUnit


7. Selenium WebDriver Test report Generation using JUnit - 3 Steps
Generate webdriver test report in HTML by running build xml file :
Part - 3
We have seen how to configure system and eclipse in configuration
part 1 and configuration part 2 posts to generate webdriver test
report. Now we have a test case and build.xml file in our project
tree. Let me describe you few steps of configuring and
running build.xml file in eclipse. Now follow the bellow given
build.xml file configuration steps to generate HTML report.

Step 1 : Verify build.xml file work space


Open External Tools Configuration dialog as bellow
Right click on Build.xml - > Run As -> External Tools Configuration. It
will open External Tools Configuration dialog as shown bellow.

In Main tab, you need to verify that your current project's build.xml
is selected or not.My current project name is "JUnitReport" so it is
correct for me. If it is of any other project then you need to change it
by clicking on Browse Workspace button.

Step 2 : Set target execution order


Go to the target tab and then set target execution order = build,
ForReport (My Project name), junitreport. If it is not in this order then
you can change it by unchecking and checking and the check box or
by clicking on order button. So now my target execution order will
looks like bellow.

Step 3 : Set Runtime JRE


Go to JRE tab. Here you need to set Runtime JRE = JDK at place of
JRE as shown in bellow image.

If JDK is not display in Separate JRE list then you can add it by
- Click on Installed JREs button. It will open Preferences dialog.
- Click on Add button from Preferences dialog. It will open Add JRE
dialog.
- Select Standard VM from Add JRE dialog and click on next button
as shown in bellow image.

On Next window, Select JDK folder path(Which is located at


C:\Program Files\Java\ in my system) In JRE home field and click on
Finish button. It will add JDK option in Separate JRE drop down.

Now build file configuration is finished and finally you are ready to
run your build.xml file and generate your test report.

Step 4 : Run build.xml


Now you can run build.xml file in 3 ways.
1st way : Run from External Tools Configuration dialog as shown.

2nd way : Run directly from build.xml file

3rd way : Run from Menu icons

Step 5 : View Report


When you run build.xml file, eclipse will run your junit test case and
on completion of execution report file will be generated in your junit
folder which is located in your project folder as bellow.

Open index.html file. It will looks like bellow.

Eclipse And Ant Configuration Steps To Generate webdriver test


execution report using JUnit : Part - 2
Webdriver test result generation is very important and essential part
of automation testing and for that you need to configure your
eclipse accordingly. Before eclipse and ant configuration, you need
to configure your system as described in Part - 1. Now let me
describe you the steps of eclipse configuration to generate web
driver test execution report using JUnit. Perform bellow given steps.

Step 1 : Create new JUnit Test Case


First of all, you need to create JUnit test case in eclipse as described
in JUnit Test Creation Post 1 and Post 2.

Step 2 : Set Ant Home Entries


To set ant home entries,

- Go to eclipse Menu -> Window -> Preferences. It will open eclipse


preference dialog.
- Select Ant -> Runtime from left side preference tree. Now select
Classpath at right side.
- Select 1st class path Ant Home Entries and click on Ant Home
button and select 'apache-ant-1.9.2' folder path and then click on
OK as shown in bellow image.

Step 3 : Set junit.jar path in Blobal Entries of Ant Runtime Preference


if it is not there
As described above, Go to Ant -> Runtime preference settings and
select Global Entries.
Now click on Add External Jars button and select 'junit.jar' located at
eclipse -> plugins -> org.junit_4.11.0.v201303080030 (This folder
name may be different if you have different version of junit) ->
junit.jar. and then click on OK as shown in bellow image.

Step 4 : Generate build.xml for your project

Now you need to generate build.xml for your project. To generate it,
Right click on your project folder and select Export. It will open
Export dialog as shown in bellow image.

Select Ant Buildfiles from export dialog and clicking on Next button
will show you all your projects list. On Next dialog, select your
current project and click on Finish button as shown bellow.

Look in above image. When you will run build.xml file, your test
reports will be saved in JUnit output directory = 'junit' folder. It will
be created automatically in your project folder when you run
build.xml file. We will learn how to run build.xml file in my next post.

When you click on Finish button, build.xml file will be generated


inside your project folder as shown bellow.

View my Next Post to see how to configure and run build.xml file to
generate your test case report in HTML view.

System Configuration Steps To Generate webdriver test execution report


using JUnit : Part -1
Many people facing issues in JUnit report generation configuration using
ant and eclipse. If every thing is not setup properly then it will give you
one or another error and you will be not able to generate JUnit test case
execution report for your web driver test case. Let me describe you few
system
configuration
steps
in
this
post and eclipse configuration steps in my next post to generate JUnit test
case execution report very easily and without any error.
Step 1 : Download and install latest Java SE
Download and install latest Java SE Development Kit (Java development
Kit(JDK) and Java Runtime Environment(JRL)) as per your system
configuration. You can download it from Java SE Development Kit
download
page.
Step
2
:
Download
Latest
Version
of apache-ant
zip
Download
latest
version
of
apache-ant
from http://ant.apache.org/bindownload.cgi.
Current
latest
version
is apache-ant-1.9.2 as shown in bellow image and it may be different in
future.

Extract zip file and save it in your local drive.


Step 3 : Steps to Set Environment variables in system property for java
- Set JAVA_HOME Environment variable
You need to set JAVA_HOME Environment variable in your system property.
To set Environment variable, Right click on My Computer -> Properties and
go to -> Advanced tab. Clicking on Environment variables button will open
Environment variable dialog. Click on New button from System Variables
box and add Variable Name = JAVA_HOME and Variable Value = Path of
your jdk folder. Here my JDK folder path is 'C:\Program
Files\Java\jdk1.7.0_40' as shown in bellow image.

- Set ANT_HOME Environment variable


Same as JAVA_HOME Environment variable, Add new system variable
name = ANT_HOME and Variable Value = Path of your apache-ant-1.9.2
folder as described in bellow image.

- Edit Path Variable


After setting JAVA_HOME and ANT_HOME system variable, Edit existing
Path variable by selecting Path variable from System variables list and
click Edit button and insert %JAVA_HOME%\bin;%ANT_HOME%\bin at the
end of Path variable value string. Do not forget to put semicolon (;) before
%JAVA_HOME%\bin as shown in bellow image.

- Copy tools.jar from jdk/lib and paste It In jre/lib

There will be 2 folders In your C:Program Files\Java folder.

In my system It Is jdk1.7.0_40 and jre7.

Open C:\Program Files\Java\jdk1.7.0_40\lib folder and copy tools.jar


file.

Open C:\Program Files\Java\jre7\lib and paste tools.jar In to It.

Now restart your system to getting system variables changes effect. Now
system configuration is completed for generating webdriver test execution
report using JUnit. Now you need to configure eclipse as described in my
Day 5 - Element Locators In WebDriver

8. Different Ways Of Locating Elements In WebDriver


We have learnt most of all the way of locating element in webdriver
like Locating Element By ID, Locating Element By Name, Locating Element
By Class Name, Locating Element By Tag Name, Locating Element By Link
Text Or Partial Link and Locating Element By CSS Selector
How To Locate Elements By ID In Selenium WebDriver With Example
Before using WebDriver, You must be aware about different ways of
locating an elements in WebDriver. Locating an element is essential part
in selenium WebDriver because when you wants to take some action on
element (typing text or clicking on button), first you need to locate that
specific
element
to
perform
action.
First of all I recommend you to read all these selenium IDE element
locating methods and then read this article about Selenium WebDriver
element locators to get all locating methods in better way.
WebDriver which is also known as a Selenium 2 has many different ways
of locating element. Let me explain each of them with examples. Here I
am explaining how to locate element By id and will describe Locating Web
Element By ClassName in my Next Post and others in latter posts.
Locating UI Element By ID
If your webpage element has unique and static ID then you can locate
your page element by ID. Look in to bellow given image. You can verify
that your webelement has any id or not using the firebug.

In above image, Submit Query button has unique id = 'submitButton'. I


can use that id to locate button as bellow.
driver.findElement(By.id("submitButton"));

Bellow given example will show you how to locate element by id and then
how to click on it. Copy bellow given @Test method part and replace it
with the @Test method part of example given on this page.(Note : @Test
method is marked with pink color in that example).
@Test
public void test() {
driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
for (int i = 0; i<=20; i++)
{
WebElement btn = driver.findElement(By.id("submitButton"));//Locating
element by id
if (btn.isEnabled())
{
//if webelement's attribute found enabled then this code will be
executed.
System.out.print("\nCongr8s... Button is enabled and webdriver is
clicking on it now");
//Locating button by id and then clicking on it.
driver.findElement(By.id("submitButton")).click();
i=20;
}
else
{
//if webelement's attribute found disabled then this code will be
executed.
System.out.print("\nSorry but Button is disabled right now..");
}
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
Selenium Webdriver Element Locator - Locating Element By Name With
Example
Selenium WebDriver/Selenium 2 is web and mobile application regression
testing tool and it is using element locators to find out and perform
actions on web elements. We have learn Element Locating by ID, Element
Locating By Tag Name and Locating element by Class Name with
examples in my previous
posts. Locating Element By Name is very useful method and many
peoples are using this method in their webdriver automation test case
preparation. Locating Element By Name and Locating Element by ID are

nearly same. In Locating Element by ID method, webdriver will look for the
specified ID attribute and in Locating Element By Name method,
webdriver will look for the specified Name attribute.
Let me show you one example of how to locate element by name and
then we will use it in our webdriver test case.

Look in to above image, web element 'First Name' input box do not have
any ID so webdriver can not locate it By ID but that element contains
name attribute. So webdriver can locate it By Name attribute. Syntax of
locating element in webdriver is as bellow.
driver.findElement(By.name("fname"));
Now let we use it in one practical example as bellow.Copy bellow given
@Test method part and replace it with the @Test method part of example
given on this page.
(Note : @Test method is marked with pink color in that example).
@Test
public void test()
{
driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
//Locating element by Name and type given texts in to input box.
driver.findElement(By.name("fname")).sendKeys("My First Name");
}
Above example will type the text in text box using By Name element
locating method.
Locating Web Element By ClassName In Selenium WebDriver with example
There are many different ways of locating elements in webdriver for your
software web application page and I have described one of them in my
PREVIOUS POST with example. In webdriver, we can't do any thing on web
page if you don't know how to locate an element. As you know, we can
use
element's
ID
to
locate
that
specific element but suppose if your element do not have any ID then how

will you locate that element ? Locating web element by className is good
alternative if your element contains class name. We can locate element
By Tag Name, By Name, By Link Text, By Partial Link Text, By CSS and By
XPATH too but will look about them in my next posts.
How to get the class name of element
You can get the class name of element using firebug as shown in bellow
given image.

Look in to above image. Post date content has a class and we can use that
class name to store that blog post date string. Notice one more thing in
above image, blog post date string has not any ID so we can not locate it
by ID.
(Note : You can view more webdriver tutorials on THIS LINK.)
Example Of Locating Web Element By ClassName
We can use bellow given syntax to locate that element.
driver.findElement(By.className("date-header"));
Practical example of locating web element by className is as bellow.
package junitreportpackage;
import java.util.concurrent.TimeUnit;
import
import
import
import
import
import
import

org.junit.After;
org.junit.Before;
org.junit.Test;
org.openqa.selenium.By;
org.openqa.selenium.WebDriver;
org.openqa.selenium.WebElement;
org.openqa.selenium.firefox.FirefoxDriver;

public class Mytest1 {


//To open Firefox browser

WebDriver driver = new FirefoxDriver();


@Before
public void beforetest() {
//To Maximize Browser Window
driver.manage().window().maximize();
//To Open URL In browser
driver.get("http://only-testing-blog.blogspot.in/2013/11/new-test.html");
}
@After
public void aftertest() {
driver.quit();
}
@Test
public void test()
{
driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
String datentime = driver.findElement(By.className("dateheader")).getText();//Locating element by className and store its text to
variable datentime.
System.out.print(datentime);
}
}
In above example,
WebDriver driver = new FirefoxDriver() will open webdriver's Firefox
browser instance. VIEW THIS POST TO KNOW HOW TO RUN WEBDRIVER
TEST IN GOOGLE CHROME.
driver.get(); will open targeted URL in browser.
Element Locators In Selenium 2 or WebDriver - Locating Element By Tag
Name
We have learn about Locating element by ID and Locating element by
Class Name with examples in my previous posts. Let me repeat once more
that if element contains ID then we can locate element by its ID and if
element do not have ID and contains Class Name then we can locate an
element by Class Name.
Now supposing, web element do not have any ID or Class Name then how
to locate that element in selenium WebDriver ? Answer is there are many
alternatives of selenium WebDriver element locators and one of them
is Locating Element By Tag Name.

Locating Element By Tag Name is not too much popular because in most
of cases, we will have other alternatives of element locators. But yes if
there is not any alternative then you can use element's DOM Tag Name to
locate that element in webdriver.

(Note : You can view all tutorials of webdriver element locators)


Look in to above image. That select box drop down do not have any ID or
Class Name. Now if we wants to locate that element then we can use it's
DOM tag name 'select' to locate that element. Element locator sysntex will
be
as
bellow.
driver.findElement(By.tagName("select"));
Bellow given example will locate dropdown element by it's tagName to
store its values in variable. Copy bellow given @Test method part and
replace it with the @Test method part of example given on this page.(Note
: @Test method is marked with pink color in that example).
@Test
public void test()
{
driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
//Locating element by tagName and store its text in to variable
dropdown.
String dropdown = driver.findElement(By.tagName("select")).getText();
System.out.print("Drop down list values are as bellow :\n"+dropdown);
}
How To Locate Element By Link Text Or Partial Link Text In Selenium
WebDriver
In my previous posts what we have learn is we can Locate Element By
Name, Locate Element By ID, Locate Element By Class Name And Locate
Element By Tag Name to take any action on that element. We will look

about different web driver actions and operations in my upcoming posts.


Now let we
learn two more element locators as bellow.
Locate Element By Link Text
If your targeted element is link text then you can use by link text element
locator to locate that element. Look in to bellow given image.

My Targeted element Is Link text 'Click Here' and I wants to click on It then
I can use It as bellow.
driver.findElement(By.linkText("Click Here")).click();
Locate Element By Partial Link Text
Same as Link text, We can locate element by partial link text too. In that
case we need to use By.partialLinkText at place of By.linkText as bellow.
driver.findElement(By.partialLinkText("Click ")).click();
For locating element by link text, we need to use full word 'Click Here' but
in case of locating element by partial link text, we can locate element by
partial work 'Click' too.
Look in to bellow given example. I have used both the element locators to
locate links.
Copy bellow given @Test method part and replace it with the @Test
method part of example given on this page. (Note : @Test method is
marked with pink color in that example).
@Test
public void test()
{

driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
driver.findElement(By.linkText("Click Here")).click();//Locate element by
linkText and then click on it.
WebDriverWait wait = new WebDriverWait(driver, 15);
wait.until(ExpectedConditions.elementToBeClickable(By.partialLinkText("18
:"))); //Locate element by partial linkText.
}
Selenium WebDriver By.cssSelector Element Locators With Example
WebDriver support many different element locating methods and locating
element by it's CSS Path is one of the most popular way in webdriver. If
you not want to use by id, name, tag name, class name or link text as
your locator then you can locate that element by it's CSS path. Read this
tutorial to learn different
ways of writing CSS path of any element. You can get CSS path of any
element using selenium IDE too by setting CSS as your Locator Builders
Preference and then performing some action on that element in Selenium
IDE recording mode. You can get CSS path of any element by Firebug too.
Now let we learn how we can use By.cssSelector in webdriver. Look in to
bellow given image.

Here we can locate input box First name using bellow given webdriver
syntax.
driver.findElement(By.cssSelector("input[name='fname']"));

Bellow given example will locate input box by CSS Selector to type text in
it.
Copy bellow given @Test method part and replace it with the @Test
method part of example given on this page.
(Note : @Test method is marked with pink color in that example).
@Test
public void test()
{
driver.manage().timeouts().implicitlyWait(15,
TimeUnit.SECONDS);
driver.findElement(By.cssSelector("input[name='fname']")).sendKeys("My
Name");;//Locate element by cssSelector and then type the text in it.
}
How To Locate Element By XPATH In Selenium 2/WebDriver With Example
We have learnt most of all the way of locating element in webdriver
like Locating Element By ID, Locating Element By Name, Locating Element
By Class Name, Locating Element By Tag Name, Locating Element By Link
Text Or Partial Link and Locating Element By CSS Selector. One
another method of locating element in selenium webdriver is By XPATH of
element. It is most popular and best way to locate element in WebDriver.
However you can use other ways too to locate element.
You can write Xpath of any element by many different ways as described
in This Post.

Above given image shows the firebug view of First name text box. Now let
me give you few examples of how to write syntax to locate it in webdriver
using xPath in 2 different ways.
1. driver.findElement(By.xpath("//input[@name='fname']"));
2. driver.findElement(By.xpath("//input[contains(@name,'fname')]"));
I have used xPath to locate element in above both the syntax. We can use
anyone from above to locate that specific element. Let we use it in
practical example as bellow.
Copy bellow given @Test method part and replace it with the @Test
method part of example given on this page.
(Note : @Test method is marked with pink color in that example).
@Test
public void test()
{
driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
driver.findElement(By.xpath("//input[@name='fname']")).sendKeys("My
Name");//Locate element by cssSelector and then type the text in it.
}

Selenium css locators tutorial with example


As you know, Locators in selenium are main elements and CSS Locator is
another alternative of Xpath element locator, ID or Name locator or any
other element locators in selenium. Full form of CSS is "Cascading Style
Sheets" and it define that how to display HTML elements on webpage.
Click here to read more about CSS. There are few advantages and also few
disadvantages of using CSS element locators at
place of Xpath element locators in selenium.
CSS Locators Main Advantage
Main advantage of using CSS locator is - It is much more faster and
simpler than the Xpath Locators in IE and also they are more readable
compared to Xpath locators. Also CSS locators are little faster compared
to Xpath locators in other browsers.
Note : Need good working examples on selenium IDE? Visit this link for
great tutorials on selenium IDE.
Now let me come to our main point - How to write CSS locator syntax
manually for selenium. I have derived couple of CSS locator syntax with
example as bellow. I written CSS locator syntax for three elements(Search
text box, Select language drop down and "Go" button) of wikipedia
website home page as shown in bellow image.

CSS locator Examples


1. Selenium CSS locator using Tag and any Attribute
css=input[type=search] \\\\ This syntax will find "input" tag node which
contains "type=search" attribute.
css=input[id=searchInput] \\\\ This syntax will find "input" tag node which
contains "id=searchInput" attribute.
css=form input[id=searchInput] \\\\ This syntax will find form containing
"input" tag node which contains "id=searchInput" attribute.
(All three CSS path examples given above will locate Search text box.)
2. Selenium CSS locator using Tag and ID attribute
css=input#searchInput \\\\ Here, '#' sign is specially used for "id" attribute
only. It will find "input" tag node which contains "id=searchInput"
attribute. This syntax will locate Search text box.
3. Selenium CSS locator using Tag and class attribute
css=input.formBtn \\\\ Here, '.' is specially used for "class" attribute only.
It will find "input" tag node which contains "class=formBtn" attribute. This
syntax will locate Search button (go).
4. Selenium CSS locator using tag, class, and any attribute
css=input.formBtn[name=go] \\\\ It will find "input" tag node which
contains "class=formBtn" class and "name=go" attribute. This syntax will
locate Search button (go).
5. Tag and multiple Attribute CSS locator
css=input[type=search][name=search] \\\\ It will find "input" tag node
which contains "type=search" attribute and "name=search" attribute. This
syntax will locate Search text box.

6. CSS Locator using Sub-string matches(Start, end and containing text) in


selenium
css=input[id^='search'] \\\\ It will find input node which contains 'id'
attribute starting with 'search' text.(Here, ^ describes the starting text).
css=input[id$='chInput'] \\\\ It will find input node which contains 'id'
attribute starting with 'chInput' text. (Here, $ describes the ending text).
css=input[id*='archIn'] \\\\ It will find input node which contains 'id'
attribute containing 'archIn' text. (Here, * describes the containing text).
(All three CSS path examples given above will locate Search text box.)
7. CSS Element locator syntax using child Selectors
css=div.search-container>form>fieldset>input[id=searchInput] \\\\ First
it will find div tag with "class = search-container" and then it will follow
remaining path to locate child node. This syntax will locate Search text
box.
8. CSS Element locator syntax using adjacent selectors
css=input + input \\\\ It will locate "input" node where another "input"
node is present before it on page.(for search tect box).
css=input + select or css=input + input + select \\\\ It will locate "select"
node, where "input" node is present before it on page(for language drop
down).
9. CSS Element locator using contains keyword
css=strong:contains("English") \\\\ It will looks for the element containing
text "English" as a value on the page.

Day 5 - WebDriver Basic Action Commands With Example


Selenium WebDriver Tutorials - Basic Action Commands And Operations
With Examples
I have already posted Selenium WebDrier Tutorials posts how to setup web
driver with eclipse and Run first test with webdriver, how to configure junit
with eclipse to generate webdriver test report. We have also learn
different methods of locating elements in webdriver. All these things are
very
basic
things and you need to learn all of them before starting your test case
creation in selenium 2. Now we are ready to learn next step of performing
basic actions in web driver with java for your software web application.

VIEW STEP BY STEP TUTORIALS ON SELENIUM WEBDRIVER


Today I wants to describe you few basic webdriver commands to perform
actions on web element of your web page. We can perform too many
command operations in webdriver and will look about them one by one in
near future. Right now I am describing you few of them for your kind
information.
1. Creating New Instance Of Firefox Driver
WebDriver driver = new FirefoxDriver();
Above given syntax will create new instance of Firefox driver. VIEW
PRACTICAL EXAMPLE
2. Command To Open URL In Browser
driver.get("http://only-testing-blog.blogspot.in/2013/11/new-test.html");
This syntax will open specified URL in web browser. VIEW PRACTICAL
EXAMPLE OF OPEN URL
3. Clicking on any element or button of webpage

driver.findElement(By.id("submitButton")).click();
Above given syntax will click on targeted element in webdriver. VIEW
PRACTICAL EXAMPLE OF CLICK ON ELEMENT
4. Store text of targeted element in variable
String dropdown = driver.findElement(By.tagName("select")).getText();
This syntax will retrieve text from targeted element and will store it in
variable = dropdown. VIEW PRACTICAL EXAMPLE OF Get Text
5. Typing text in text box or text area.
driver.findElement(By.name("fname")).sendKeys("My First Name");
Above syntax will type specified text in targeted element. VIEW
PRACTICAL EXAMPLE OF SendKeys
6. Applying Implicit wait in webdriver
driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
This syntax will force webdriver to wait for 15 second if element not found
on page. VIEW PRACTICAL EXAMPLE OF IMPLICIT WAIT
7. Applying Explicit wait in webdriver with WebDriver canned conditions.
WebDriverWait wait = new WebDriverWait(driver, 15);
wait.until(ExpectedConditions.textToBePresentInElementLocated(By.xpath(
"//div[@id='timeLeft']"), "Time left: 7 seconds"));
Above 2 syntax will wait for till 15 seconds for expected text "Time left: 7
seconds" to be appear on targeted element. VIWE DIFFERENT PRACTICAL
EXAMPLES OF EXPLICIT WAIT
8. Get page title in selenium webdriver
driver.getTitle();
It will retrieve page title and you can store it in variable to use in next
steps. VIEW PRACTICAL EXAMPLE OF GET TITLE
9. Get Current Page URL In Selenium WebDriver
driver.getCurrentUrl();
It will retrieve current page URL and you can use it to compare with your
expected URL. VIEW PRACTICAL EXAMPLE OF GET CURRENT URL
10. Get domain name using java script executor
JavascriptExecutor javascript = (JavascriptExecutor) driver;
String CurrentURLUsingJS=(String)javascript.executeScript("return
document.domain");
Above syntax will retrieve your software application's domain name using
webdriver's java script executor interface and store it in to variable.

VIEW GET DOMAIN NAME PRACTICAL EXAMPLE.


11. Generate alert using webdriver's java script executor interface
JavascriptExecutor javascript = (JavascriptExecutor) driver;
javascript.executeScript("alert('Test Case Execution Is started Now..');");
It will generate alert during your selenium webdriver test case execution.
VIEW PRACTICAL EXAMPLE OF GENERATE ALERT USING SELENIUM
WEBDRIVER.
12. Selecting or Deselecting value from drop down in selenium webdriver.

Select By Visible Text

Select mydrpdwn = new Select(driver.findElement(By.id("Carlist")));


mydrpdwn.selectByVisibleText("Audi");
It will select value from drop down list using visible text value = "Audi".

Select By Value

Select listbox = new


Select(driver.findElement(By.xpath("//select[@name='FromLB']")));
listbox.selectByValue("Italy");
It will select value by value = "Italy".

Select By Index

Select listbox = new


Select(driver.findElement(By.xpath("//select[@name='FromLB']")));
listbox.selectByIndex(0);
It will select value by index= 0(First option).
VIEW PRACTICAL EXAMPLES OF SELECTING VALUE FROM DROP DOWN
LIST.

Deselect by Visible Text

Select listbox = new


Select(driver.findElement(By.xpath("//select[@name='FromLB']")));
listbox.deselectByVisibleText("Russia");
It will deselect option by visible text = Russia from list box.

Deselect by Value

Select listbox = new


Select(driver.findElement(By.xpath("//select[@name='FromLB']")));
listbox.deselectByValue("Mexico");
It will deselect option by value = Mexico from list box.

Deselect by Index

Select listbox = new


Select(driver.findElement(By.xpath("//select[@name='FromLB']")));
listbox.deselectByIndex(5);
It will deselect option by Index = 5 from list box.

Deselect All

Select listbox = new


Select(driver.findElement(By.xpath("//select[@name='FromLB']")));
listbox.deselectAll();
It will remove all selections from list box.
VIEW PRACTICAL EXAMPLES OF DESELECT SPECIFIC OPTION FROM LIST
BOX

isMultiple()

Select listbox = new


Select(driver.findElement(By.xpath("//select[@name='FromLB']")));
boolean value = listbox.isMultiple();
It will return true if select box is multiselect else it will return false.VIEW
PRACTICAL EXAMPLE OF isMultiple()
13. Navigate to URL or Back or Forward in Selenium Webdriver
driver.navigate().to("http://only-testingblog.blogspot.in/2014/01/textbox.html");
driver.navigate().back();
driver.navigate().forward();
1st command will navigate to specific URL, 2nd will navigate one step
back and 3rd command will navigate one step forward. VIEW PRACTICAL
EXAMPLES OF NAVIGATION COMMANDS.
14. Verify Element Present in Selenium WebDriver
Boolean iselementpresent =
driver.findElements(By.xpath("//input[@id='text2']")).size()!= 0;
It will return true if element is present on page, else it will return false in
variable iselementpresent. VIEW PRACTICAL EXAMPLE OF VERIFY ELEMENT
PRESENT.
15. Capturing entire page screenshot in Selenium WebDriver
File screenshot =
((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(screenshot, new File("D:\\screenshot.jpg"));

It will capture page screenshot and store it in your D: drive. VIEW


PRACTICAL EXAMPLE ON THIS PAGE.
16. Generating Mouse Hover Event In WebDriver
Actions actions = new Actions(driver);
WebElement moveonmenu =
driver.findElement(By.xpath("//div[@id='menu1']/div"));
actions.moveToElement(moveonmenu);
actions.perform();
Above example will move mouse on targeted element. VIEW PRACTICAL
EXAMPLE OF MOUSE HOVER.
17. Handling Multiple Windows In Selenium WebDriver.
1. Get All Window Handles.
Set<String> AllWindowHandles = driver.getWindowHandles();
2. Extract parent and child window handle from all window handles.
String window1 = (String) AllWindowHandles.toArray()[0];
String window2 = (String) AllWindowHandles.toArray()[1];
3. Use window handle to switch from one window to other window.
driver.switchTo().window(window2);
Above given steps with helps you to get window handle and then how to
switch from one window to another window. VIEW PRACTICAL EXAMPLE OF
HANDLING MULTIPLE WINDOWS IN WEBDRIVER
18. Check Whether Element is Enabled Or Disabled In Selenium Web
driver.
boolean fname =
driver.findElement(By.xpath("//input[@name='fname']")).isEnabled();
System.out.print(fname);
Above syntax will verify that element (text box) fname is enabled or not.
You can use it for any input element. VIEW PRACTICAL EXAMPLE OF VERIFY
ELEMENT IS ENABLED OR NOT.
19. Enable/Disable Textbox During Selenium Webdriver Test Case
Execution.
JavascriptExecutor javascript = (JavascriptExecutor) driver;
String todisable = "document.getElementsByName('fname')
[0].setAttribute('disabled', '');";
javascript.executeScript(todisable);
String toenable = "document.getElementsByName('lname')
[0].removeAttribute('disabled');";

javascript.executeScript(toenable);
It will disable fname element using setAttribute() method and enable
lname element using removeAttribute() method. VIEW PRACTICAL
EXAMPLE OF ENABLE/DISABLE TEXTBOX.
20. Selenium WebDriver Assertions With TestNG Framework

assertEquals

Assert.assertEquals(actual, expected);
assertEquals assertion helps you to assert actual and expected equal
values. VIEW PRACTICAL EXAMPLE OF assertEquals ASSERTION

assertNotEquals

Assert.assertNotEquals(actual, expected);
assertNotEquals assertion is useful to assert not equal values. VIEW
PRACTICAL EXAMPLE OF assertNotEquals ASSERTION.

assertTrue

Assert.assertTrue(condition);
assertTrue assertion works for boolean value true assertion. VIEW
PRACTICAL EXAMPLE OF assertTrue ASSERTION.

assertFalse

Assert.assertFalse(condition);
assertFalse assertion works for boolean value false assertion. VIEW
PRACTICAL EXAMPLE OF assertFalse ASSERTION.
21. Submit() method to submit form
driver.findElement(By.xpath("//input[@name='Company']")).submit();
It will submit the form. VIEW PRACTICAL EXAMPLE OF SUBMIT FORM.
22. Handling Alert, Confirmation and Prompts Popups
String myalert = driver.switchTo().alert().getText();
To store alert text. VIEW PRACTICAL EXAMPLE OF STORE ALERT TEXT
driver.switchTo().alert().accept();
To accept alert. VIEW PRACTICAL EXAMPLE OF ALERT ACCEPT
driver.switchTo().alert().dismiss();

To dismiss confirmation. VIEW PRACTICAL EXAMPLE OF CANCEL


CONFIRMATION
driver.switchTo().alert().sendKeys("This Is John");
To type text In text box of prompt popup.
elenium WebDriver : Handling Javascript Alerts, Confirmations And
Prompts
Alerts, Confirmation and Prompts are very commonly used elements of
any webpage and you must know how to handle all these popups In
selenium webdriver. If you know, Selenium IDE has many commands to
handle
alerts,
confirmations
and
prompt
popups
like
assertAlert, assertConfirmation, storeAlert,
verifyAlertPresent, etc.. First of all, Let me show you all three different
popup types to remove confusion from your mind and then we will see
how to handle them In selenium webdriver.
Alert Popup
Generally alert message popup display with alert text and Ok button as
shown In bellow given Image.

Confirmation Popup
Confirmation popup displays with confirmation text, Ok and Cancel button
as shown In bellow given Image.

Prompt Popup
Prompts will have prompt text, Input text box, Ok and Cancel buttons.

Selenium webdriver has Its own Alert Interface to handle all above
different popups. Alert Interface has different methods like accept(),
dismiss(), getText(), sendKeys(java.lang.String keysToSend) and we can
use all these methods to perform different actions on popups.
VIEW WEBDRIVER EXAMPLES STEP BY STEP
Look at the bellow given simple example of handling alerts, confirmations
and prompts In selenium webdriver. Bellow given example will perform
different actions (Like click on Ok button, Click on cancel button, retrieve
alert text, type text In prompt text box etc..)on all three kind of popups
using different methods od Alert Interface.
Run bellow given example In eclipse with testng and observe the result.
package Testng_Pack;
import java.util.concurrent.TimeUnit;
import
import
import
import
import
import
import

org.openqa.selenium.Alert;
org.openqa.selenium.By;
org.openqa.selenium.WebDriver;
org.openqa.selenium.firefox.FirefoxDriver;
org.testng.annotations.AfterTest;
org.testng.annotations.BeforeTest;
org.testng.annotations.Test;

public class unexpected_alert {


WebDriver driver;
@BeforeTest
public void setup() throws Exception {
driver =new FirefoxDriver();
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
driver.get("http://only-testing-blog.blogspot.in/2014/01/textbox.html");
}
@AfterTest

public void tearDown() throws Exception {


driver.quit();
}
@Test
public void Text() throws InterruptedException {
//Alert Pop up Handling.
driver.findElement(By.xpath("//input[@value='Show Me Alert']")).click();
//To locate alert.
Alert A1 = driver.switchTo().alert();
//To read the text from alert popup.
String Alert1 = A1.getText();
System.out.println(Alert1);
Thread.sleep(2000);
//To accept/Click Ok on alert popup.
A1.accept();
//Confirmation Pop up Handling.
driver.findElement(By.xpath("//button[@onclick='myFunction()']")).click();
Alert A2 = driver.switchTo().alert();
String Alert2 = A2.getText();
System.out.println(Alert2);
Thread.sleep(2000);
//To click On cancel button of confirmation box.
A2.dismiss();
//Prompt Pop up Handling.
driver.findElement(By.xpath("//button[contains(.,'Show Me
Prompt')]")).click();
Alert A3 = driver.switchTo().alert();
String Alert3 = A3.getText();
System.out.println(Alert3);
//To type text In text box of prompt pop up.
A3.sendKeys("This Is John");
Thread.sleep(2000);
A3.accept();
}
}
This way you can handle different kind of alerts very easily using Alert
Interface of selenium webdriver. NEXT POST will show you how to handle
unexpected alerts In selenium webdriver.
How To Handle Unexpected Alerts In Selenium WebDriver
Some times when we browsing software web application, Display some
unexpected alerts due to some error or some other reasons. This kind of
alerts not display every time but they are displaying only some time. If

you have created webdriver test case for such page and not handled this
kind of alerts In your code then
your script will fail Immediately If such unexpected alert pop up displayed.
We have already learnt, How to handle expected alert popups In selenium
webdriver In THIS EXAMPLE. Now unexpected alert appears only some
times so we can not write direct code to accept or dismiss that alert. In
this kind of situation, we have to handle them specially.
You can VIEW ALL WEBDRIVER TUTORIALS ONE BY ONE.
To handle this kind of unexpected alerts, You must at least aware about on
which action such unexpected alert Is generated. Sometimes, They are
generated during page load and sometime they are generated when you
perform some action. So first of all we have to note down the action where
such unexpected alert Is generated and then we can check for alert after
performing that action. We need to use try catch block for checking such
unexpected alters because If we will use direct code(without try catch) to
accept or dismiss alert and If alert not appears then our test case will fail.
try catch can handle both situations.
I have one example where alert Is displaying when loading page. So we
can check for alert Inside try catch block after page load as shown In
bellow given example. After loading page, It will check for alert. If alert Is
there on the page then It will dismiss It else It will go to catch block and
print message as shown In bellow given example.
Run bellow given example In eclipse with testng and observe the result.
package Testng_Pack;
import java.util.concurrent.TimeUnit;
import
import
import
import
import
import

org.openqa.selenium.By;
org.openqa.selenium.WebDriver;
org.openqa.selenium.firefox.FirefoxDriver;
org.testng.annotations.AfterTest;
org.testng.annotations.BeforeTest;
org.testng.annotations.Test;

public class unexpected_alert {


WebDriver driver;
@BeforeTest
public void setup() throws Exception {
driver =new FirefoxDriver();
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
driver.get("http://only-testing-blog.blogspot.in/2014/06/alert_6.html");

}
@AfterTest
public void tearDown() throws Exception {
driver.quit();
}
@Test
public void Text() throws InterruptedException {
//To handle unexpected alert on page load.
try{
driver.switchTo().alert().dismiss();
}catch(Exception e){
System.out.println("unexpected alert not present");
}
driver.findElement(By.xpath("//input[@name='fname']")).sendKeys("fname
");
driver.findElement(By.xpath("//input[@name='lname']")).sendKeys("lname
");
driver.findElement(By.xpath("//input[@type='submit']")).click();
}
}
Above given webdriver code Is just for example. It Is just explaining the
way of using try catch block to handle unexpected alert. You can use such
try catch block In that area where you are facing unexpected alerts very
frequently.
* Open Firefox Browser
Locating Web Element By ClassName In Selenium WebDriver with example
There are many different ways of locating elements in webdriver for your
software web application page and I have described one of them in my
PREVIOUS POST with example. In webdriver, we can't do any thing on web
page if you don't know how to locate an element. As you know, we can
use
element's
ID
to
locate
that
specific element but suppose if your element do not have any ID then how
will you locate that element ? Locating web element by className is good
alternative if your element contains class name. We can locate element
By Tag Name, By Name, By Link Text, By Partial Link Text, By CSS and By
XPATH too but will look about them in my next posts.
How to get the class name of element
You can get the class name of element using firebug as shown in bellow
given image.

Look in to above image. Post date content has a class and we can use that
class name to store that blog post date string. Notice one more thing in
above image, blog post date string has not any ID so we can not locate it
by ID.
(Note : You can view more webdriver tutorials on THIS LINK.)
Example Of Locating Web Element By ClassName
We can use bellow given syntax to locate that element.
driver.findElement(By.className("date-header"));
Practical example of locating web element by className is as bellow.
package junitreportpackage;
import java.util.concurrent.TimeUnit;
import
import
import
import
import
import
import

org.junit.After;
org.junit.Before;
org.junit.Test;
org.openqa.selenium.By;
org.openqa.selenium.WebDriver;
org.openqa.selenium.WebElement;
org.openqa.selenium.firefox.FirefoxDriver;

public class Mytest1 {


//To open Firefox browser
WebDriver driver = new FirefoxDriver();
@Before
public void beforetest() {
//To Maximize Browser Window
driver.manage().window().maximize();
//To Open URL In browser

driver.get("http://only-testing-blog.blogspot.in/2013/11/new-test.html");
}
@After
public void aftertest() {
driver.quit();
}
@Test
public void test()
{
driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
String datentime = driver.findElement(By.className("dateheader")).getText();//Locating element by className and store its text to
variable datentime.
System.out.print(datentime);
}
}
In above example,
WebDriver driver = new FirefoxDriver() will open webdriver's Firefox
browser instance. VIEW THIS POST TO KNOW HOW TO RUN WEBDRIVER
TEST IN GOOGLE CHROME.
driver.get(); will open targeted URL in browser.
How To Locate Elements By ID In Selenium WebDriver With Example
Before using WebDriver, You must be aware about different ways of
locating an elements in WebDriver. Locating an element is essential part
in selenium WebDriver because when you wants to take some action on
element (typing text or clicking on button), first you need to locate that
specific
element
to
perform
action.
First of all I recommend you to read all these selenium IDE element
locating methods and then read this article about Selenium WebDriver
element locators to get all locating methods in better way.
WebDriver which is also known as a Selenium 2 has many different ways
of locating element. Let me explain each of them with examples. Here I
am explaining how to locate element By id and will describe Locating Web
Element By ClassName in my Next Post and others in latter posts.
Locating UI Element By ID
If your webpage element has unique and static ID then you can locate
your page element by ID. Look in to bellow given image. You can verify
that your webelement has any id or not using the firebug.

In above image, Submit Query button has unique id = 'submitButton'. I


can use that id to locate button as bellow.
driver.findElement(By.id("submitButton"));
Bellow given example will show you how to locate element by id and then
how to click on it. Copy bellow given @Test method part and replace it
with the @Test method part of example given on this page.(Note : @Test
method is marked with pink color in that example).
@Test
public void test() {
driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
for (int i = 0; i<=20; i++)
{
WebElement btn = driver.findElement(By.id("submitButton"));//Locating
element by id
if (btn.isEnabled())
{
//if webelement's attribute found enabled then this code will be
executed.
System.out.print("\nCongr8s... Button is enabled and webdriver is
clicking on it now");
//Locating button by id and then clicking on it.
driver.findElement(By.id("submitButton")).click();
i=20;
}
else
{
//if webelement's attribute found disabled then this code will be
executed.
System.out.print("\nSorry but Button is disabled right now..");

}
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
* Submitting Form Using .submit() Method
Submitting Form Using submit() Method Of Selenium WebDriver
You will find many forms In any website like Contact Us form, New User
Registration Form, Inquiry Form, LogIn Form etc.. Supposing you are
testing one site where you have to prepare Login form submission test
case In selenium webdriver then how will you do It? Simplest way Is
described In THIS POST. If you will
see In that example post, we have used .click() method to click on Login
button.
Selenium Webdriver has one special method to submit any form and that
method name Is submit(). submit() method works same as clicking on
submit button.
WEBDRIVER TUTORIAL PART 2
When to use .click() method
You can use .click() method to click on any button. Means element's type
= "button" or type = "submit", .click() method will works for both.
When to use .submit() method
If you will look at firebug view for any form's submit button then always
It's type will be "submit" as shown In bellow given Image. In this case,
.submit() method Is very good alternative of .click() method.

Final Notes :
1. If any form has submit button which has type = "button" then .submit()
method will not work.
2. If button Is not Inside <form> tag then .submit() method will not work.

Now let us take a look at very simple example where I have used .submit()
method to submit form. In bellow given example, I have not used .click()
method but used .submit() method with company name field. Run bellow
give example In eclipse with testng and verify the result.
package Testng_Pack;
import java.util.concurrent.TimeUnit;
import
import
import
import
import
import

org.openqa.selenium.By;
org.openqa.selenium.WebDriver;
org.openqa.selenium.firefox.FirefoxDriver;
org.testng.annotations.AfterTest;
org.testng.annotations.BeforeTest;
org.testng.annotations.Test;

public class Form_Submit {


WebDriver driver = new FirefoxDriver();
@BeforeTest
public void setup() throws Exception {
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
driver.get("http://only-testing-blog.blogspot.in/2014/05/form.html");
}
@AfterTest
public void tearDown() throws Exception {
driver.quit();
}
@Test
public void LogIn_Test(){
driver.findElement(By.xpath("//input[@name='FirstName']")).sendKeys("M
yFName");
driver.findElement(By.xpath("//input[@name='LastName']")).sendKeys("M
yLName");
driver.findElement(By.xpath("//input[@name='EmailID']")).sendKeys("My
Email ID");
driver.findElement(By.xpath("//input[@name='MobNo']")).sendKeys("My
Mob No.");
driver.findElement(By.xpath("//input[@name='Company']")).sendKeys("My
Comp Name");
//To submit form.

//You can use any other Input field's(First Name, Last Name etc.) xpath
too In bellow given syntax.
driver.findElement(By.xpath("//input[@name='Company']")).submit();
String alrt = driver.switchTo().alert().getText();
driver.switchTo().alert().accept();
System.out.println(alrt);
}
}
Above example will simply submit the form and retrieve submission alert
to print. So this way we can use webdriver's submit method to submit any
form. You can try different form for your better understanding.
* Store Text Of Element
Element Locators In Selenium 2 or WebDriver - Locating Element By Tag
Name
We have learn about Locating element by ID and Locating element by
Class Name with examples in my previous posts. Let me repeat once more
that if element contains ID then we can locate element by its ID and if
element do not have ID and contains Class Name then we can locate an
element by Class Name.
Now supposing, web element do not have any ID or Class Name then how
to locate that element in selenium WebDriver ? Answer is there are many
alternatives of selenium WebDriver element locators and one of them
is Locating Element By Tag Name.
Locating Element By Tag Name is not too much popular because in most
of cases, we will have other alternatives of element locators. But yes if
there is not any alternative then you can use element's DOM Tag Name to
locate that element in webdriver.

(Note : You can view all tutorials of webdriver element locators)


Look in to above image. That select box drop down do not have any ID or
Class Name. Now if we wants to locate that element then we can use it's
DOM tag name 'select' to locate that element. Element locator sysntex will

be

as

bellow.

driver.findElement(By.tagName("select"));
Bellow given example will locate dropdown element by it's tagName to
store its values in variable. Copy bellow given @Test method part and
replace it with the @Test method part of example given on this page.(Note
: @Test method is marked with pink color in that example).
@Test
public void test()
{
driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
//Locating element by tagName and store its text in to variable
dropdown.
String dropdown = driver.findElement(By.tagName("select")).getText();
System.out.print("Drop down list values are as bellow :\n"+dropdown);
}
* Typing Text In To Text box
Selenium Webdriver Element Locator - Locating Element By Name With
Example
Selenium WebDriver/Selenium 2 is web and mobile application regression
testing tool and it is using element locators to find out and perform
actions on web elements. We have learn Element Locating by ID, Element
Locating By Tag Name and Locating element by Class Name with
examples in my previous
posts. Locating Element By Name is very useful method and many
peoples are using this method in their webdriver automation test case
preparation. Locating Element By Name and Locating Element by ID are
nearly same. In Locating Element by ID method, webdriver will look for the
specified ID attribute and in Locating Element By Name method,
webdriver will look for the specified Name attribute.
Let me show you one example of how to locate element by name and
then we will use it in our webdriver test case.

Look in to above image, web element 'First Name' input box do not have
any ID so webdriver can not locate it By ID but that element contains
name attribute. So webdriver can locate it By Name attribute. Syntax of
locating element in webdriver is as bellow.
driver.findElement(By.name("fname"));
Now let we use it in one practical example as bellow.Copy bellow given
@Test method part and replace it with the @Test method part of example
given on this page.
(Note : @Test method is marked with pink color in that example).
@Test
public void test()
{
driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
//Locating element by Name and type given texts in to input box.
driver.findElement(By.name("fname")).sendKeys("My First Name");
}
Above example will type the text in text box using By Name element
locating method.
* Get Page Title
Selenium WebDriver wait for title with example
WebDriver has many Canned Expected Conditions by which we can force
webdriver to wait explicitly. However Implicit wait is more practical than
explicit wait in WebDriver. But in some special cases where implicit wait is
not able to handle your scenario then in that case you need to use explicit
waits in your test
cases. You can view different posts on explicit waits where I have
described WebDriver's different Canned Expected conditions with
examples.
If you have a scenario where you need to wait for title then you can
use titleContains(java.lang.String title) with webdriver wait. You need to
provide some part of your expected software web application page title
with this condition as bellow.
WebDriverWait wait = new WebDriverWait(driver, 15);
wait.until(ExpectedConditions.titleContains(": MyTest"));
In above syntax, ": MyTest" is my web page's expected title and 15
seconds is max waiting time to appear title on web page. If title will not
appears within 15 seconds due to the any reason then your test case will
fails with timeout error.
First run bellow given test case in your eclipse and then try same test case
for your own software application.

Copy bellow given @Test method part of wait for title example and replace
it with the @Test method part of example given on this
page. (Note : @Test method is marked with pink color in that linked page).

@Test
public void test ()
{
driver.findElement(By.xpath("//input[@name='fname']")).sendKeys("My
Name");
driver.findElement(By.xpath("//a[contains(text(),'Click Here')]")).click();
//Wait for page title
WebDriverWait wait = new WebDriverWait(driver, 15);
wait.until(ExpectedConditions.titleContains(": MyTest"));
//Get and store page title in to variable
String title = driver.getTitle();
System.out.print(title);
}
In above example, when webdriver will click on Click Here link, another
page will open. During page navigation, webdriver will wait for expected
page title.
* Get Current Page URL
Executing javascript in selenium webdriver to get page title with example
JavascriptExecutor is very useful Interface in webdriver. Interface
JavascriptExecutor helps you to execute javascript in your test case
whenever required. If you knows/remember, We had seen Different
examples of executing javascript in selenium IDE to perform different
actions. Let me you one example of
executing javascript in selenium WebDriver.
Sometimes in your test case, you needs to store your software web
application page title to compare it with expected page title. In selenium
IDE, we can use "storeTitle" command to store it in variable. In
webdriver ,we can do it directly using driver.getTitle(); as shown in this
example. But if you wants to do it using javascript then how will you do it?
Example : Get page title using javascript in selenium webdriver
Copy bellow given @Test method part of get page title using javascript
example and replace it with the @Test method part of example given
on this page. (Note : @Test method is marked with pink color in that linked

page).
@Test
public void test ()
{
JavascriptExecutor javascript = (JavascriptExecutor) driver;
//Get current page title
String pagetitle=(String)javascript.executeScript("return
document.title");
System.out.println("My Page Title Is : "+pagetitle);
//Get current page URL
String CurrentURL = driver.getCurrentUrl();
System.out.println("My Current URL Is : "+CurrentURL);
}
(View more JavascriptExecutor examples in webdriver)
In above example, I have used JavascriptExecutor to execute java script in
selenium webdriver. Inner javascript will return current page title and
store it in variable = pagetitle. Then Next statement will print it in the
console. You can use that variable value to compare with your expected
page title if required.
Last 2 syntax will get current page URLs and Print it in console.
* Get Domain Name
Selenium WebDriver - Get Domain Name Using JavascriptExecutor
You need current page URL when you have to compare it with your
expected URL. You can do it using WebDriver basic operation command
driver.getCurrentUrl();. This method we have seen in my Previous Post. If
you remember, we can use "storeLocation" command to get current page
URL in selenium
IDE. Main purpose of this post is to explore how to get domain name in
webdriver. So if you wants to store application's domain name then you
need to use JavascriptExecutor in your test case.
Look here, software application's domain name is different than the
current page URL.
If
my
current
page
URL
blog.blogspot.in/2013/11/new-test.html Then
My domain name is = only-testing-blog.blogspot.in

= http://only-testing-

Let me provide you simple example of how to get current page URL using
driver.getCurrentUrl();
and
how
to
get
domain
name
using
JavascriptExecutor.

Example : Get current URL of page and domain name in selenium


webdriver
Copy bellow given @Test method part of get current page URL using
javascript example and replace it with the @Test method part of example
given on THIS PAGE. (Note : @Test method is marked with pink color
in that linked page).

@Test
public void test ()
{
String CurrentURL = driver.getCurrentUrl();
System.out.println("My Current URL Is : "+CurrentURL);
//Get and store domain name in variable
JavascriptExecutor javascript = (JavascriptExecutor) driver;
String DomainUsingJS=(String)javascript.executeScript("return
document.domain");
System.out.println("My Current URL Is : "+DomainUsingJS);
}
(View more Javascript examples in selenium webdriver)
In above example, 1st 2 syntax will get and print current page URL. Last 3
syntax will get domain name using javascript and will print it in console.
* Generating Alert Manually
Generating Alert In Selenium Webdriver using JavascriptExecutor
If you need to generate alert during your test case execution then you can
use java script Executor in selenium webdriver. Java Script Executor is
very helpful interface of selenium webdriver because using it we can
execute any java script. I think manual alert generation in webdriver test
is required only in rare case but
main purpose of this post is to explore Java Script Executor. You can view
more examples of JavascriptExecutor on THIS LINK.
If you remember, we can generate alert in selenium IDE too using
"runScript" command. THIS POST will describe you how to generate alert
in selenium IDE using "runScript" command with example.
Now let me describe you how to generate alert in selenium webdriver if
required during test case execution of your software web application.
Copy bellow given @Test method part of generate alert using javascript
example and replace it with the @Test method part of example given
on THIS PAGE. (Note : @Test method is marked with pink color in that
linked page).

Example 3 : JavascriptExecutor to generate alert in selenium webdriver


@Test
public void test () throws InterruptedException
{
//Generating Alert Using Javascript Executor
JavascriptExecutor javascript = (JavascriptExecutor) driver;
javascript.executeScript("alert('Test Case Execution Is started Now..');");
Thread.sleep(2000);
driver.switchTo().alert().accept();
}
In above example, Java Script Executor will simply execute the javascript
and generate alert. You can your own alert text in it. Try it in your own
software application test if required.
* Selecting Value From Dropdown Or Listbox
How To Select Option By Value or By Index In Selenium WebDriver With
Example
In my earlier post, We have seen example of HOW TO SELECT OPTION BY
VISIBLE TEXT from drop down. There are two more alternatives to select
option value from drop down or list box in selenium webdriver. 1. Selecting
Option By Value and 2. Selecting Option By Index. You can use any one
from these
How To Select Option By Value or By Index In Selenium WebDriver With
Example
In my earlier post, We have seen example of HOW TO SELECT OPTION BY
VISIBLE TEXT from drop down. There are two more alternatives to select
option value from drop down or list box in selenium webdriver. 1. Selecting
Option By Value and 2. Selecting Option By Index. You can use any one
from these
three to select value from list box of your software web application page.
If you know, we can use "select" command or "addSelection" command in
selenium IDE to select option from list box.
First of all let me show you difference between visible text, value and
index of list box option. Bellow given image will show you clear difference
between value, visible text and index.

1. Select Option By Value In WebDriver


Syntax for selecting option by value in webdriver is as bellow. First syntax
will locate the select element from page and 2nd syntax will select the
option from select box by value = Italy.
Select listbox = new
Select(driver.findElement(By.xpath("//select[@name='FromLB']")));
listbox.selectByValue("Italy");
2. Select Option By Index In WebDriver
Syntax for selection option by index from list box is as bellow. It will select
1st element(index = 0) from select box.
Select listbox = new
Select(driver.findElement(By.xpath("//select[@name='FromLB']")));
listbox.selectByIndex(0);
Execute bellow given example in your eclipse and verify result. Try to use
it in different applications.
Copy bellow given @Test method part of select option by value or
index and replace it with the @Test method part of example given on THIS
PAGE.(Note : @Test method is marked with pink color in that linked page).
@Test
public void test () throws InterruptedException
{
driver.findElement(By.id("text1")).sendKeys("My First Name");
//Selecting value from drop down by value

Select listbox = new


Select(driver.findElement(By.xpath("//select[@name='FromLB']")));
listbox.selectByValue("Italy");
listbox.selectByValue("Mexico");
listbox.selectByValue("Spain");
driver.findElement(By.xpath("//input[@value='->']")).click();
WebDriverWait wait = new WebDriverWait(driver, 15);
wait.until(ExpectedConditions.elementToBeClickable(By.id("text2")));
//Selecting value from drop down by index
listbox.selectByIndex(0);
listbox.selectByIndex(3);
driver.findElement(By.xpath("//input[@value='->']")).click();
Thread.sleep(2000);
}
Selenium Webdriver tutorial : How To Select Dropdown Value With
Example
In my earlier tutorial of selenium webdriver, we learn few basic action
commands of selenium WebDriver like HOW TO CLICK ON BUTTON,
IMPLICIT WAIT, EXPLICIT WAIT etc. THIS LINK will show you more different
examples of basic action commands of selenium webdriver. As you
know, Drop down is also essential element of any software web
application page. So it is important to know
that how to control or take action on drop down list like selecting specific
value from drop down list using selenium webdriver/selenium 2.
If you know, In selenium IDE we can select value from drop down list using
"select" or "addSelection" command. Now let me give you example of how
to select value from drop down list in webdriver.
In bellow given example, First imported webdriver package
"org.openqa.selenium.support.ui.Select" to get support of webdriver class
"Select".
import org.openqa.selenium.support.ui.Select;
Now we can use "Select" class to identify drop down from web page by
writing bellow given syntax.
Select mydrpdwn = new Select(driver.findElement(By.id("Carlist")));
Now we can select any value from selected drop down as bellow.
mydrpdwn.selectByVisibleText("Audi");
Full Example to select value from drop down is as bellow.

EXAMPLE
package junitreportpackage;
import java.util.concurrent.TimeUnit;
import
import
import
import
import
import
import
import
import
import
import

org.junit.After;
org.junit.Before;
org.junit.Test;
org.openqa.selenium.By;
org.openqa.selenium.JavascriptExecutor;
org.openqa.selenium.WebDriver;
org.openqa.selenium.WebElement;
org.openqa.selenium.firefox.FirefoxDriver;
org.openqa.selenium.support.ui.ExpectedConditions;
org.openqa.selenium.support.ui.Select;
org.openqa.selenium.support.ui.WebDriverWait;

public class Mytesting {


WebDriver driver = new FirefoxDriver();
@Before
public void beforetest() {
driver.manage().window().maximize();
driver.get("http://only-testing-blog.blogspot.in/2014/01/textbox.html");
}
@After
public void aftertest() {
driver.quit();
}
@Test
public void test () throws InterruptedException
{
driver.findElement(By.id("text1")).sendKeys("My First Name");
//Selecting value from drop down using visible text
Select mydrpdwn = new Select(driver.findElement(By.id("Carlist")));
mydrpdwn.selectByVisibleText("Audi");
WebDriverWait wait = new WebDriverWait(driver, 15);
wait.until(ExpectedConditions.elementToBeClickable(By.id("text2")));
}
}

Same thing we can do for list box to select option from list box by visible
text.
How to use implicit wait in selenium webdriver and why
There are 2 types of waits available in Webdriver/Selenium 2. One of them
is implicit wait and another one is explicit wait. Both (Implicit wait and
explicit wait) are useful for waiting in WebDriver. Using waits, we are
telling WebDriver to wait for a certain amount of time before going to next
step. We will see about explicit
wait in my upcoming posts. In this post let me tell you why and how to use
implicit wait in webdriver.
Why Need Implicit Wait In WebDriver
As you knows sometimes, some elements takes some time to appear on
page when browser is loading the page. In this case, sometime your
webdriver test will fail if you have not applied Implicit wait in your test
case. If implicit wait is applied in your test case then webdriver will wait
for specified amount of time if targeted element not appears on page. As
you know, we can Set default timeout or use "setTimeout" command in
selenium IDE which is same as implicit wait in webdriver.
If you write implicit wait statement in you webdriver script then it will be
applied automatically to all elements of your test case. I am suggesting
you to use Implicit wait in your all test script of software web application
with 10 to 15 seconds. In webdriver, Implicit wait statement is as bellow.
How To Write Implicit Wait In WebDriver
driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
Above statement will tell webdriver to wait for 15 seconds if targeted
element not found/not appears on page. Le we look at simple exemple to
understand implicit wait better.
Copy bellow given @Test method part and replace it with the @Test
method part of example given on this page. (Note : @Test method is
marked with pink color in that example).
@Test
public void test ()
{
driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
driver.findElement(By.xpath("//input[@name='fname']")).sendKeys("My
Name");
driver.findElement(By.xpath("//input[@name='namexyz']"));
}

In Above webdriver test case with JUnit example, 1st Element


'xpath("//input[@name='fname']")' will be found on page but element
xpath("//input[@name='namexyz']") is not there on page. So in this case
webdriver will wait for 15 to locate that element on page because we have
written implicit wait statement in our code. At last webdriver test will fail
because xpath("//input[@name='namexyz']") is not on the page.
How to apply wait in webdriver till element becomes invisible or hidden
As you know, WebDriver is software web application regression testing
tool and you will face many problems during your webdriver test case
creation and execution. You must knows alternate solution if one not
works for your test scenario. For example, you have used IMPLICIT WAIT in
your test case but if it is
not sufficient to handle your condition of waiting till element becomes
invisible from page then you can use it's alternative way of using EXPLICIT
WAIT in your test case.
In
my
PREVIOUS
POST,
I
have
describe
use
of visibilityOfElementLocated(By locator) method with explicit wait to wait
till element becomes visible (not hidden) on page. Now let we look at
opposite side. If you wants webdriver to wait till element becomes
invisible
or
hidden
from
page
then
we
can
use invisibilityOfElementLocated(By locator) method with wait condition.
Syntax for wait till element invisible from page is as bellow.
WebDriverWait wait = new WebDriverWait(driver, 15);
wait.until(ExpectedConditions.invisibilityOfElementLocated(By.xpath("//inp
ut[@id='text4']")));
In above syntax, you can change webdriver wait time from 15 to 20, 30 or
more as per your requirement. Also you can use any OTHER ELEMENT
LOCATING METHODS except By.xpath. Practical example of webdriver wait
till element becomes invisible is as bellow.
Copy bellow given @Test method part of wait till element invisible and
replace it with the @Test method part of example given on THIS PAGE.
(Note : @Test method is marked with pink color in that linked page).
@Test
public void test () throws InterruptedException, IOException
{
//Wait for element invisible
WebDriverWait wait = new WebDriverWait(driver, 15);

wait.until(ExpectedConditions.invisibilityOfElementLocated(By.xpath("//inp
ut[@id='text4']")));
System.out.print("Text box text4 is now invisible");
}
You can VIEW EXAMPLE OF "waitForElementNotPresent" IN SELENIUM
IDE if you are using selenium IDE.
Selenium WebDriver : Verify Element Present In Selenium WebDriver
Some times you need to verify the presence of element before taking
some action on software web application page. As you know, Selenium IDE
has many built in commands to perform different types of actions on your
software web application page. You can verify presence of element by
using
"verifyElementPresent" command in selenium IDE. Also you can view
example of selenium IDE "verifyElementNotPresent" command. Web
driver have not any built in method or interface by which we can verify
presence of element on the page.
Yes we can do it very easily in WebDriver too using bellow given syntax.
Boolean
iselementpresent
=
driver.findElements(By.xpath("//input[@id='text2']")).size()!= 0;
We have to use findElements() method for this purpose. Above syntax will
return true if element is present on page. Else it will return false. You can
put if condition to take action based on presence of element.
Bellow given example will check the presence of different text box on
page. It will print message in console based on presence of element.
Copy bellow given @Test method part of iselementpresent example and
replace it with the @Test method part of example given on THIS
PAGE. (Note : @Test method is marked with pink color in that linked page).
@Test
public void test () throws InterruptedException
{
for (int i=1; i<6; i++)
{
//To verify element is present on page or not.
String XPath = "//input[@id='text"+i+"']";
Boolean iselementpresent = driver.findElements(By.xpath(XPath)).size()!
= 0;
if (iselementpresent == true)
{

System.out.print("\nTargeted TextBox"+i+" Is Present On The Page");


}
else
{
System.out.print("\nTargeted Text Box"+i+" Is Not Present On The
Page");
}
}
}
* Deselecting Value From Dropdown Or Listbox
Use Of isMultiple() And deselectAll() In Selenium WebDriver With Example
Now you can easily select or deselect any specific option from select box
or drop down as described in my earlier POST 1, POST 2 and POST 3. All
these three posts will describe you different alternative ways of selecting
options from list box or drop down. Now let me take you one step ahead to
describe
you
the
use
of deselectAll() and isMultiple() methods in selenium webdriver.
deselectAll() Method
deselectAll() method is useful to remove selection from all selected
options of select box. It will works with multiple select box when you need
to remove all selections. Syntax for deselectAll() method is as bellow.
Select listbox = new
Select(driver.findElement(By.xpath("//select[@name='FromLB']")));
listbox.deselectAll();
isMultiple() Method
isMultiple() method is useful to verify if targeted select box is multiple
select box or not means we can select multiple options from that select
box or not. It will return boolean (true or false) value. We can use it with if
condition before working with select box. Syntax is as bellow.
Select listbox = new
Select(driver.findElement(By.xpath("//select[@name='FromLB']")));
boolean value = listbox.isMultiple();
System.out.print(value);
Bellow given example will show you use of isMultiple() and deselectAll()
methods very clearly in selenium webdriver.
@Test
public void test () throws InterruptedException
{
Select listbox = new
Select(driver.findElement(By.xpath("//select[@name='FromLB']")));
//To verify that specific select box supports multiple select or not.
if(listbox.isMultiple())

{
System.out.print("Multiple selections is supported");
listbox.selectByVisibleText("USA");
listbox.selectByValue("Russia");
listbox.selectByIndex(5);
Thread.sleep(3000);
//To deselect all selected options.
listbox.deselectAll();
Thread.sleep(2000);
}
else
{
System.out.print("Not supported multiple selections");
}
}
In above example, if condition will check that listbox is multiple select box
or not? Used listbox.deselectAll(); to remove all selected options.
How To Deselect Option By Visible Text Or Value Or By Index In Selenium
WebDriver With Example
Adding selection or removing selection from list box are very common
actions for list box. WebDriver has 3 alternate options to select or deselect
value from list box. It is very important to learn all three methods of
selecting or deselecting option from list box because if one is not possible
to implement in your test then you
must be aware about alternate option. I already described 3 selection
options in my earlier posts - Selecting specific option BY VISIBLE TEXT, BY
VALUE or BY INDEX from drop down or list box.
Now let me describe you all three deselect methods to deselect specific
option from list box. Do you remember that we can use "removeSelection"
command to deselect option from list box? VIEW THIS SELENIUM IDE
EXAMPLE for "removeSelection" command.
1. Deselect By Visible Text
If you wants to remove selection from list box then you can use
webdriver's deselectByVisibleText() method. Syntax is as bellow. 1st
syntax will locate the select box and 2nd syntax will remove selection by
visible text = Russia.
Select listbox = new
Select(driver.findElement(By.xpath("//select[@name='FromLB']")));
listbox.deselectByVisibleText("Russia");
2. Deselect By Value
You can also deselect option from list box by value. 2nd syntax will

deselect option by value = Mexico.


Select listbox = new
Select(driver.findElement(By.xpath("//select[@name='FromLB']")));
listbox.deselectByValue("Mexico");
3. Deselect By Index
Bellow given syntax will remove selection by index = 5.
Select listbox = new
Select(driver.findElement(By.xpath("//select[@name='FromLB']")));
listbox.deselectByIndex(5);
Execute bellow given example in eclipse and observe results during
execution.
Copy bellow given @Test method part of deselect option by visible text or
value or index and replace it with the @Test method part of example given
on THIS PAGE.(Note : @Test method is marked with pink color in that
linked page).

@Test
public void test () throws InterruptedException
{
driver.findElement(By.id("text1")).sendKeys("My First Name");
Select listbox = new
Select(driver.findElement(By.xpath("//select[@name='FromLB']")));
listbox.selectByVisibleText("USA");
listbox.selectByVisibleText("Russia");
Thread.sleep(1000);
//To deselect by visible text
listbox.deselectByVisibleText("Russia");
Thread.sleep(1000);
listbox.selectByValue("Japan");
listbox.selectByValue("Mexico");
Thread.sleep(1000);
//To deselect by value
listbox.deselectByValue("Mexico");
Thread.sleep(1000);
listbox.selectByIndex(4);
listbox.selectByIndex(5);
Thread.sleep(1000);

//To deselect by index


listbox.deselectByIndex(5);
Thread.sleep(1000);
driver.findElement(By.xpath("//input[@value='->']")).click();
Thread.sleep(1000);
}
}
You can view MORE webdriver examples on THIS LINK.
Common Function To Compare Two Double Values In Selenium WebDriver
Comparison of double values Is not much more different than comparison
of Integer values as described In my PREVIOUS POST but let me give you
example of same so that you can get It better. Let me tell you one thing
that comparison of different data types (compare two strings, compare
two Integers, etc..) Is
pure java concept and It has not any relation with selenium webdriver. My
main Intention Is to show you that how to handle rest of test execution
based on execution result and how to mark your test fail In webdriver test
report without any Interruption In execution.
Let me try to describe you how to compare two double values with
example.
As explained In my previous post, If you are retrieving value from web
page then It will be always In string format because webdriver's .getText()
function Is returning It as a string. So my first task Is to convert It from
string to double using bellow given syntax.
String actualValString = driver.findElement(By.xpath("//*[@id='post-body4292417847084983089']/div[1]/table/tbody/tr[2]/td[4]")).getText();
//To convert actual value string to Double value.
double actualVal = Double.parseDouble(actualValString);
Second task Is to create general function In CommonFunctions class to
compare two double values. Latter on I will use this function whenever
required In my test. Main work of this function Is to accept two double
values then compare them and return true or false based on comparison
result. See bellow given example.
package Testng_Pack;
import org.testng.Assert;
import org.testng.asserts.SoftAssert;

public class CommonFunctions {


SoftAssert Soft_Assert = new SoftAssert();
public boolean compareDoubleVals(double actualDobVal, double
expectedDobVal){
try{
//If this assertion will fail, It will throw exception and catch block will be
executed.
Assert.assertEquals(actualDobVal, expectedDobVal);
}catch(Throwable t){
//This will throw soft assertion to keep continue your execution even
assertion failure.
//Un-comment bellow given hard assertion line and commnet soft
assertion line If you wants to stop test execution on assertion failure.
//Assert.fail("Actual Value '"+actualDobVal+"' And Expected Value
'"+expectedDobVal+"' Do Not Match.");
Soft_Assert.fail("Actual Value '"+actualDobVal+"' And Expected Value
'"+expectedDobVal+"' Do Not Match.");
//If double values will not match, return false.
return false;
}
//If double values match, return true.
return true;
}
}
Now I can use compareDoubleVals function In my test whenever required
as described In bellow given example.
package Testng_Pack;
import
import
import
import
import
import

org.openqa.selenium.By;
org.openqa.selenium.WebDriver;
org.openqa.selenium.firefox.FirefoxDriver;
org.testng.annotations.AfterTest;
org.testng.annotations.BeforeTest;
org.testng.annotations.Test;

public class Common_Functions_Test extends CommonFunctions{


WebDriver driver;
@BeforeTest
public void StartBrowser_NavURL() {
driver = new FirefoxDriver();
driver.get("http://only-testing-blog.blogspot.in/2014/01/textbox.html");
}

@AfterTest
public void CloseBrowser() {
driver.quit();
}
@Test
public void testToCompareDoubles(){
String actualValString = driver.findElement(By.xpath("//*[@id='postbody-4292417847084983089']/div[1]/table/tbody/tr[2]/td[4]")).getText();
//To convert actual value string to Double value.
double actualVal = Double.parseDouble(actualValString);
//Call compareDoubleVals method Inside If condition to check Double
values match or not.
if(compareDoubleVals(actualVal, 20.63)){
//If values match, This block will be executed.
System.out.println("Write Action taking lines In this block when Values
match.");
}else{
//If values not match, This block will be executed.
System.out.println("Write Action taking lines In this block when Values
not match.");
}
//To mark test fail In report at the end of execution If values not match.
Soft_Assert.assertAll();
}
}
Above test will call compareDoubleVals function and It will return false
because actual and expected values will not match. So test will be marked
as fail. You can use hard assertion too Inside compareDoubleVals function
to stop your test on assertion failure.
Method To Compare Two Integer Values In Selenium WebDriver Test
We have learnt how to create common function to compare two strings In
my PREVIOUS POST. Same way, Many times you need to compare two
Integer values. And based on comparison result, You can perform your
next step of test execution. You can also stop or continue your test
execution on assertion
failure by using soft or hard TestNG assertions. In this post, we will see
how to compare two Integer values using common function.
Main Intention of creating this kind of common functions Is to minimize
your code size. You have to create It only once and then you can call It
again and again whenever required In your test. And for that, You have to
create common class which should be accessible from all the test classes.

If you are retrieving text(which Is Integer value) from web page using
webdriver's .getText() function then It will be string and you have to
convert It In Integer value using bellow given syntax before comparision.
String actualValString = driver.findElement(By.xpath("//*[@id='post-body8228718889842861683']/div[1]/table/tbody/tr[1]/td[2]")).getText();
//To convert actual value string to Integer value.
int actualVal = Integer.parseInt(actualValString);
Bellow given example will explain you how to create common function to
compare two Integers In your CommonFunctions class.
package Testng_Pack;
import org.testng.Assert;
import org.testng.asserts.SoftAssert;
public class CommonFunctions {
SoftAssert Soft_Assert = new SoftAssert();
public boolean compareIntegerVals(int actualIntegerVal, int
expectedIntegerVal){
try{
//If this assertion will fail, It will throw exception and catch block will be
executed.
Assert.assertEquals(actualIntegerVal, expectedIntegerVal);
}catch(Throwable t){
//This will throw soft assertion to keep continue your execution even
assertion failure.
//Un-comment bellow given hard assertion line and commnet soft
assertion line If you wants to stop test execution on assertion failure.
//Assert.fail("Actual Value '"+actualIntegerVal+"' And Expected Value
'"+expectedIntegerVal+"' Do Not Match.");
Soft_Assert.fail("Actual Value '"+actualIntegerVal+"' And Expected
Value '"+expectedIntegerVal+"' Do Not Match.");
//If Integer values will not match, return false.
return false;
}
//If Integer values match, return true.
return true;
}
}
Now you can call compareIntegerVals() function In your test to compare
two Integer values as shown In bellow given example.

package Testng_Pack;
import
import
import
import
import
import

org.openqa.selenium.By;
org.openqa.selenium.WebDriver;
org.openqa.selenium.firefox.FirefoxDriver;
org.testng.annotations.AfterTest;
org.testng.annotations.BeforeTest;
org.testng.annotations.Test;

public class Common_Functions_Test extends CommonFunctions{


WebDriver driver;
@BeforeTest
public void StartBrowser_NavURL() {
driver = new FirefoxDriver();
driver.get("http://only-testing-blog.blogspot.in/2014/05/form.html");
}
@AfterTest
public void CloseBrowser() {
driver.quit();
}
@Test
public void testToCompareIntegers(){
String actualValString = driver.findElement(By.xpath("//*[@id='postbody-8228718889842861683']/div[1]/table/tbody/tr[1]/td[2]")).getText();
//To convert actual value string to Integer value.
int actualVal = Integer.parseInt(actualValString);
//Call compareIntegerVals method Inside If condition to check Integer
values match or not.
if(compareIntegerVals(actualVal, 5)){
//If values match, This block will be executed.
System.out.println("Write Action taking lines In this block when Values
match.");
}else{
//If values not match, This block will be executed.
System.out.println("Write Action taking lines In this block when Values
not match.");
}
//To mark test fail In report at the end of execution If values not match.
Soft_Assert.assertAll();
}
}
General Function To Comparing Two Strings In Selenium WebDriver
TestCase

When you will use selenium webdriver to automate real world


applications, Many times you have to compare two strings like page title,
product name or any other string. And based on comparison result you
have to take specific action. Simple example of such scenario Is, You are
navigating on any view product
page to add product In to basket. But before adding product In basket, You
wants to verify product's name to check It Is correct product or not.
Many time you have to compare strings In automating any single
application. So What you will do? You will write same code multiple time In
your different scripts? General way(Which I am using) Is to create common
method In base class (Which Is accessible from all test classes) to
compare two strings. Then we can call that method by passing actual and
expected string to compare strings whenever required In out tests.
Let me explain you how to do It.
VIEW MORE WEBDRIVER TUTORIALS STEP BY STEP
Step 1 : Create CommonFunctions Class In your package which can be
accessible by any other class.
Step 2 : Create method compareStrings which can accept two string
values. Also Create object of TestNG SoftAssert class to assert assertion
softly as shown In bellow given example.
package Testng_Pack;
import org.testng.Assert;
import org.testng.asserts.SoftAssert;
public class CommonFunctions {
SoftAssert Soft_Assert = new SoftAssert();
public boolean compareStrings(String actualStr, String expectedStr){
try{
//If this assertion will fail, It will throw exception and catch block will be
executed.
Assert.assertEquals(actualStr, expectedStr);
}catch(Throwable t){
//This will throw soft assertion to keep continue your execution even
assertion failure.
//Use here hard assertion "Assert.fail("Failure Message String")" If you
wants to stop your test on assertion failure.
Soft_Assert.fail("Actual String '"+actualStr+"' And Expected String
'"+expectedStr +"' Do Not Match.");
//If Strings will not match, return false.
return false;
}

//If Strings match, return true.


return true;
}
}
Step 3 : Now we can call compareStrings method In our test class
whenever required as shown In bellow given example. We have Inherited
CommonFunctions class to use Its function In Common_Functions_Test.
Also call Soft_Assert.assertAll() method at last of your test to mark your
test fail If both strings not match. Read More about usage of TestNG Soft
Assertion In webdriver.
package Testng_Pack;
import
import
import
import
import

org.openqa.selenium.WebDriver;
org.openqa.selenium.firefox.FirefoxDriver;
org.testng.annotations.AfterTest;
org.testng.annotations.BeforeTest;
org.testng.annotations.Test;

//Used Inheritance
public class Common_Functions_Test extends CommonFunctions{
WebDriver driver;
@BeforeTest
public void StartBrowser_NavURL() {
driver = new FirefoxDriver();
driver.get("http://only-testing-blog.blogspot.in/2014/05/login.html");
}
@AfterTest
public void CloseBrowser() {
driver.quit();
}
@Test
public void testToCompareStrings(){
String actualTitle = driver.getTitle();
//Call compareStrings method Inside If condition to check string match or
not.
if(compareStrings(actualTitle, "Only Testing: LogIn")){
//If strings match, This block will be executed.
System.out.println("Write Action taking lines In this block when title
match.");
}else{
//If strings not match, This block will be executed.
System.out.println("Write Action taking lines In this block when title not
match.");
}

//To mark test fail In report at the end of execution If strings not match.
Soft_Assert.assertAll();
}
}
Above given example will compare actual and expected title strings and
mark test failure at the end of test execution If both strings not match
without any Interruption In execution. Now you can call compareStrings
method any time to compare strings. You just need to provide expected
and
actual
string
values.
Note : You can use hard assertion In your common function catch block at
place of soft assertion If you wants to stop test on failure. See bellow. If
you will use bellow given syntax In catch block then It will stop test
execution
on
failure.
Assert.fail("Actual String '"+actualStr+"' And Expected String
'"+expectedStr+"' Do Not Match.");
How To Handle Dynamic Web Table In Selenium WebDriver
If web table has same number of rows and same number of cells In each
rows every time you load page then It Is very easy to handle that table's
data In selenium WebDriver as described In How To Extract Table
Data/Read Table Data Using Selenium WebDriver post. Now supposing
your
table's
rows
and
columns are increasing/decreasing every time you loading page or some
rows has more cells and some rows has less cells then you need to put
some extra code In your webdriver test case which can retrieve cell data
based on number of cells In specific row. Consider the table shown In
bellow given Image.

In this table, Row number 1, 2 and 4 has 3 cells, Row number 3 has 2 Cells
and Row 5 has 1 cell. In this case, You need to do some extra code to
handle these dynamic cells of different rows. To do It, You need to find out
the number of cells of that specific row before retrieving data from It.
You can view more webdriver tutorials with testng and java WEBDRIVER
TUTORIAL @PART 1 and WEBDRIVER TUTORIAL @PART 2.

Bellow given example will first locate the row and then It will calculate the
cells from that row and then based on number of cells, It will retrieve cell
data Information.
Run bellow given example In your eclipse with testng which Is designed
for above given dynamic web table.
package Testng_Pack;
import java.util.List;
import java.util.concurrent.TimeUnit;
import
import
import
import
import
import
import

org.openqa.selenium.By;
org.openqa.selenium.WebDriver;
org.openqa.selenium.WebElement;
org.openqa.selenium.firefox.FirefoxDriver;
org.testng.annotations.AfterTest;
org.testng.annotations.BeforeTest;
org.testng.annotations.Test;

public class dynamic_table {


WebDriver driver = new FirefoxDriver();
@BeforeTest
public void setup() throws Exception {
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
driver.get("http://only-testing-blog.blogspot.in/2014/05/form.html");
}
@AfterTest
public void tearDown() throws Exception {
driver.quit();
}
@Test
public void Handle_Dynamic_Webtable() {
//To locate table.
WebElement mytable = driver.findElement(By.xpath(".//*[@id='postbody-8228718889842861683']/div[1]/table/tbody"));
//To locate rows of table.
List<WebElement> rows_table =
mytable.findElements(By.tagName("tr"));
//To calculate no of rows In table.
int rows_count = rows_table.size();
//Loop will execute till the last row of table.
for (int row=0; row<rows_count; row++){
//To locate columns(cells) of that specific row.

List<WebElement> Columns_row =
rows_table.get(row).findElements(By.tagName("td"));
//To calculate no of columns(cells) In that specific row.
int columns_count = Columns_row.size();
System.out.println("Number of cells In Row "+row+" are
"+columns_count);
//Loop will execute till the last cell of that specific row.
for (int column=0; column<columns_count; column++){
//To retrieve text from that specific cell.
String celtext = Columns_row.get(column).getText();
System.out.println("Cell Value Of row number "+row+" and column
number "+column+" Is "+celtext);
}
System.out.println("--------------------------------------------------");
}
}
}
Above example will works for dynamic changing web table too where
number of rows changing every time you load the page or search for
something.
How To Handle Ajax Auto Suggest Drop List In Selenium Webdriver
What Is Ajax Auto Suggest Drop List?
Before learning about how to handle ajax auto suggest drop list In
selenium webdriver, Let me tell you what Is ajax auto suggest drop list. If
you have visited any site with search box and that search box Is showing
auto suggest list when you type some thing Inside It. Simplest example of
ajax auto suggest drop list Id
Google search suggestion. When you will type something Inside It, It will
show you a list of suggestions as shown In bellow given Image.

This Is only example for your reference. You will find this kind of ajax drop
lists In many sites.
How to handle ajax drop list In selenium WebDriver
Now supposing you wants to select some value from that auto suggest list
or you wants to store and print all those suggestions then how will you do
It?. If you know, It Is very hard to handle such ajax In selenium IDE. Let we
try to print all those suggestions In console.

Here, Xpath pattern Is same for all ajax auto suggest drop list Items. Only
changing Is Value Inside <tr> tag. See bellow xpath of 1st two Items of
drop list.
//*[@id='gsr']/table/tbody/tr[1]/td[2]/table/tbody/tr[1]/td/div/table/tbody/tr
[1]/td[1]/span
//*[@id='gsr']/table/tbody/tr[1]/td[2]/table/tbody/tr[2]/td/div/table/tbody/tr
[1]/td[1]/span
So we will use for loop(As described In my THIS POST) to feed that
changing values to xpath of drop list different Items. Other one thing we
need to consider Is we don't know how many Items It will show In ajax
drop list. Some keywords show you 4 Items and some other will show you
more than 4 Items In drop list. To handle this dynamic changing list, We
will
USE
TRY
CATCH
BLOCK
to
catch
the
NoSuchElementException exception if not found next Item In ajax drop
list.
In bellow given example, we have used testng @DataProvider annotation.
If you know, @DataProvider annotation Is useful for data driven testing.
THIS LINKED POST will describe you the usage of @DataProvider
annotation with detailed example and explanation.
Run bellow given example In your eclipse with testng and see how It Is
retrieving values from ajax drop list and print them In console.
package Testng_Pack;
import java.util.concurrent.TimeUnit;
import
import
import
import
import
import
import

org.openqa.selenium.By;
org.openqa.selenium.WebDriver;
org.openqa.selenium.firefox.FirefoxDriver;
org.testng.annotations.AfterTest;
org.testng.annotations.BeforeTest;
org.testng.annotations.DataProvider;
org.testng.annotations.Test;

public class Ajax_Handle {


WebDriver driver = new FirefoxDriver();
@BeforeTest
public void setup() throws Exception {
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
driver.get("http://www.google.com");
}

@AfterTest
public void tearDown() throws Exception {
driver.quit();
}
//Data provider Is used for supplying 2 different values to
Search_Test method.
@DataProvider(name="search-data")
public Object[][] dataProviderTest(){
return new Object[][]{{"selenium webdriver tutorial"},{"auto
s"}};
}
@Test(dataProvider="search-data")
public void Search_Test(String Search){
driver.findElement(By.xpath("//input[@id='gbqfq']")).clear();
driver.findElement(By.xpath("//input[@id='gbqfq']")).sendKeys(Search);
int i=1;
int j=i+1;
try{
//for loop will run till the
NoSuchElementException exception.
for(i=1; i<j;i++)
{
//Value of variable i Is used for
creating xpath of drop list's different elements.
String suggestion =
driver.findElement(By.xpath("//*[@id='gsr']/table/tbody/tr[1]/td[2]/table/tb
ody/tr["+i+"]/td/div/table/tbody/tr/td[1]/span")).getText();
System.out.println(suggestion);
j++;
}
}catch(Exception e){//Catch block will catch
and handle the exception.
System.out.println("***Please search for
another word***");
System.out.println();
}
}
}
This way you can also select specific from that suggestion for your
searching purpose. It Is very simple In selenium webdriver. You can use
other or more search values In above example. To do It simply modify
@DataProvider annotation method.

Submitting Form Using submit() Method Of Selenium WebDriver


You will find many forms In any website like Contact Us form, New User
Registration Form, Inquiry Form, LogIn Form etc.. Supposing you are
testing one site where you have to prepare Login form submission test
case In selenium webdriver then how will you do It? Simplest way Is
described In THIS POST. If you will
see In that example post, we have used .click() method to click on Login
button.
Selenium Webdriver has one special method to submit any form and that
method name Is submit(). submit() method works same as clicking on
submit button.
WEBDRIVER TUTORIAL PART 2
When to use .click() method
You can use .click() method to click on any button. Means element's type
= "button" or type = "submit", .click() method will works for both.
When to use .submit() method
If you will look at firebug view for any form's submit button then always
It's type will be "submit" as shown In bellow given Image. In this case,
.submit() method Is very good alternative of .click() method.

Final Notes :
1. If any form has submit button which has type = "button" then .submit()
method will not work.
2. If button Is not Inside <form> tag then .submit() method will not work.
Now let us take a look at very simple example where I have used .submit()
method to submit form. In bellow given example, I have not used .click()
method but used .submit() method with company name field. Run bellow
give example In eclipse with testng and verify the result.
package Testng_Pack;
import java.util.concurrent.TimeUnit;

import
import
import
import
import
import

org.openqa.selenium.By;
org.openqa.selenium.WebDriver;
org.openqa.selenium.firefox.FirefoxDriver;
org.testng.annotations.AfterTest;
org.testng.annotations.BeforeTest;
org.testng.annotations.Test;

public class Form_Submit {


WebDriver driver = new FirefoxDriver();
@BeforeTest
public void setup() throws Exception {
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
driver.get("http://only-testing-blog.blogspot.in/2014/05/form.html");
}
@AfterTest
public void tearDown() throws Exception {
driver.quit();
}
@Test
public void LogIn_Test(){
driver.findElement(By.xpath("//input[@name='FirstName']")).sendKeys("M
yFName");
driver.findElement(By.xpath("//input[@name='LastName']")).sendKeys("M
yLName");
driver.findElement(By.xpath("//input[@name='EmailID']")).sendKeys("My
Email ID");
driver.findElement(By.xpath("//input[@name='MobNo']")).sendKeys("My
Mob No.");
driver.findElement(By.xpath("//input[@name='Company']")).sendKeys("My
Comp Name");
//To submit form.
//You can use any other Input field's(First Name, Last Name etc.) xpath
too In bellow given syntax.
driver.findElement(By.xpath("//input[@name='Company']")).submit();
String alrt = driver.switchTo().alert().getText();
driver.switchTo().alert().accept();
System.out.println(alrt);
}
}

Above example will simply submit the form and retrieve submission alert
to print. So this way we can use webdriver's submit method to submit any
form. You can try different form for your better understanding.
How To Extract Table Data/Read Table Data Using Selenium WebDriver
Example
Table Is very frequently used element In web pages. Many times you need
to extract your web table data to compare and verify as per your test
case. You can read about How To Extracting All Links From Page If you
need It In your test scenarios. If you knows, Selenium IDE has also many
commands related to Table
and you can view all of them on LINK 1 and LINK 2 with examples. Now let
me come to our current discussion point about how to read values from
table. Before reading values from web table, You must know there are how
many rows and how many columns In your table. Let we try to get number
of rows and columns from table.
SELENIUM WEBDRIVER STEP BY STEP TUTORIALS.
How To Get Number Of Rows Using Selenium WebDriver

Look at the firebug view of above HTML table. In any web table, Number
of <tr> tags Inside <tbody> tag describes the number of rows of table. So
you need to calculate that there are how many <tr> tags Inside <tbody>
tag. To get row count for above given example table, we can use
webdriver statement like bellow.
int Row_count = driver.findElements(By.xpath("//*[@id='post-body6522850981930750493']/div[1]/table/tbody/tr")).size();
In above syntax, .size() method with webdriver's findElements method will
retrieve the count of <tr> tags and store It In Row_count variable.

How To Get Number Of Columns Using Selenium WebDriver


Same way In any web table, Number of <td> tags from any <tr> tag
describes the number of columns of table as shown In bellow given Image.

So for getting number of columns, we can use syntax like bellow.


int Col_count = driver.findElements(By.xpath("//*[@id='post-body6522850981930750493']/div[1]/table/tbody/tr[1]/td")).size();
Now we have row count and column count. One more thing you require to
read data from table Is generating Xpath for each cell of column. Look at
bellow given xpath syntax of 1st cell's 1st and 2nd rows.
//*[@id='post-body-6522850981930750493']/div[1]/table/tbody/tr[1]/td[1]
//*[@id='post-body-6522850981930750493']/div[1]/table/tbody/tr[2]/td[1]
Highlighted string Is common for both cell's xpath. Only changing Is row
number Inside tr node. So here we can pass Row_count variable's
value Inside tr node.
Same way, look at bellow given xpath syntax of 1st and 2nd cells of 1st
row. Highlighted string Is common for both cell's xpath. Only changing Is
column number Inside td node. So here we can pass Col_count variable's
value Inside td node.
//*[@id='post-body-6522850981930750493']/div[1]/table/tbody/tr[1]/td[1]
//*[@id='post-body-6522850981930750493']/div[1]/table/tbody/tr[1]/td[2]
All above thing Is applied In bellow given example. Simply run It In your
eclipse using testng and observe output In console.
package Testng_Pack;

import java.util.concurrent.TimeUnit;
import
import
import
import
import
import

org.openqa.selenium.By;
org.openqa.selenium.WebDriver;
org.openqa.selenium.firefox.FirefoxDriver;
org.testng.annotations.AfterTest;
org.testng.annotations.BeforeTest;
org.testng.annotations.Test;

public class table {


WebDriver driver = new FirefoxDriver();
@BeforeTest
public void setup() throws Exception {
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
driver.get("http://only-testing-blog.blogspot.in/2013/09/test.html");
}
@AfterTest
public void tearDown() throws Exception {
driver.quit();
}
@Test
public void print_data(){
//Get number of rows In table.
int Row_count = driver.findElements(By.xpath("//*[@id='post-body6522850981930750493']/div[1]/table/tbody/tr")).size();
System.out.println("Number Of Rows = "+Row_count);
//Get number of columns In table.
int Col_count = driver.findElements(By.xpath("//*[@id='post-body6522850981930750493']/div[1]/table/tbody/tr[1]/td")).size();
System.out.println("Number Of Columns = "+Col_count);
//divided xpath In three parts to pass Row_count and Col_count values.
String first_part = "//*[@id='post-body6522850981930750493']/div[1]/table/tbody/tr[";
String second_part = "]/td[";
String third_part = "]";
//Used for loop for number of rows.
for (int i=1; i<=Row_count; i++){
//Used for loop for number of columns.
for(int j=1; j<=Col_count; j++){
//Prepared final xpath of specific cell as per values of i and j.
String final_xpath = first_part+i+second_part+j+third_part;

//Will retrieve value from located cell and print It.


String Table_data = driver.findElement(By.xpath(final_xpath)).getText();
System.out.print(Table_data +" ");
}
System.out.println("");
System.out.println("");
}
}
}
Console output of above given example will looks like bellow.
Number Of Rows = 3
Number Of Columns = 6
11 12 13 14 15 16
21 22 23 24 25 26
31 32 33 34 35 36
Here you can see, all the values of table are extracted and printed.
Selenium WebDriver : Extracting All Text Fields From Web Page
Sometimes you need to extract specific types of web elements from page
like extract all Links to open all of them one by one, extract all text boxes
from page to type some text In all of them or In some of them one by one.
Previously we have learnt how to extract all links from page In THIS POST.
Now supposing you have
a scenario where you needs to extract all text fields from page to send
some text In all of them how to do It In selenium WebDriver?
You can VIEW MORE TUTORIALS ON SELENIUM WEBDRIVER.
WebDriver's In built findelements method will help us to find all text boxes
from page. If you know, Each simple text box are Input fields and will have
always attribute type = text and If It Is password text box then It's type
will be password as shown In bellow given Image.

In short we have to find all those Input fields where type = "text" or
"password". In bellow given example, I have used findelements method to
find and store all those elements In txtfields array list and then used for
loop to type some text In all of them.
package Testng_Pack;
import java.util.List;
import
import
import
import
import
import
import

org.openqa.selenium.By;
org.openqa.selenium.WebDriver;
org.openqa.selenium.WebElement;
org.openqa.selenium.firefox.FirefoxDriver;
org.testng.annotations.AfterTest;
org.testng.annotations.BeforeTest;
org.testng.annotations.Test;

public class Extract_Text {


WebDriver driver;
@BeforeTest
public void StartBrowser() {
driver = new FirefoxDriver();
}
@Test
public void Text() throws InterruptedException{
driver.get("http://only-testing-blog.blogspot.in/2014/05/login.html");
//find all input fields where type = text or password and store them In
array list txtfields.

List<WebElement> txtfields =
driver.findElements(By.xpath("//input[@type='text' or
@type='password']"));
//for loop to send text In all text box one by one.
for(int a=0; a<txtfields.size();a++){
txtfields.get(a).sendKeys("Text"+(a+1));
}
Thread.sleep(3000);
}
@AfterTest
public void CloseBrowser() {
driver.quit();
}
}
This way we can extract all text box from page If required In any scenario.
How To Download Different Files Using Selenium WebDriver
In my PREVIOUS POST, we have learnt about how to create create and use
custom profile Firefox browser to use It In selenium webdriver. Now let me
show you how to create Firefox custom profile run time and set Its
properties to download any file using selenium webdriver. Many times you
need to download
different files from sites like MS Excel file, MS Word File, Zip file, PDF file,
CSV file, Text file, ect..
It Is tricky way to download file using selenium webdriver. Manually when
you click on link to download file, It will show you dialogue to save file In
your local drive as shown In bellow given Image.

Now selenium webdriver do not have any feature to handle this save file
dialogue. But yes, Selenium webdriver has one more very good feature by
which you do not need to handle that dialogue and you can download any
file very easily. We can do It using webdriver's Inbuilt class FirefoxProfile
and Its different methods. Before looking at example of downloading file,
Let me describe you some thing about file's MIME types. Yes you must
know MIME type of file which you wants to download using selenium
webdriver.
What Is MIME of File
MIME Is full form of Multi-purpose Internet Mail Extensions which Is useful
to Identify file type by browser or server to transfer online.
You need to provide MIME type of file In your selenium webdriver test so
that you must be aware about It. There are many online tools available to
know MIME type of any file. Just google with "MIME checker" to find this
kind of tools.
In our example given bellow, I have used MIME types as shown bellow for
different file types In bellow given selenium webdriver test.
1. Text File (.txt) - text/plain
2. PDF File (.pdf) - application/pdf
3. CSV File (.csv) - text/csv
4. MS
Excel
File
(.xlsx)
- application/vnd.openxmlformatsofficedocument.spreadsheetml.sheet
5. MS
word
File
(.docx)
- application/vnd.openxmlformatsofficedocument.wordprocessingml.document
Example Of downloading different files using selenium webdriver
package Testng_Pack;
import
import
import
import
import
import
import

org.openqa.selenium.By;
org.openqa.selenium.WebDriver;
org.openqa.selenium.firefox.FirefoxDriver;
org.openqa.selenium.firefox.FirefoxProfile;
org.testng.annotations.AfterTest;
org.testng.annotations.BeforeTest;
org.testng.annotations.Test;

public class downloadingfile {


WebDriver driver;

@BeforeTest
public void StartBrowser() {
//Create object of FirefoxProfile in built class to access Its properties.
FirefoxProfile fprofile = new FirefoxProfile();
//Set Location to store files after downloading.
fprofile.setPreference("browser.download.dir",
"D:\\WebDriverdownloads");
fprofile.setPreference("browser.download.folderList", 2);
//Set Preference to not show file download confirmation dialogue using
MIME types Of different file extension types.
fprofile.setPreference("browser.helperApps.neverAsk.saveToDisk",
"application/vnd.openxmlformatsofficedocument.spreadsheetml.sheet;"//MIME types Of MS Excel File.
+ "application/pdf;" //MIME types Of PDF File.
+ "application/vnd.openxmlformatsofficedocument.wordprocessingml.document;" //MIME types Of MS doc
File.
+ "text/plain;" //MIME types Of text File.
+ "text/csv"); //MIME types Of CSV File.
fprofile.setPreference( "browser.download.manager.showWhenStarting",
false );
fprofile.setPreference( "pdfjs.disabled", true );
//Pass fprofile parameter In webdriver to use preferences to download
file.
driver = new FirefoxDriver(fprofile);
}
@Test
public void OpenURL() throws InterruptedException{
driver.get("http://only-testing-blog.blogspot.in/2014/05/login.html");
//Download Text File
driver.findElement(By.xpath("//a[contains(.,'Download Text
File')]")).click();
Thread.sleep(5000);//To wait till file gets downloaded.
//Download PDF File
driver.findElement(By.xpath("//a[contains(.,'Download PDF
File')]")).click();
Thread.sleep(5000);
//Download CSV File
driver.findElement(By.xpath("//a[contains(.,'Download CSV
File')]")).click();
Thread.sleep(5000);
//Download Excel File
driver.findElement(By.xpath("//a[contains(.,'Download Excel
File')]")).click();
Thread.sleep(5000);
//Download Doc File

driver.findElement(By.xpath("//a[contains(.,'Download Doc
File')]")).click();
Thread.sleep(5000);
}
@AfterTest
public void CloseBrowser() {
driver.quit();
}
}
When you run above example, It will download all 5(Text, pdf, CSV, docx
and xlsx) files one by one and store them In D:\WebDriverdownloads
folder automatically as shown In bellow given example.

InterruptedException Is used with method OpenURL to handle checked


exception of Thread.sleep(5000). View detailed tutorials of exception
handling In selenium WebDriver on THIS LINK.
This way you can download any file using selenium webdriver like zip file,
exe file, etc.. Just know your file's MIME type and download It as shown In
above example.
How To Handle Exception In Java : Tutorials For Selenium WebDriver
Anyone don't like exceptions and at the same time, anyone can not hide
himself from exceptions when running webdriver tests because (What Is
An Exception? :->) exception Is an error event generated during the
execution of webdriver test case or java program which disrupts test
execution In between. Exception
can arise due to the many reasons like, network connection or hardware
failure, Invalid data entered by user, DB server down etc.. So all these

things can happens any time when you run your selenium webdriver test
case and we can not stop It. So Instead of thinking about stopping
exception(Which Is not possible) during run time, Think about handling
exceptions. Java provides very good exception handling mechanism to
recover from this kind of errors. Let us learn different ways of handling
exception In java.
There are two types of exceptions In java as bellow.
1. Checked Exception :
Checked exceptions are those exceptions which are checked during
compile time and needs catch block to caught that exception during
compilation. If compiler will not find catch block then It will throw
compilation error. Very simple example of checked exception Is using
Thread.sleep(5000); statement In your code. If you will not put this
statement Inside try catch block then It will not allow you to compile your
program.
2. Unchecked Exceptions :
Unchecked exception are those exception which are not checked during
compile time. Generally checked exceptions occurred due to the error In
code during run time. Simplest example of unchecked exception Is int i =
4/0;. This statement will throws / by zero exception during run time.
Handling exceptions using try-catch block
We need to place try catch block around that code which might generate
exception. In bellow given example, System.out.println(a[9]); Is written
Intentionally to generate an exception. If you see, that statement Is
written Inside try block so If that statement throw an exception - catch
block can caught and handle It.
public class Handle_exce {
public static void main(String[] args) {
int a[] = {3,1,6};
try { //If any exception arise Inside this try block, Control will goes to
catch block.
System.out.println("Before Exception");
//unchecked exception
System.out.println(a[9]);//Exception will arise here
because we have only 3 values In array.
System.out.println("After Exception");
}catch(Exception e){
System.out.println("Exception Is "+e);
}
System.out.println("Outside The try catch.");
}
}

If you will run above example In your eclipse, try block will be
executed. "Before Exception" statement will be printed In console and
Next statement will generate an exception so "After Exception" statement
will be not printed In console and control will goes to catch block to handle
that exception.
Always use try catch block to log your exception In selenium webdriver
reports.
Handling exceptions using throws keyword
Another way of handling exception Is using throws keyword with method
as shown In bellow given example. Supposing you have a throwexc
method which Is throwing some exception and this method Is called from
some other method catchexc. Now you wants to handle exception of
throwexc method In to catchexc method then you need to use throws
keyword with throwexc method.
public class Handle_exce {
public static void main(String[] args) {
catchexc();
}
private static void catchexc() {
try {
//throwexc() Method called.
throwexc();
} catch (ArithmeticException e) { //Exception of throwexc() will be
caught here and take required action.
System.out.println("Devide by 0 error.");
}
}
//This method will throw ArithmeticException divide by 0.
private static void throwexc() throws ArithmeticException {
int i=15/0;
}
}
In above given example, Exception of throwexc() Is handled Inside
catchexc() method.
Using throw Keyword To Throw An Exception Explicitly
Difference between throw and throws In java :
As we learnt, throws keyword Is useful to throw those exceptions to calling
methods which are not handled Inside called methods. Throw keyword has
a different work - throw keyword Is useful to throw an exception explicitly
whenever required. This Is the difference between throw and throws In
java. Interviewer can ask this question. Let us look at practical example.

public class Handle_exce {


public static void main(String[] args) {
catchexc();
}
private static void catchexc() {
try {
//throwexc() Method called.
throwexc();
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Array Index out of bound exception.");
}
}
private static void throwexc() {
//This statement will throw ArrayIndexOutOfBoundsException exception.
throw new ArrayIndexOutOfBoundsException();
}
}
In above example, ArrayIndexOutOfBoundsException exception will be
thrown by throw keyword of throwexc method.
finally keyword and Its use
finally keyword Is used with try catch block at the end of try catch block.
Code written Inside finally block will be executed always regardless of
exception Is occurred or not. Main intention of using finally with try catch
block Is : If you wants to perform some action without considering
exception occurred or not. finally block will be executed In both the cases.
Let us see simple example of finally.
public class Handle_exce {
public static void main(String[] args) {
try{
int i=5/0; //Exception will be thrown.
System.out.println("Value Of i Is "+i);//This statement will be not
executed.
}catch (Exception e)//Exception will be caught.
{
System.out.println("Inside catch."+e);//print the exception.
}finally//finally block will be executed.
{
System.out.println("Inside finally. Please take appropriate action");
}
try{
int j=5/2; //Exception will be not thrown.
System.out.println("Value Of j Is "+j);//This statement will be executed.

}catch (Exception e)//No exception so catch block code will not execute.
{
System.out.println("Inside catch."+e);
}finally//finally block code will be executed.
{
System.out.println("Inside finally. Please take appropriate action");
}
}
}
In above example, 2 try-catch-finally blocks used. Run above example and
observe result.
1st try block will throw an error and catch will handle and then finally
block will be executed. 2nd try block will not throw any error so catch will
be not executed but finally block will be executed. So In both the cases
finally block will be executed.
So all these things about exception and ways of handling them will helps
you In your webdriver test exception handling.
How To Create And Use Custom Firefox Profile For Selenium WebDriver
What Is the Firefox Profile?
When you Install Firefox In your computer, Firefox creates one default
profile folder In your local drive to save your preferences like your
bookmarks, your preferred home page on Firefox open, your toolbar
settings, your saved passwords and all the other settings. You can create
different profiles for your Firefox
browser as per your requirement. Now supposing same computer Is used
by two users and both wants their own Firefox settings then both users
can create their own Firefox profile to access their own settings when
he/she opens Firefox browser.
You can LEARN SELENIUM WEBDRIVER STEP BY STEP to become master of
selenium Webdriver.
If you have noticed, When you will run your selenium webdriver test In
Firefox browser then WebDriver will open blank Firefox browser like No
bookmarks, No saved passwords, No addons etc.. as shown In bellow
given Image.

If you wants access of all these things In your selenium webdriver test
browser then you have to create new profile of Firefox and set all required
properties In newly created profile and then you can access that profile In
webdriver using FirefoxProfile class of webdriver.
First Of all, Let us see how to create new profile of Firefox and then we will
see how to use that profile In your test.
How to Create New Custom Firefox Profile For Selenium WebDriver?
To create new firefox profile manually,

Close Firefox browser from File -> Exit.

Go to Start -> Run and type "firefox.exe -p" In run window and click
OK. It will open "Firefox - Choose User Profile" dialogue as shown In
bellow Image.

Now click on Create profile button. It will open create profile wizard
dialogue. Click On Next as shown In bellow given Image.

On next screen, Give profile name = "WebDriver_Profile" and click


on finish button as shown In bellow given Image.

It Will create new profile of Firefox.

To use that newly Created profile, Select that profile and click on
Start Firefox button as shown In bellow given Image. It will open
Firefox browser with newly created profile.

Now you can make you required settings on this new created profile
browser like add your required addons, bookmark your required page,
network settings, proxy settings, etc.. and all other required settings.
How To Access Custom Firefox(Changing User Agent) Profile In Selenium
WebDriver Test
To access newly created Firefox profile In selenium WebDriver, We needs
to use webdriver's Inbuilt class ProfilesIni and Its method getProfile as
shown In bellow given example.
package Testng_Pack;
import
import
import
import
import
import
import

org.openqa.selenium.WebDriver;
org.openqa.selenium.firefox.FirefoxDriver;
org.openqa.selenium.firefox.FirefoxProfile;
org.openqa.selenium.firefox.internal.ProfilesIni;
org.testng.annotations.AfterTest;
org.testng.annotations.BeforeTest;
org.testng.annotations.Test;

public class custom_profile {


WebDriver driver;
@BeforeTest
public void StartBrowser() {
//Create object of webdriver's inbuilt class ProfilesIni to access Its method
getProfile.
ProfilesIni firProfiles = new ProfilesIni();
//Get access of newly created profile WebDriver_Profile.
FirefoxProfile wbdrverprofile = firProfiles.getProfile("WebDriver_Profile");
//Pass wbdrverprofile parameter to FirefoxDriver.
driver = new FirefoxDriver(wbdrverprofile);
}

@Test
public void OpenURL(){
driver.get("http://only-testing-blog.blogspot.in/2014/05/login.html");
}
@AfterTest
public void CloseBrowser() {
driver.quit();
}
}
When you will run above given example, It will open Firefox browser with
newly created profile settings.
Why needs To Set Firefox Profile In Selenium WebDriver
To perform some actions In your selenium webdriver test, You need special
Firefox profile. Some example actions are as bellow where we need to set
Firefox profile. We will learn more about how to perform all those actions
In Selenium webdriver In my upcoming posts.
1. To Download files. VIEW EXAMPLE
2. To Set Proxy Settings.
3. To Resolve Certificate related errors.
If you have any example where we need to set Firefox profile properties
then you can share It with world by commenting bellow.
WebDriver Test Data Driven Testing Using TestNG @DataProvider
Annotation
Data driven testing Is most Important topic for all software testing
automation tools because you need to provide different set of data In your
tests. If you are selenium IDE user and you wants to perform data driven
testing IN YOUR TEST then THESE POSTS will helps you. For Selenium
Webdriver, Data driven testing
using excel file Is very easy. For that you need support of Java Excel API
and It Is explained very clearly In THIS POST. Now If you are using TestNG
framework for selenium webdriver then there Is one another way to
perform data driven testing.
TestNG @DataProvider Annotation
@DataProvider Is TestNG annotation. @DataProvider Annotation of testng
framework provides us a facility of storing and preparing data set In
method. Task of @DataProvider annotated method Is supplying data for a
test method. Means you can configure data set In that method and then
use that data In your test method. @DataProvider annotated method must
return an Object[][] with data.

Let us see simple example of data driven testing using @DataProvider


annotation. We have to create 2 dimensional array In @DataProvider
annotated method to store data as shown In bellow given example. You
can VIEW THIS POST to know more about two dimensional array In java.
Bellow given example will retrieve userid and password one by one from
@DataProvider annotated method and will feed them In LogIn_Test(String
Usedid, String Pass) one by one. Run this example In your eclipse and
observe result.
package Testng_Pack;
import
import
import
import
import
import
import
import

java.util.concurrent.TimeUnit;
org.openqa.selenium.By;
org.openqa.selenium.WebDriver;
org.openqa.selenium.firefox.FirefoxDriver;
org.testng.annotations.AfterTest;
org.testng.annotations.BeforeTest;
org.testng.annotations.DataProvider;
org.testng.annotations.Test;

public class Sample_Login {


WebDriver driver = new FirefoxDriver();
@BeforeTest
public void setup() throws Exception {
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
driver.get("http://only-testing-blog.blogspot.in/2014/05/login.html");
}
@AfterTest
public void tearDown() throws Exception {
driver.quit();
}
//This method will return two dimensional array.
//This method behaves as data provider for LogIn_Test method.
@DataProvider
public Object[][] LoginCredentials(){
//Created two dimensional array with 4 rows and 2 columns.
//4 rows represents test has to run 4 times.
//2 columns represents 2 data parameters.
Object[][] Cred = new Object[4][2];
Cred[0][0] = "UserId1";
Cred[0][1] = "Pass1";

Cred[1][0] = "UserId2";
Cred[1][1] = "Pass2";
Cred[2][0] = "UserId3";
Cred[2][1] = "Pass3";
Cred[3][0] = "UserId4";
Cred[3][1] = "Pass4";
return Cred; //Returned Cred
}
//Give data provider method name as data provider.
//Passed 2 string parameters as LoginCredentials() returns 2 parameters
In object.
@Test(dataProvider="LoginCredentials")
public void LogIn_Test(String Usedid, String Pass){
driver.findElement(By.xpath("//input[@name='userid']")).clear();
driver.findElement(By.xpath("//input[@name='pswrd']")).clear();
driver.findElement(By.xpath("//input[@name='userid']")).sendKeys(Usedid)
;
driver.findElement(By.xpath("//input[@name='pswrd']")).sendKeys(Pass);
driver.findElement(By.xpath("//input[@value='Login']")).click();
String alrt = driver.switchTo().alert().getText();
driver.switchTo().alert().accept();
System.out.println(alrt);
}
}
testng.xml file to run this example Is as bellow.
<suite name="Simple Suite">
<test name="Simple Skip Test">
<classes>
<class name = "Testng_Pack.Sample_Login"/>
</classes>
</test>
</suite>
When you will run above example In eclipse, It will enter UserID and
passwords one by one In UserId and password test box of web page.
TestNG result report will looks like bellow.

Creating Object Repository Using Properties File In Selenium WebDriver


In selenium WebDriver, There Is not any built In facility to create object
repository. So maintenance of page objects(Page element locators)
becomes very hard If you will write all objects of page on code level. Let
me give you one simple example - You have one search button and you
have used It(Using Id locator) In many
of your test cases. Now supposing someone has changed Its Id In your
application then what you will do? You will go for replacing Id of that
element In all test cases wherever It Is used? It will create overhead for
you. Simple solution to remove this overhead Is creating object repository
using properties File support of java. In properties file, First we can write
element locator of web element and then we can use It In our test cases.
Let us try to create object repository for simple calculator application
given on THIS PAGE and then will try to create test case for that calc
application using object repository..
How to create new properties file
To create new properties file, Right click on your project package -> New
-> Other .

It will open New wizard. Expand General folder In New wizard and select
File and click on Next button.

Give file name objects.properties on next window and click on Finish


button.

It will add object.properties file under your package. Now copy paste
bellow
given
lines
in
objects.properties
file.
So
now
this objects.properties file Is object repository for your web application
page calc.
objects.properties file
#Created unique key for Id of all web elements.
# Example 'one' Is key and '1' Is ID of web element button 1.
one=1
two=2
three=3
four=4
five=5
six=6
seven=7
eight=8
nine=9
zero=0
equalsto=equals
cler=AC
result=Resultbox
plus=plus
minus=minus
mul=multiply
In above file, Left side value Is key and right side value Is element
locator(by Id) of all web elements of web calculator. You can use other
element locator methods too like xpath, css ect.. VISIT THIS LINK to view
different element locator methods of webdriver.

Now let us create webdriver test case to perform some operations on


calculation. In bellow given example, All the element locators are coming
from objects.properties file using obj.getProperty(key). Here key Is
reference of element locator value in objects.properties file.
package ObjectRepo;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;
import
import
import
import
import
import

org.openqa.selenium.By;
org.openqa.selenium.WebDriver;
org.openqa.selenium.firefox.FirefoxDriver;
org.testng.annotations.AfterMethod;
org.testng.annotations.BeforeMethod;
org.testng.annotations.Test;

public class CalcTest {


WebDriver driver = new FirefoxDriver();
@BeforeMethod
public void openbrowser() throws IOException {
driver.manage().window().maximize();
driver.get("http://only-testing-blog.blogspot.in/2014/04/calc.html");
}
@AfterMethod
public void closebrowser() {
driver.quit();
}
@Test
public void Calc_Operations() throws IOException{
//Create Object of Properties Class.
Properties obj = new Properties();
//Create Object of FileInputStream Class. Pass file path.
FileInputStream objfile = new
FileInputStream(System.getProperty("user.dir")
+"\\src\\ObjectRepo\\objects.properties");
//Pass object reference objfile to load method of Properties object.
obj.load(objfile);
//Sum operation on calculator.
//Accessing element locators of all web elements using
obj.getProperty(key)
driver.findElement(By.id(obj.getProperty("eight"))).click();
driver.findElement(By.id(obj.getProperty("plus"))).click();

driver.findElement(By.id(obj.getProperty("four"))).click();
driver.findElement(By.id(obj.getProperty("equalsto"))).click();
String i =
driver.findElement(By.id(obj.getProperty("result"))).getAttribute("value");
System.out.println(obj.getProperty("eight")+" +
"+obj.getProperty("four")+" = "+i);
driver.findElement(By.id(obj.getProperty("result"))).clear();
//Subtraction operation on calculator.
//Accessing element locators of all web elements using
obj.getProperty(key)
driver.findElement(By.id(obj.getProperty("nine"))).click();
driver.findElement(By.id(obj.getProperty("minus"))).click();
driver.findElement(By.id(obj.getProperty("three"))).click();
driver.findElement(By.id(obj.getProperty("equalsto"))).click();
String j =
driver.findElement(By.id(obj.getProperty("result"))).getAttribute("value");
System.out.println(obj.getProperty("nine")+" - "+obj.getProperty("three")
+" = "+j);
}
}
Run above given example In your eclipse and observe execution.
Now supposing I have many such test cases and some one has changed Id
of any button of calc application then what I have to do? I have to modify
all test cases? Answer Is No. I just need to modify objects.properties file
because I have not use element's Id directly In any test case but I have
Used just Its key reference In all test cases.
This way you can create object repository of all your web elements In
one .properties file. You can VIEW MORE TUTORIALS about selenium
webdriver.
Use Of isMultiple() And deselectAll() In Selenium WebDriver With Example
Now you can easily select or deselect any specific option from select box
or drop down as described in my earlier POST 1, POST 2 and POST 3. All
these three posts will describe you different alternative ways of selecting
options from list box or drop down. Now let me take you one step ahead to
describe
you
the
use
of deselectAll() and isMultiple() methods in selenium webdriver.
deselectAll() Method
deselectAll() method is useful to remove selection from all selected
options of select box. It will works with multiple select box when you need
to remove all selections. Syntax for deselectAll() method is as bellow.

Select listbox = new


Select(driver.findElement(By.xpath("//select[@name='FromLB']")));
listbox.deselectAll();
isMultiple() Method
isMultiple() method is useful to verify if targeted select box is multiple
select box or not means we can select multiple options from that select
box or not. It will return boolean (true or false) value. We can use it with if
condition before working with select box. Syntax is as bellow.
Select listbox = new
Select(driver.findElement(By.xpath("//select[@name='FromLB']")));
boolean value = listbox.isMultiple();
System.out.print(value);
Bellow given example will show you use of isMultiple() and deselectAll()
methods very clearly in selenium webdriver.
@Test
public void test () throws InterruptedException
{
Select listbox = new
Select(driver.findElement(By.xpath("//select[@name='FromLB']")));
//To verify that specific select box supports multiple select or not.
if(listbox.isMultiple())
{
System.out.print("Multiple selections is supported");
listbox.selectByVisibleText("USA");
listbox.selectByValue("Russia");
listbox.selectByIndex(5);
Thread.sleep(3000);
//To deselect all selected options.
listbox.deselectAll();
Thread.sleep(2000);
}
else
{
System.out.print("Not supported multiple selections");
}
}
In above example, if condition will check that listbox is multiple select box
or not? Used listbox.deselectAll(); to remove all selected options.
]
How To Deselect Option By Visible Text Or Value Or By Index In Selenium
WebDriver With Example

Adding selection or removing selection from list box are very common
actions for list box. WebDriver has 3 alternate options to select or deselect
value from list box. It is very important to learn all three methods of
selecting or deselecting option from list box because if one is not possible
to implement in your test then you
must be aware about alternate option. I already described 3 selection
options in my earlier posts - Selecting specific option BY VISIBLE TEXT, BY
VALUE or BY INDEX from drop down or list box.
Now let me describe you all three deselect methods to deselect specific
option from list box. Do you remember that we can use "removeSelection"
command to deselect option from list box? VIEW THIS SELENIUM IDE
EXAMPLE for "removeSelection" command.
1. Deselect By Visible Text
If you wants to remove selection from list box then you can use
webdriver's deselectByVisibleText() method. Syntax is as bellow. 1st
syntax will locate the select box and 2nd syntax will remove selection by
visible text = Russia.
Select listbox = new
Select(driver.findElement(By.xpath("//select[@name='FromLB']")));
listbox.deselectByVisibleText("Russia");
2. Deselect By Value
You can also deselect option from list box by value. 2nd syntax will
deselect option by value = Mexico.
Select listbox = new
Select(driver.findElement(By.xpath("//select[@name='FromLB']")));
listbox.deselectByValue("Mexico");
3. Deselect By Index
Bellow given syntax will remove selection by index = 5.
Select listbox = new
Select(driver.findElement(By.xpath("//select[@name='FromLB']")));
listbox.deselectByIndex(5);
Execute bellow given example in eclipse and observe results during
execution.
Copy bellow given @Test method part of deselect option by visible text or
value or index and replace it with the @Test method part of example given
on THIS PAGE.(Note : @Test method is marked with pink color in that
linked page).

@Test

public void test () throws InterruptedException


{
driver.findElement(By.id("text1")).sendKeys("My First Name");
Select listbox = new
Select(driver.findElement(By.xpath("//select[@name='FromLB']")));
listbox.selectByVisibleText("USA");
listbox.selectByVisibleText("Russia");
Thread.sleep(1000);
//To deselect by visible text
listbox.deselectByVisibleText("Russia");
Thread.sleep(1000);
listbox.selectByValue("Japan");
listbox.selectByValue("Mexico");
Thread.sleep(1000);
//To deselect by value
listbox.deselectByValue("Mexico");
Thread.sleep(1000);
listbox.selectByIndex(4);
listbox.selectByIndex(5);
Thread.sleep(1000);
//To deselect by index
listbox.deselectByIndex(5);
Thread.sleep(1000);
driver.findElement(By.xpath("//input[@value='->']")).click();
Thread.sleep(1000);
}
}
How To Select Option By Value or By Index In Selenium WebDriver With
Example
In my earlier post, We have seen example of HOW TO SELECT OPTION BY
VISIBLE TEXT from drop down. There are two more alternatives to select
option value from drop down or list box in selenium webdriver. 1. Selecting
Option By Value and 2. Selecting Option By Index. You can use any one
from these
three to select value from list box of your software web application page.
If you know, we can use "select" command or "addSelection" command in
selenium IDE to select option from list box.

First of all let me show you difference between visible text, value and
index of list box option. Bellow given image will show you clear difference
between value, visible text and index.

1. Select Option By Value In WebDriver


Syntax for selecting option by value in webdriver is as bellow. First syntax
will locate the select element from page and 2nd syntax will select the
option from select box by value = Italy.
Select listbox = new
Select(driver.findElement(By.xpath("//select[@name='FromLB']")));
listbox.selectByValue("Italy");
2. Select Option By Index In WebDriver
Syntax for selection option by index from list box is as bellow. It will select
1st element(index = 0) from select box.
Select listbox = new
Select(driver.findElement(By.xpath("//select[@name='FromLB']")));
listbox.selectByIndex(0);
Execute bellow given example in your eclipse and verify result. Try to use
it in different applications.
Copy bellow given @Test method part of select option by value or
index and replace it with the @Test method part of example given on THIS
PAGE.(Note : @Test method is marked with pink color in that linked page).
@Test
public void test () throws InterruptedException

{
driver.findElement(By.id("text1")).sendKeys("My First Name");
//Selecting value from drop down by value
Select listbox = new
Select(driver.findElement(By.xpath("//select[@name='FromLB']")));
listbox.selectByValue("Italy");
listbox.selectByValue("Mexico");
listbox.selectByValue("Spain");
driver.findElement(By.xpath("//input[@value='->']")).click();
WebDriverWait wait = new WebDriverWait(driver, 15);
wait.until(ExpectedConditions.elementToBeClickable(By.id("text2")));
//Selecting value from drop down by index
listbox.selectByIndex(0);
listbox.selectByIndex(3);
driver.findElement(By.xpath("//input[@value='->']")).click();
Thread.sleep(2000);
}
Posted by P
Email ThisBlogThis!Share to TwitterShare to FacebookShare to Pinterest
Parameterization/Data Driven Testing Of Selenium Webdriver Test Using
Excel
Parameterization or data driven of your test is must required thing of any
automation testing tool. If you can not perform data driven testing in any
automation tool then it is biggest drawback of that tool. Till now, Selenium
webdriver has not any built in structure or method to parameterize your
test. If you know, we can
perform data driven testing using user extension in selenium IDE. You can
view practical example of selenium IDE parameterization test on THIS
ARTICLE POST. To parameterize selenium webdriver test, We need support
of Java Excel API. First of all, we need to configure eclipse. Configuration
steps are as bellow.
Another way of data driven testing In selenium webdriver Is using TestNG
@DataProvider Annotation. VIEW STEPS OF DATA DRIVEN TESTING USING
@DataProvider.
Step 1 : Download latest jxl.jar file
Current latest version of jexcelapi is 2_6_12. It may change in future so
download link can also change.

Click on THIS LINK to go to jexcelapi_2_6_12 page.

Click on jexcelapi_2_6_12.zip link as shown in bellow image. It will


start downloading zip folder.

On completion of zip folder download, extract that zip folder. You will
find jxl.jar file inside it.

Step 2 : Add jxl.jar in your project folder as a external jar.

Right click on your project folder in eclipse and go to Build Path ->
Configure Build path -> Libraries tab -> Click on Add External JARs
button and select jxl.jar.

For detailed description with image on how to add any external jar in your
project folder, You can follow step 2 of THIS POST .
Step 3 : Download data file
I have prepared example data file for parameterization. CLICK HERE to
download data file and save in your D: drive.
Step 4 : Import header files
All Bellow given header files are required for this example. Please include
them in your header file list if not included.
import java.io.FileInputStream;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;
import org.openqa.selenium.JavascriptExecutor;
Step 5 : Run bellow given example in your eclipse.
Bellow given example will read data from D:\\MyDataSheet.xls file and
then type that data in First Name and Last Name text box one by one.
Last Name text box will be disabled initially so I have used javascript
executor to enable it. You can view practical example with description for
the same on THIS LINK.

Copy bellow given @Test method part of data driven testing example and
replace it with the @Test method part of example given on THIS
PAGE. (Note : @Test method is marked with pink color in that linked page).
@Test
public void test () throws BiffException, IOException,
InterruptedException
{
//Open MyDataSheet.xls file from given location.
FileInputStream fileinput = new FileInputStream("D:\\MyDataSheet.xls");
//Access first data sheet. getSheet(0) describes first sheet.
Workbook wbk = Workbook.getWorkbook(fileinput);
Sheet sheet = wbk.getSheet(0);
//Read data from the first data sheet of xls file and store it in array.
String TestData[][] = new String[sheet.getRows()][sheet.getColumns()];
//To enable Last Name text box.
JavascriptExecutor javascript = (JavascriptExecutor) driver;
String toenable = "document.getElementsByName('lname')
[0].removeAttribute('disabled');";
javascript.executeScript(toenable);
//Type data in first name and last name text box from array.
for(int i=0;i<sheet.getRows();i++)
{
for (int j=0;j<sheet.getColumns();j++)
{
TestData[i][j] = sheet.getCell(j,i).getContents();
if(j%2==0)
{
driver.findElement(By.xpath("//input[@name='fname']")).sendKeys(TestDa
ta[i][j]);
}
else
{
driver.findElement(By.xpath("//input[@name='lname']")).sendKeys(TestDat
a[i][j]);
}
}
Thread.sleep(1000);
driver.findElement(By.xpath("//input[@name='fname']")).clear();
driver.findElement(By.xpath("//input[@name='lname']")).clear();
}
Thread.sleep(1000);

How To Enable/Disable Textbox In Selenium WebDriver On The Fly


We can know element's enabled/disabled status very easily
using isEnabled() method in selenium webdriver as described in THIS
EXAMPLE POST. Now supposing you have a scenario where you wants to
enable any disabled text box or disable any enabled text box then how to
do it? Webdriver do not have any built in
method by which you perform this action. But yes, Webdriver has
JavascriptExecutor interface by which we can execute any javascript
using executeScript() method.
I have posted many posts on how to execute javascript in selenium
webdriver to perform different actions. You can view all those example on
THIS LINK. Same way, we can enable or disable any element
using JavascriptExecutor interface during webdriver test case execution.
To disable text box, we will use html dom setAttribute() method and to
enable text box, we will use html dom removeAttribute() method
with executeScript() method. Javascript syntax for both of these is as
bellow.
document.getElementsByName('fname')[0].setAttribute('disabled', '');
document.getElementsByName('lname')[0].removeAttribute('disabled');
Now let we use both these javascripts practically to understand them
better. VIEW THIS POST to see how to enable or disable text box in
selenium IDE.
Copy bellow given @Test method part of enable or disable element and
replace it with the @Test method part of example given on THIS
PAGE. (Note : @Test method is marked with pink color in that linked page).
@Test
public void test () throws BiffException, IOException,
InterruptedException
{
boolean fbefore =
driver.findElement(By.xpath("//input[@name='fname']")).isEnabled();
System.out.print("\nBefore : First Name Text box enabled status is :
"+fbefore);
boolean lbefore =
driver.findElement(By.xpath("//input[@name='lname']")).isEnabled();
System.out.print("\nBefore : Last Name Text box enabled status is :
"+lbefore);

Thread.sleep(2000);
//To disable First Name text box
JavascriptExecutor javascript = (JavascriptExecutor) driver;
String todisable = "document.getElementsByName('fname')
[0].setAttribute('disabled', '');";
javascript.executeScript(todisable);
Thread.sleep(2000);
//To enable Last Name text box
String toenable = "document.getElementsByName('lname')
[0].removeAttribute('disabled');";
javascript.executeScript(toenable);
Thread.sleep(3000);
boolean fafter =
driver.findElement(By.xpath("//input[@name='fname']")).isEnabled();
System.out.print("\nAfter : First Name Text box enabled status is :
"+fafter);
boolean lafter =
driver.findElement(By.xpath("//input[@name='lname']")).isEnabled();
System.out.print("\nAfter : Last Name Text box enabled status is :
"+lafter);
}
How To Verify Element Is Enabled Or Disabled in Selenium WebDriver
During your Selenium WebDriver test case creation, frequently you need
to verify that your targeted element is enabled or disabled before
performing action on it. Webdriver has built in method isEnabled() to
check the element enable status. Verification of element is disable and
verification of element invisible is totally different.
Element is disabled means it is visible but not editable and element is
invisible means it is hidden. VIEW THIS EXAMPLE to know how to wait till
element is visible on the page.
isEnabled()
isEnabled() webdriver method will verify and return true if specified
element is enabled. Else it will return false. Generic syntax to store and
print element's status value is as bellow.
boolean fname =
driver.findElement(By.xpath("//input[@name='fname']")).isEnabled();
System.out.print(fname);
We can use isEnabled() method with if condition to take action based on
element's enabled status. Bellow given example will explain you deeply
about isEnabled() webdriver method. If you are selenium IDE user then

VIEW THIS POST to know how to wait for targeted element becomes
editable.
Copy bellow given @Test method part of check element enabled status
and replace it with the @Test method part of example given on THIS
PAGE. (Note : @Test method is marked with pink color in that linked page).
@Test
public void test () throws BiffException, IOException,
InterruptedException
{
boolean fname =
driver.findElement(By.xpath("//input[@name='fname']")).isEnabled();
System.out.print(fname);
WebElement firstname =
driver.findElement(By.xpath("//input[@name='fname']"));
WebElement lastname =
driver.findElement(By.xpath("//input[@name='lname']"));
//Verify First name text box is enabled or not and then print related
message.
if(firstname.isEnabled())
{
System.out.print("\nText box First name is enabled. Take your action.");
}
else
{
System.out.print("\nText box First name is disabled. Take your action.");
}
//Verify Last name text box is enabled or not and then print related
message.
if(lastname.isEnabled())
{
System.out.print("\nText box Last name is enabled. Take your action.");
}
else
{
System.out.print("\nText box Last name is disabled. Take your action.");
}
}
Above given example, will check the status of First name and Last name
text box and print message in console based on element is enabled or
disabled.
Example of Handling Multiple Browser Windows in Selenium WebDriver

Selenium WebDriver has built in "WebDriver.switchTo().window()" method


available to switch from one window to another window so it is very easy
to handle multiple windows in webdriver. If you remember, We can use
"selectWindow" window command in selenium IDE to select another
window.
If
window
do
not
have any title or both window has same title then it was very difficult to
select other window in selenium IDE. WebDriver has made it very easy.
You can handle multiple windows even if all the windows do not have any
title
or
contains
same
title.
WebDriver.getWindowHandles()
In WebDriver, We can use "WebDriver.getWindowHandles()" to get the
handles of all opened windows by webdriver and then we can use that
window handle to switch from from one window to another window.
Example Syntax for getting window handles is as bellow.
Set<String> AllWindowHandles = driver.getWindowHandles();
WebDriver.switchTo().window()
WebDriver.switchTo().window() method is useful to switch from one
window to another window of software web application. Example syntax is
as bellow.
driver.switchTo().window(window2);
Bellow given webdriver example of switching window will explain you it
deeply. Execute it in your eclipse and try to understand how webdriver do
it.
Copy bellow given @Test method part of handling multiple windows of
webdriver and replace it with the @Test method part of example given
on THIS PAGE.(Note : @Test method is marked with pink color in that
linked page).
@Test
public void test () throws InterruptedException
{
driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
driver.findElement(By.xpath("//b[contains(.,'Open New Page')]")).click();
// Get and store both window handles in array
Set<String> AllWindowHandles = driver.getWindowHandles();
String window1 = (String) AllWindowHandles.toArray()[0];
System.out.print("window1 handle code = "+AllWindowHandles.toArray()
[0]);
String window2 = (String) AllWindowHandles.toArray()[1];
System.out.print("\nwindow2 handle code =
"+AllWindowHandles.toArray()[1]);

//Switch to window2(child window) and performing actions on it.


driver.switchTo().window(window2);
driver.findElement(By.xpath("//input[@name='fname']")).sendKeys("My
Name");
driver.findElement(By.xpath("//input[@value='Bike']")).click();
driver.findElement(By.xpath("//input[@value='Car']")).click();
driver.findElement(By.xpath("//input[@value='Boat']")).click();
driver.findElement(By.xpath("//input[@value='male']")).click();
Thread.sleep(5000);
//Switch to window1(parent window) and performing actions on it.
driver.switchTo().window(window1);
driver.findElement(By.xpath("//option[@id='country6']")).click();
driver.findElement(By.xpath("//input[@value='female']")).click();
driver.findElement(By.xpath("//input[@value='Show Me Alert']")).click();
driver.switchTo().alert().accept();
Thread.sleep(5000);
//Once Again switch to window2(child window) and performing actions on
it.
driver.switchTo().window(window2);
driver.findElement(By.xpath("//input[@name='fname']")).clear();
driver.findElement(By.xpath("//input[@name='fname']")).sendKeys("Name
Changed");
Thread.sleep(5000);
driver.close();
//Once Again switch to window1(parent window) and performing actions
on it.
driver.switchTo().window(window1);
driver.findElement(By.xpath("//input[@value='male']")).click();
Thread.sleep(5000);
}
How To Get/Extract All Links From Web Page Using Selenium WebDriver
As we all knows, Each and every software web application contains many
number of different links/URLs. Some of them are redirecting to some
page of same website and others are redirecting to any external website.
One of my blog reader has requested the webdriver test script example
for printing all these links in
console. I have created and published many different WEBDRIVER
EXAMPLE SCRIPTS on this blog but requested example by blog reader is
not pushed till now so I have created example for the same to share with
all of you.

You can look at example of EXTRACTING TABLE DATA USING SELENIUM


WEBDRIVER.
We have seen HOW TO USE findElements in webdriver to locate multiple
elements of page. We can use same thing here to locate multiple links of
the page. Bellow given example will retrieve all URLs from the page and
will print all of them in console. You can click on each URL if you wish to do
so. Try bellow given example for different websites by providing that
website's URL in @Before annotation.
Copy bellow given @Test method part of extract all links from web
page and replace it with the @Test method part of example given on THIS
PAGE.(Note : @Test method is marked with pink color in that linked page).
@Test
public void test () throws InterruptedException
{
try {
List<WebElement> no = driver.findElements(By.tagName("a"));
int nooflinks = no.size();
System.out.println(nooflinks);
for (WebElement pagelink : no)
{
String linktext = pagelink.getText();
String link = pagelink.getAttribute("href");
System.out.println(linktext+" ->");
System.out.println(link);
}
}catch (Exception e){
System.out.println("error "+e);
}
}
THIS LINK will show you many other basic action command examples.
Selenium WebDriver Tutorials - Basic Action Commands And Operations
With Examples
I have already posted Selenium WebDrier Tutorials posts how to setup web
driver with eclipse and Run first test with webdriver, how to configure junit
with eclipse to generate webdriver test report. We have also learn
different methods of locating elements in webdriver. All these things are
very
basic
things and you need to learn all of them before starting your test case
creation in selenium 2. Now we are ready to learn next step of performing
basic actions in web driver with java for your software web application.

VIEW STEP BY STEP TUTORIALS ON SELENIUM WEBDRIVER


Today I wants to describe you few basic webdriver commands to perform
actions on web element of your web page. We can perform too many
command operations in webdriver and will look about them one by one in
near future. Right now I am describing you few of them for your kind
information.
1. Creating New Instance Of Firefox Driver
WebDriver driver = new FirefoxDriver();
Above given syntax will create new instance of Firefox driver. VIEW
PRACTICAL EXAMPLE
2. Command To Open URL In Browser
driver.get("http://only-testing-blog.blogspot.in/2013/11/new-test.html");
This syntax will open specified URL in web browser. VIEW PRACTICAL
EXAMPLE OF OPEN URL
3. Clicking on any element or button of webpage
driver.findElement(By.id("submitButton")).click();
Above given syntax will click on targeted element in webdriver. VIEW
PRACTICAL EXAMPLE OF CLICK ON ELEMENT

4. Store text of targeted element in variable


String dropdown = driver.findElement(By.tagName("select")).getText();
This syntax will retrieve text from targeted element and will store it in
variable = dropdown. VIEW PRACTICAL EXAMPLE OF Get Text
5. Typing text in text box or text area.
driver.findElement(By.name("fname")).sendKeys("My First Name");
Above syntax will type specified text in targeted element. VIEW
PRACTICAL EXAMPLE OF SendKeys
6. Applying Implicit wait in webdriver
driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
This syntax will force webdriver to wait for 15 second if element not found
on page. VIEW PRACTICAL EXAMPLE OF IMPLICIT WAIT
7. Applying Explicit wait in webdriver with WebDriver canned conditions.
WebDriverWait wait = new WebDriverWait(driver, 15);
wait.until(ExpectedConditions.textToBePresentInElementLocated(By.xpath(
"//div[@id='timeLeft']"), "Time left: 7 seconds"));
Above 2 syntax will wait for till 15 seconds for expected text "Time left: 7
seconds" to be appear on targeted element. VIWE DIFFERENT PRACTICAL
EXAMPLES OF EXPLICIT WAIT
8. Get page title in selenium webdriver
driver.getTitle();
It will retrieve page title and you can store it in variable to use in next
steps. VIEW PRACTICAL EXAMPLE OF GET TITLE
9. Get Current Page URL In Selenium WebDriver
driver.getCurrentUrl();
It will retrieve current page URL and you can use it to compare with your
expected URL. VIEW PRACTICAL EXAMPLE OF GET CURRENT URL
10. Get domain name using java script executor
JavascriptExecutor javascript = (JavascriptExecutor) driver;
String CurrentURLUsingJS=(String)javascript.executeScript("return
document.domain");
Above syntax will retrieve your software application's domain name using
webdriver's java script executor interface and store it in to variable.
VIEW GET DOMAIN NAME PRACTICAL EXAMPLE.

11. Generate alert using webdriver's java script executor interface


JavascriptExecutor javascript = (JavascriptExecutor) driver;
javascript.executeScript("alert('Test Case Execution Is started Now..');");
It will generate alert during your selenium webdriver test case execution.
VIEW PRACTICAL EXAMPLE OF GENERATE ALERT USING SELENIUM
WEBDRIVER.
12. Selecting or Deselecting value from drop down in selenium webdriver.

Select By Visible Text

Select mydrpdwn = new Select(driver.findElement(By.id("Carlist")));


mydrpdwn.selectByVisibleText("Audi");
It will select value from drop down list using visible text value = "Audi".

Select By Value

Select listbox = new


Select(driver.findElement(By.xpath("//select[@name='FromLB']")));
listbox.selectByValue("Italy");
It will select value by value = "Italy".

Select By Index

Select listbox = new


Select(driver.findElement(By.xpath("//select[@name='FromLB']")));
listbox.selectByIndex(0);
It will select value by index= 0(First option).
VIEW PRACTICAL EXAMPLES OF SELECTING VALUE FROM DROP DOWN
LIST.

Deselect by Visible Text

Select listbox = new


Select(driver.findElement(By.xpath("//select[@name='FromLB']")));
listbox.deselectByVisibleText("Russia");
It will deselect option by visible text = Russia from list box.

Deselect by Value

Select listbox = new


Select(driver.findElement(By.xpath("//select[@name='FromLB']")));
listbox.deselectByValue("Mexico");
It will deselect option by value = Mexico from list box.

Deselect by Index

Select listbox = new


Select(driver.findElement(By.xpath("//select[@name='FromLB']")));
listbox.deselectByIndex(5);
It will deselect option by Index = 5 from list box.

Deselect All

Select listbox = new


Select(driver.findElement(By.xpath("//select[@name='FromLB']")));
listbox.deselectAll();
It will remove all selections from list box.
VIEW PRACTICAL EXAMPLES OF DESELECT SPECIFIC OPTION FROM LIST
BOX

isMultiple()

Select listbox = new


Select(driver.findElement(By.xpath("//select[@name='FromLB']")));
boolean value = listbox.isMultiple();
It will return true if select box is multiselect else it will return false.VIEW
PRACTICAL EXAMPLE OF isMultiple()
13. Navigate to URL or Back or Forward in Selenium Webdriver
driver.navigate().to("http://only-testingblog.blogspot.in/2014/01/textbox.html");
driver.navigate().back();
driver.navigate().forward();
1st command will navigate to specific URL, 2nd will navigate one step
back and 3rd command will navigate one step forward. VIEW PRACTICAL
EXAMPLES OF NAVIGATION COMMANDS.
14. Verify Element Present in Selenium WebDriver
Boolean iselementpresent =
driver.findElements(By.xpath("//input[@id='text2']")).size()!= 0;
It will return true if element is present on page, else it will return false in
variable iselementpresent. VIEW PRACTICAL EXAMPLE OF VERIFY ELEMENT
PRESENT.
15. Capturing entire page screenshot in Selenium WebDriver
File screenshot =
((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(screenshot, new File("D:\\screenshot.jpg"));
It will capture page screenshot and store it in your D: drive. VIEW
PRACTICAL EXAMPLE ON THIS PAGE.

16. Generating Mouse Hover Event In WebDriver


Actions actions = new Actions(driver);
WebElement moveonmenu =
driver.findElement(By.xpath("//div[@id='menu1']/div"));
actions.moveToElement(moveonmenu);
actions.perform();
Above example will move mouse on targeted element. VIEW PRACTICAL
EXAMPLE OF MOUSE HOVER.
17. Handling Multiple Windows In Selenium WebDriver.
1. Get All Window Handles.
Set<String> AllWindowHandles = driver.getWindowHandles();
2. Extract parent and child window handle from all window handles.
String window1 = (String) AllWindowHandles.toArray()[0];
String window2 = (String) AllWindowHandles.toArray()[1];
3. Use window handle to switch from one window to other window.
driver.switchTo().window(window2);
Above given steps with helps you to get window handle and then how to
switch from one window to another window. VIEW PRACTICAL EXAMPLE OF
HANDLING MULTIPLE WINDOWS IN WEBDRIVER
18. Check Whether Element is Enabled Or Disabled In Selenium Web
driver.
boolean fname =
driver.findElement(By.xpath("//input[@name='fname']")).isEnabled();
System.out.print(fname);
Above syntax will verify that element (text box) fname is enabled or not.
You can use it for any input element. VIEW PRACTICAL EXAMPLE OF VERIFY
ELEMENT IS ENABLED OR NOT.
19. Enable/Disable Textbox During Selenium Webdriver Test Case
Execution.
JavascriptExecutor javascript = (JavascriptExecutor) driver;
String todisable = "document.getElementsByName('fname')
[0].setAttribute('disabled', '');";
javascript.executeScript(todisable);
String toenable = "document.getElementsByName('lname')
[0].removeAttribute('disabled');";
javascript.executeScript(toenable);

It will disable fname element using setAttribute() method and enable


lname element using removeAttribute() method. VIEW PRACTICAL
EXAMPLE OF ENABLE/DISABLE TEXTBOX.
20. Selenium WebDriver Assertions With TestNG Framework

assertEquals

Assert.assertEquals(actual, expected);
assertEquals assertion helps you to assert actual and expected equal
values. VIEW PRACTICAL EXAMPLE OF assertEquals ASSERTION

assertNotEquals

Assert.assertNotEquals(actual, expected);
assertNotEquals assertion is useful to assert not equal values. VIEW
PRACTICAL EXAMPLE OF assertNotEquals ASSERTION.

assertTrue

Assert.assertTrue(condition);
assertTrue assertion works for boolean value true assertion. VIEW
PRACTICAL EXAMPLE OF assertTrue ASSERTION.

assertFalse

Assert.assertFalse(condition);
assertFalse assertion works for boolean value false assertion. VIEW
PRACTICAL EXAMPLE OF assertFalse ASSERTION.
21. Submit() method to submit form
driver.findElement(By.xpath("//input[@name='Company']")).submit();
It will submit the form. VIEW PRACTICAL EXAMPLE OF SUBMIT FORM.
22. Handling Alert, Confirmation and Prompts Popups
String myalert = driver.switchTo().alert().getText();
To store alert text. VIEW PRACTICAL EXAMPLE OF STORE ALERT TEXT
driver.switchTo().alert().accept();
To accept alert. VIEW PRACTICAL EXAMPLE OF ALERT ACCEPT
driver.switchTo().alert().dismiss();
To dismiss confirmation. VIEW PRACTICAL EXAMPLE OF CANCEL
CONFIRMATION

driver.switchTo().alert().sendKeys("This Is John");
* Navigating Back And Forward
Selenium WebDriver : How To Navigate URL, Forward and Backward With
Example
In my earlier posts, we have learnt few BASIC ACTION COMMANDS of
selenium WebDriver with examples. You will have to use them on daily
basis for you software web application's webdriver test case preparation.
It is very important for you to use them on right time and right place. Now
let we learn 3 more
action commands of webdriver.
1. driver.navigate().to
If you wants to navigate on specific page or URL in between your test then
you can use driver.navigate().to command as bellow.
driver.navigate().to("http://only-testingblog.blogspot.in/2014/01/textbox.html");
2. driver.navigate().back();
This command is useful to go back on previous page. Same as we are
clicking browser back button. You can use this command as bellow. In
Selenium IDE, we can use "goBack" to perform same action.
driver.navigate().back();
3. driver.navigate().forward();
Same as we are clicking on forward button of browser.
Bellow given example will cover all three commands. Execute it in your
eclipse to know them practically.
Copy bellow given @Test method part of driver.navigate() command
examples and replace it with the @Test method part of example given
on THIS PAGE. (Note : @Test method is marked with pink color in that
linked page).
@Test
public void test () throws InterruptedException
{
driver.navigate().to("http://only-testingblog.blogspot.in/2014/01/textbox.html");
//To navigate back (Same as clicking on browser back button)
driver.navigate().back();
//To navigate forward (Same as clicking on browser forward button)
driver.navigate().forward();

}
* Verify Element Present
Selenium WebDriver : Verify Element Present In Selenium WebDriver
Some times you need to verify the presence of element before taking
some action on software web application page. As you know, Selenium IDE
has many built in commands to perform different types of actions on your
software web application page. You can verify presence of element by
using
"verifyElementPresent" command in selenium IDE. Also you can view
example of selenium IDE "verifyElementNotPresent" command. Web
driver have not any built in method or interface by which we can verify
presence of element on the page.
Yes we can do it very easily in WebDriver too using bellow given syntax.
Boolean
iselementpresent
=
driver.findElements(By.xpath("//input[@id='text2']")).size()!= 0;
We have to use findElements() method for this purpose. Above syntax will
return true if element is present on page. Else it will return false. You can
put if condition to take action based on presence of element.
Bellow given example will check the presence of different text box on
page. It will print message in console based on presence of element.
Copy bellow given @Test method part of iselementpresent example and
replace it with the @Test method part of example given on THIS
PAGE. (Note : @Test method is marked with pink color in that linked page).
@Test
public void test () throws InterruptedException
{
for (int i=1; i<6; i++)
{
//To verify element is present on page or not.
String XPath = "//input[@id='text"+i+"']";
Boolean iselementpresent = driver.findElements(By.xpath(XPath)).size()!
= 0;
if (iselementpresent == true)
{
System.out.print("\nTargeted TextBox"+i+" Is Present On The Page");
}
else
{
System.out.print("\nTargeted Text Box"+i+" Is Not Present On The
Page");

}
}
}
* Capturing Entire Page Screenshot
Selenium Webdriver Tutorial To Capture Screenshot With Example
Capturing screenshot of software web application page is very easy in
selenium webdriver. As we knows, It is very basic required thing in
automation tools to capture screenshot on test case failure or whenever
required during test case execution. VIEW MORE SELENIUM WEBDRIVER
BASIC COMMANDS for your webdriver knowledge improvement and use
them in your software web application test case creation.

If you remember, We can use "captureEntirePageScreenshot" command in


selenium IDE to capture the screenshot on software web application
current page. In Selenium WebDriver/Selenium 2, we need to capture
screenshot of web page using bellow syntax.
File screenshot =
((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
Then we have to store it in our local drive using bellow given syntax. You
can change/provide your own file destination path and name.
FileUtils.copyFile(screenshot, new File("D:\\screenshot.jpg"));
Now we need to import bellow given header files to get support of capture
screenshot in webdriver.
import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
Copy bellow given @Test method part of Capture screen shot webdriver
example and replace it with the @Test method part of example given
on THIS PAGE. Don't forget to import above given header files in your
eclipse test.(Note : @Test method is marked with pink color in that linked
page).
@Test
public void test () throws InterruptedException, IOException
{
//Capture entire page screenshot and then store it to destination drive
File screenshot =
((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(screenshot, new File("D:\\screenshot.jpg"));

System.out.print("Screenshot is captured and stored in your D: Drive");


}
You can put above syntax under catch block of try to capture screenshot
on failure.
* Generating Mouse Hover Event

Selenium WebDriver : Generating Mouse Hover Event On Main Menu To


Click On Sub Menu
Selenium WebDriver is totally freeware testing tool and we can use it for
software web application regression purpose. Hovering mouse on main
menu or any other element of web page or simulating mouse movement
in webdriver is not very tough task. As you know, We can perform most of
actions
and
operations directly in webdriver and you can VIEW FEW OF THEM ON THIS
PAGE. But there are also some actions which we can not perform directly
in webdriver and to perform them, we need to use some tricky
ways. Generating mouse hover event is one of them.
To generate mouse hover event in webdriver, We can use advanced user
interactions API constructor "Actions" with "moveToElement" method.
Bunch of syntax to hover mouse on main menu is as bellow. You can
replace xpath of an element as per your requirement in bellow given
syntax.
Actions actions = new Actions(driver);
WebElement moveonmenu =
driver.findElement(By.xpath("//div[@id='menu1']/div"));
actions.moveToElement(moveonmenu);
actions.perform();
Above example will only move mouse on targeted element. It will not
perform click operation. To perform click operation on sub menu, we need
to use click() action before perform() as shown in bellow example.
package junitreportpackage;

import java.io.IOException;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import
import
import
import
import
import
import

org.openqa.selenium.By;
org.openqa.selenium.WebDriver;
org.openqa.selenium.WebElement;
org.openqa.selenium.firefox.FirefoxDriver;
org.openqa.selenium.interactions.Actions;
org.openqa.selenium.support.ui.ExpectedConditions;
org.openqa.selenium.support.ui.WebDriverWait;

public class Mytesting {


WebDriver driver = new FirefoxDriver();
@Before
public void beforetest() {
driver.manage().window().maximize();
driver.get("http://only-testing-blog.blogspot.in/p/mouse-hover.html");
}
@After
public void aftertest() {
driver.quit();
}
@Test
public void test () throws InterruptedException, IOException
{
//Generate mouse hover event on main menu to click on sub menu
Actions actions = new Actions(driver);
WebElement moveonmenu =
driver.findElement(By.xpath("//div[@id='menu1']/div"));
actions.moveToElement(moveonmenu).moveToElement(driver.findElement
(By.xpath("//div[@id='menu1choices']/a"))).click().perform();
WebDriverWait wait = new WebDriverWait(driver, 15);
wait.until(ExpectedConditions.titleContains("Google"));
}
}
* Handling Multiple Windows
Example of Handling Multiple Browser Windows in Selenium WebDriver
Selenium WebDriver has built in "WebDriver.switchTo().window()" method
available to switch from one window to another window so it is very easy
to handle multiple windows in webdriver. If you remember, We can use
"selectWindow" window command in selenium IDE to select another
window.
If
window
do
not
have any title or both window has same title then it was very difficult to

select other window in selenium IDE. WebDriver has made it very easy.
You can handle multiple windows even if all the windows do not have any
title
or
contains
same
title.
WebDriver.getWindowHandles()
In WebDriver, We can use "WebDriver.getWindowHandles()" to get the
handles of all opened windows by webdriver and then we can use that
window handle to switch from from one window to another window.
Example Syntax for getting window handles is as bellow.
Set<String> AllWindowHandles = driver.getWindowHandles();
WebDriver.switchTo().window()
WebDriver.switchTo().window() method is useful to switch from one
window to another window of software web application. Example syntax is
as bellow.
driver.switchTo().window(window2);
Bellow given webdriver example of switching window will explain you it
deeply. Execute it in your eclipse and try to understand how webdriver do
it.
Copy bellow given @Test method part of handling multiple windows of
webdriver and replace it with the @Test method part of example given
on THIS PAGE.(Note : @Test method is marked with pink color in that
linked page).
@Test
public void test () throws InterruptedException
{
driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
driver.findElement(By.xpath("//b[contains(.,'Open New Page')]")).click();
// Get and store both window handles in array
Set<String> AllWindowHandles = driver.getWindowHandles();
String window1 = (String) AllWindowHandles.toArray()[0];
System.out.print("window1 handle code = "+AllWindowHandles.toArray()
[0]);
String window2 = (String) AllWindowHandles.toArray()[1];
System.out.print("\nwindow2 handle code =
"+AllWindowHandles.toArray()[1]);
//Switch to window2(child window) and performing actions on it.
driver.switchTo().window(window2);
driver.findElement(By.xpath("//input[@name='fname']")).sendKeys("My
Name");
driver.findElement(By.xpath("//input[@value='Bike']")).click();
driver.findElement(By.xpath("//input[@value='Car']")).click();

driver.findElement(By.xpath("//input[@value='Boat']")).click();
driver.findElement(By.xpath("//input[@value='male']")).click();
Thread.sleep(5000);
//Switch to window1(parent window) and performing actions on it.
driver.switchTo().window(window1);
driver.findElement(By.xpath("//option[@id='country6']")).click();
driver.findElement(By.xpath("//input[@value='female']")).click();
driver.findElement(By.xpath("//input[@value='Show Me Alert']")).click();
driver.switchTo().alert().accept();
Thread.sleep(5000);
//Once Again switch to window2(child window) and performing actions on
it.
driver.switchTo().window(window2);
driver.findElement(By.xpath("//input[@name='fname']")).clear();
driver.findElement(By.xpath("//input[@name='fname']")).sendKeys("Name
Changed");
Thread.sleep(5000);
driver.close();
//Once Again switch to window1(parent window) and performing actions
on it.
driver.switchTo().window(window1);
driver.findElement(By.xpath("//input[@value='male']")).click();
Thread.sleep(5000);
}
* Verify Element Is Enabled Or Not

How To Verify Element Is Enabled Or Disabled in Selenium WebDriver


During your Selenium WebDriver test case creation, frequently you need
to verify that your targeted element is enabled or disabled before
performing action on it. Webdriver has built in method isEnabled() to
check the element enable status. Verification of element is disable and
verification of element invisible is totally different.
Element is disabled means it is visible but not editable and element is
invisible means it is hidden. VIEW THIS EXAMPLE to know how to wait till
element is visible on the page.
isEnabled()
isEnabled() webdriver method will verify and return true if specified
element is enabled. Else it will return false. Generic syntax to store and
print element's status value is as bellow.

boolean fname =
driver.findElement(By.xpath("//input[@name='fname']")).isEnabled();
System.out.print(fname);
We can use isEnabled() method with if condition to take action based on
element's enabled status. Bellow given example will explain you deeply
about isEnabled() webdriver method. If you are selenium IDE user then
VIEW THIS POST to know how to wait for targeted element becomes
editable.
Copy bellow given @Test method part of check element enabled status
and replace it with the @Test method part of example given on THIS
PAGE. (Note : @Test method is marked with pink color in that linked page).
@Test
public void test () throws BiffException, IOException,
InterruptedException
{
boolean fname =
driver.findElement(By.xpath("//input[@name='fname']")).isEnabled();
System.out.print(fname);
WebElement firstname =
driver.findElement(By.xpath("//input[@name='fname']"));
WebElement lastname =
driver.findElement(By.xpath("//input[@name='lname']"));
//Verify First name text box is enabled or not and then print related
message.
if(firstname.isEnabled())
{
System.out.print("\nText box First name is enabled. Take your action.");
}
else
{
System.out.print("\nText box First name is disabled. Take your action.");
}
//Verify Last name text box is enabled or not and then print related
message.
if(lastname.isEnabled())
{
System.out.print("\nText box Last name is enabled. Take your action.");
}
else
{
System.out.print("\nText box Last name is disabled. Take your action.");
}
}

Above given example, will check the status of First name and Last name
text box and print message in console based on element is enabled or
disabled.
* Enable/Disable Element
How To Enable/Disable Textbox In Selenium WebDriver On The Fly
We can know element's enabled/disabled status very easily
using isEnabled() method in selenium webdriver as described in THIS
EXAMPLE POST. Now supposing you have a scenario where you wants to
enable any disabled text box or disable any enabled text box then how to
do it? Webdriver do not have any built in
method by which you perform this action. But yes, Webdriver has
JavascriptExecutor interface by which we can execute any javascript
using executeScript() method.
I have posted many posts on how to execute javascript in selenium
webdriver to perform different actions. You can view all those example on
THIS LINK. Same way, we can enable or disable any element
using JavascriptExecutor interface during webdriver test case execution.
To disable text box, we will use html dom setAttribute() method and to
enable text box, we will use html dom removeAttribute() method
with executeScript() method. Javascript syntax for both of these is as
bellow.
document.getElementsByName('fname')[0].setAttribute('disabled', '');
document.getElementsByName('lname')[0].removeAttribute('disabled');
Now let we use both these javascripts practically to understand them
better. VIEW THIS POST to see how to enable or disable text box in
selenium IDE.
Copy bellow given @Test method part of enable or disable element and
replace it with the @Test method part of example given on THIS
PAGE. (Note : @Test method is marked with pink color in that linked page).
@Test
public void test () throws BiffException, IOException,
InterruptedException
{
boolean fbefore =
driver.findElement(By.xpath("//input[@name='fname']")).isEnabled();
System.out.print("\nBefore : First Name Text box enabled status is :
"+fbefore);
boolean lbefore =
driver.findElement(By.xpath("//input[@name='lname']")).isEnabled();
System.out.print("\nBefore : Last Name Text box enabled status is :
"+lbefore);

Thread.sleep(2000);
//To disable First Name text box
JavascriptExecutor javascript = (JavascriptExecutor) driver;
String todisable = "document.getElementsByName('fname')
[0].setAttribute('disabled', '');";
javascript.executeScript(todisable);
Thread.sleep(2000);
//To enable Last Name text box
String toenable = "document.getElementsByName('lname')
[0].removeAttribute('disabled');";
javascript.executeScript(toenable);
Thread.sleep(3000);
boolean fafter =
driver.findElement(By.xpath("//input[@name='fname']")).isEnabled();
System.out.print("\nAfter : First Name Text box enabled status is :
"+fafter);
boolean lafter =
driver.findElement(By.xpath("//input[@name='lname']")).isEnabled();
System.out.print("\nAfter : Last Name Text box enabled status is :
"+lafter);
}
* Handling Alert, Confirmation and Prompt popup
Selenium WebDriver : Handling Javascript Alerts, Confirmations And
Prompts
Alerts, Confirmation and Prompts are very commonly used elements of
any webpage and you must know how to handle all these popups In
selenium webdriver. If you know, Selenium IDE has many commands to
handle
alerts,
confirmations
and
prompt
popups
like
assertAlert, assertConfirmation, storeAlert,
verifyAlertPresent, etc.. First of all, Let me show you all three different
popup types to remove confusion from your mind and then we will see
how to handle them In selenium webdriver.
Alert Popup
Generally alert message popup display with alert text and Ok button as
shown In bellow given Image.

Confirmation Popup
Confirmation popup displays with confirmation text, Ok and Cancel button
as shown In bellow given Image.

Prompt Popup
Prompts will have prompt text, Input text box, Ok and Cancel buttons.

Selenium webdriver has Its own Alert Interface to handle all above
different popups. Alert Interface has different methods like accept(),
dismiss(), getText(), sendKeys(java.lang.String keysToSend) and we can
use all these methods to perform different actions on popups.
VIEW WEBDRIVER EXAMPLES STEP BY STEP
Look at the bellow given simple example of handling alerts, confirmations
and prompts In selenium webdriver. Bellow given example will perform
different actions (Like click on Ok button, Click on cancel button, retrieve

alert text, type text In prompt text box etc..)on all three kind of popups
using different methods od Alert Interface.
Run bellow given example In eclipse with testng and observe the result.
package Testng_Pack;
import java.util.concurrent.TimeUnit;
import
import
import
import
import
import
import

org.openqa.selenium.Alert;
org.openqa.selenium.By;
org.openqa.selenium.WebDriver;
org.openqa.selenium.firefox.FirefoxDriver;
org.testng.annotations.AfterTest;
org.testng.annotations.BeforeTest;
org.testng.annotations.Test;

public class unexpected_alert {


WebDriver driver;
@BeforeTest
public void setup() throws Exception {
driver =new FirefoxDriver();
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
driver.get("http://only-testing-blog.blogspot.in/2014/01/textbox.html");
}
@AfterTest
public void tearDown() throws Exception {
driver.quit();
}
@Test
public void Text() throws InterruptedException {
//Alert Pop up Handling.
driver.findElement(By.xpath("//input[@value='Show Me Alert']")).click();
//To locate alert.
Alert A1 = driver.switchTo().alert();
//To read the text from alert popup.
String Alert1 = A1.getText();
System.out.println(Alert1);
Thread.sleep(2000);
//To accept/Click Ok on alert popup.
A1.accept();
//Confirmation Pop up Handling.
driver.findElement(By.xpath("//button[@onclick='myFunction()']")).click();
Alert A2 = driver.switchTo().alert();

String Alert2 = A2.getText();


System.out.println(Alert2);
Thread.sleep(2000);
//To click On cancel button of confirmation box.
A2.dismiss();
//Prompt Pop up Handling.
driver.findElement(By.xpath("//button[contains(.,'Show Me
Prompt')]")).click();
Alert A3 = driver.switchTo().alert();
String Alert3 = A3.getText();
System.out.println(Alert3);
//To type text In text box of prompt pop up.
A3.sendKeys("This Is John");
Thread.sleep(2000);
A3.accept();
}
}
This way you can handle different kind of alerts very easily using Alert
Interface of selenium webdriver. NEXT POST will show you how to handle
unexpected alerts In selenium webdriver.
* Handle Unexpected Alert
How To Handle Unexpected Alerts In Selenium WebDriver
Some times when we browsing software web application, Display some
unexpected alerts due to some error or some other reasons. This kind of
alerts not display every time but they are displaying only some time. If
you have created webdriver test case for such page and not handled this
kind of alerts In your code then
your script will fail Immediately If such unexpected alert pop up displayed.
We have already learnt, How to handle expected alert popups In selenium
webdriver In THIS EXAMPLE. Now unexpected alert appears only some
times so we can not write direct code to accept or dismiss that alert. In
this kind of situation, we have to handle them specially.
You can VIEW ALL WEBDRIVER TUTORIALS ONE BY ONE.
To handle this kind of unexpected alerts, You must at least aware about on
which action such unexpected alert Is generated. Sometimes, They are
generated during page load and sometime they are generated when you
perform some action. So first of all we have to note down the action where
such unexpected alert Is generated and then we can check for alert after
performing that action. We need to use try catch block for checking such
unexpected alters because If we will use direct code(without try catch) to
accept or dismiss alert and If alert not appears then our test case will fail.
try catch can handle both situations.

I have one example where alert Is displaying when loading page. So we


can check for alert Inside try catch block after page load as shown In
bellow given example. After loading page, It will check for alert. If alert Is
there on the page then It will dismiss It else It will go to catch block and
print message as shown In bellow given example.
Run bellow given example In eclipse with testng and observe the result.
package Testng_Pack;
import java.util.concurrent.TimeUnit;
import
import
import
import
import
import

org.openqa.selenium.By;
org.openqa.selenium.WebDriver;
org.openqa.selenium.firefox.FirefoxDriver;
org.testng.annotations.AfterTest;
org.testng.annotations.BeforeTest;
org.testng.annotations.Test;

public class unexpected_alert {


WebDriver driver;
@BeforeTest
public void setup() throws Exception {
driver =new FirefoxDriver();
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
driver.get("http://only-testing-blog.blogspot.in/2014/06/alert_6.html");
}
@AfterTest
public void tearDown() throws Exception {
driver.quit();
}
@Test
public void Text() throws InterruptedException {
//To handle unexpected alert on page load.
try{
driver.switchTo().alert().dismiss();
}catch(Exception e){
System.out.println("unexpected alert not present");
}
driver.findElement(By.xpath("//input[@name='fname']")).sendKeys("fname
");

driver.findElement(By.xpath("//input[@name='lname']")).sendKeys("lname
");
driver.findElement(By.xpath("//input[@type='submit']")).click();
}
}
Above given webdriver code Is just for example. It Is just explaining the
way of using try catch block to handle unexpected alert. You can use such
try catch block In that area where you are facing unexpected alerts very
frequently.
Day 6 - WebDriver Wait For Examples Using JUnit And Eclipse
10. How to apply implicit wait in selenium WebDriver script
How to use implicit wait in selenium webdriver and why
There are 2 types of waits available in Webdriver/Selenium 2. One of them
is implicit wait and another one is explicit wait. Both (Implicit wait and
explicit wait) are useful for waiting in WebDriver. Using waits, we are
telling WebDriver to wait for a certain amount of time before going to next
step. We will see about explicit
wait in my upcoming posts. In this post let me tell you why and how to use
implicit wait in webdriver.
Why Need Implicit Wait In WebDriver
As you knows sometimes, some elements takes some time to appear on
page when browser is loading the page. In this case, sometime your
webdriver test will fail if you have not applied Implicit wait in your test
case. If implicit wait is applied in your test case then webdriver will wait
for specified amount of time if targeted element not appears on page. As
you know, we can Set default timeout or use "setTimeout" command in
selenium IDE which is same as implicit wait in webdriver.
If you write implicit wait statement in you webdriver script then it will be
applied automatically to all elements of your test case. I am suggesting
you to use Implicit wait in your all test script of software web application
with 10 to 15 seconds. In webdriver, Implicit wait statement is as bellow.
How To Write Implicit Wait In WebDriver
driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
Above statement will tell webdriver to wait for 15 seconds if targeted
element not found/not appears on page. Le we look at simple exemple to
understand implicit wait better.

Copy bellow given @Test method part and replace it with the @Test
method part of example given on this page. (Note : @Test method is
marked with pink color in that example).
@Test
public void test ()
{
driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
driver.findElement(By.xpath("//input[@name='fname']")).sendKeys("My
Name");
driver.findElement(By.xpath("//input[@name='namexyz']"));
}
In Above webdriver test case with JUnit example, 1st Element
'xpath("//input[@name='fname']")' will be found on page but element
xpath("//input[@name='namexyz']") is not there on page. So in this case
webdriver will wait for 15 to locate that element on page because we have
written implicit wait statement in our code. At last webdriver test will fail
because xpath("//input[@name='namexyz']") is not on the page.
11.WebDriverExamples
How to wait for element to be clickable in selenium webdriver using
explicit wait
In my previous post, We have seen how to wait implicitly in selenium
webdriver. Let me remind you one thing is implicit wait will be applied to
all elements of test case by default while explicit will be applied to
targeted element only. This is the difference between implicit wait and
explicit wait. Still i am suggesting
you to use implicit wait in your test script.
If you knows, In selenium IDE we can use "waitForElementPresent" or
"verifyElementPresent" to wait for or verify that element is present or not
on page. In selenium webdriver, we can do same thing using explicit wait
of elementToBeClickable(By locator). Full syntax is as bellow.
WebDriverWait wait = new WebDriverWait(driver, 15);
wait.until(ExpectedConditions.elementToBeClickable(By.cssSelector("#sub
mitButton")));
Here above syntax will wait till 15 seconds to become targeted
element(#submitButton) clickable if it is not clickable or not loaded on the
page of software web application. As soon as targeted element becomes
clickable, webdriver will go for perform next action. You can increase or
decrease webdriver wait time from 15.
Let me give you practical example for the element to be clickable.

package junitreportpackage;
import
import
import
import
import
import
import
import
import
import
import
import
import
import
import
import
import

java.util.concurrent.TimeUnit;
java.io.FileInputStream;
java.io.IOException;
jxl.Sheet;
jxl.Workbook;
jxl.read.biff.BiffException;
org.junit.After;
org.junit.Before;
org.junit.Test;
org.openqa.selenium.By;
org.openqa.selenium.JavascriptExecutor;
org.openqa.selenium.WebDriver;
org.openqa.selenium.WebElement;
org.openqa.selenium.firefox.FirefoxDriver;
org.openqa.selenium.support.ui.ExpectedConditions;
org.openqa.selenium.support.ui.Select;
org.openqa.selenium.support.ui.WebDriverWait;

public class Mytest1 {


WebDriver driver = new FirefoxDriver();
@Before
public void beforetest() {
driver.manage().window().maximize();
driver.get("http://only-testing-blog.blogspot.in/2013/11/new-test.html");
driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
}
@After
public void aftertest() {
driver.quit();
}
@Test
public void test ()
{
driver.findElement(By.xpath("//input[@name='fname']")).sendKeys("My
Name");
//Wait for element to be clickable
WebDriverWait wait = new WebDriverWait(driver, 15);
wait.until(ExpectedConditions.elementToBeClickable(By.cssSelector("#sub
mitButton")));
driver.findElement(By.cssSelector("#submitButton")).click();

}
public void HighlightMyElement(WebElement element) {
for (int i = 0; i < 10; i++)
{
JavascriptExecutor javascript = (JavascriptExecutor) driver;
javascript.executeScript("arguments[0].setAttribute('style',
arguments[1]);", element, "color: orange; border: 4px solid orange;");
javascript.executeScript("arguments[0].setAttribute('style',
arguments[1]);", element, "color: pink; border: 4px solid pink;");
javascript.executeScript("arguments[0].setAttribute('style',
arguments[1]);", element, "color: yellow; border: 4px solid yellow;");
javascript.executeScript("arguments[0].setAttribute('style',
arguments[1]);", element, "");
}
}
}
Run above given example of wait for element to be clickable in selenium
webdriver in your eclipse with junit. Click here to view different posts
on how to use junit with eclipse for your webdriver test.
*WaitForText
WebDriver - wait for text to be present with example using explicit wait
Some times you need to wait for text, wait for element, wait for alert
before performing actions in your regular test cases. Generally we need to
use this types of conditions in our test case when software web
application page is navigating from one page to other page. In my
previous post, we have seen how to write and use wait for element syntax
in our test case. Now let we see how can we force webdriver to wait if
expected text is not displayed on targeted element.
As you know, we can use "waitForText" or "waitForTextPresent" commands
in selenium IDE to wait till targeted text appears on page or element. In
webdriver, we can use syntax as shown bellow.
WebDriverWait wait = new WebDriverWait(driver, 15);
wait.until(ExpectedConditions.textToBePresentInElementLocated(By.xpath(
"//div[@id='timeLeft']"), "Time left: 7 seconds"));
Look
in
to
above
syntax.
Here
i
have
used textToBePresentInElementLocated(By, String) to wait till expected
text appears on targeted element. So here what WebDriver will do is it will
check for expected text on targeted element on every 500 milliseconds
and will execute next step as soon as expected text appears on targeted
element.
Run bellow given practical example.in eclipse and see how it works.

Copy bellow given @Test method part of wait for text example and replace
it with the @Test method part of example given on this
page. (Note : @Test method is marked with pink color in that linked page).
@Test
public void test ()
{
driver.findElement(By.xpath("//input[@name='fname']")).sendKeys("alpes
h");
WebDriverWait wait = new WebDriverWait(driver, 15);
wait.until(ExpectedConditions.elementToBeClickable(By.cssSelector("#sub
mitButton1")));
driver.findElement(By.cssSelector("#submitButton")).click();
wait.until(ExpectedConditions.textToBePresentInElementLocated(By.xpath(
"//div[@id='timeLeft']"), "Time left: 7 seconds"));
}
In above example, When WebDriver clicks on #submitButton page will be
refreshed and then WebDriver will wait for text = "Time left: 7 seconds" on
targeted element
WebDriver how to wait for alert in selenium 2
As
we
have
seen
in
my
previous
posts,
we
can
use textToBePresentInElementLocated(By, String) WebDriver condition to
wait for text present on page and we can use elementToBeClickable(By
locator) to wait for element clickable/present on page. If you read both
those posts, We had used explicit waits in
both the cases and both are canned expected conditions of webdriver so
we can use them directly in our test case without any modifications.
Sometimes you will face wait for alert scenario where you have to wait for
alert before performing any action on your software application web page.
If you know, we can use "waitForAlert" command in selenium IDE to
handle alerts. In WebDriver/Selenium 2, You can use WebDriver's built in
canned condition alertIsPresent() with wait command as bellow.
WebDriverWait wait = new WebDriverWait(driver, 15);
wait.until(ExpectedConditions.alertIsPresent());
Look in to above syntax. 1st syntax described how much time it has to
wait and 2nd syntax describes the waiting condition. Here we have
used alertIsPresent() condition so it will wait for the alert on page. Let me
give you full practical example to describe scenario perfectly.

Copy paste bellow given test case in your eclipse with JUnit and then run
it. You can View how to configure eclipse with JUnit if you have no idea.
package junitreportpackage;
import java.util.concurrent.TimeUnit;
import
import
import
import
import
import
import
import

org.junit.After;
org.junit.Before;
org.junit.Test;
org.openqa.selenium.By;
org.openqa.selenium.WebDriver;
org.openqa.selenium.firefox.FirefoxDriver;
org.openqa.selenium.support.ui.ExpectedConditions;
org.openqa.selenium.support.ui.WebDriverWait;

public class Mytest1 {


WebDriver driver = new FirefoxDriver();
@Before
public void beforetest() {
driver.manage().window().maximize();
driver.get("http://only-testing-blog.blogspot.in/2014/01/newtesting.html");
}
@After
public void aftertest() {
driver.quit();
}
@Test
public void test ()
{
driver.findElement(By.xpath("//input[@name='fname']")).sendKeys("My
Name");
WebDriverWait wait = new WebDriverWait(driver, 15);
wait.until(ExpectedConditions.alertIsPresent());
String alrt = driver.switchTo().alert().getText();
System.out.print(alrt);
}

}
Above example will wait for the alert on page and as soon as alert appears

on page, it will store alert text in variable 'alrt' and then will print to it in
console.
Selenium WebDriver wait for title with example
WebDriver has many Canned Expected Conditions by which we can force
webdriver to wait explicitly. However Implicit wait is more practical than
explicit wait in WebDriver. But in some special cases where implicit wait is
not able to handle your scenario then in that case you need to use explicit
waits in your test
cases. You can view different posts on explicit waits where I have
described WebDriver's different Canned Expected conditions with
examples.
If you have a scenario where you need to wait for title then you can
use titleContains(java.lang.String title) with webdriver wait. You need to
provide some part of your expected software web application page title
with this condition as bellow.
WebDriverWait wait = new WebDriverWait(driver, 15);
wait.until(ExpectedConditions.titleContains(": MyTest"));
In above syntax, ": MyTest" is my web page's expected title and 15
seconds is max waiting time to appear title on web page. If title will not
appears within 15 seconds due to the any reason then your test case will
fails with timeout error.
First run bellow given test case in your eclipse and then try same test case
for your own software application.
Copy bellow given @Test method part of wait for title example and replace
it with the @Test method part of example given on this
page. (Note : @Test method is marked with pink color in that linked page).

@Test
public void test ()
{
driver.findElement(By.xpath("//input[@name='fname']")).sendKeys("My
Name");
driver.findElement(By.xpath("//a[contains(text(),'Click Here')]")).click();
//Wait for page title
WebDriverWait wait = new WebDriverWait(driver, 15);
wait.until(ExpectedConditions.titleContains(": MyTest"));
//Get and store page title in to variable

String title = driver.getTitle();


System.out.print(title);
}
In above example, when webdriver will click on Click Here link, another
page will open. During page navigation, webdriver will wait for expected
page title.
Selenium WebDriver : How to wait till element visible or appear or present
on page
In any software web application's webdriver test case, you can easily wait
for presence of element using IMPLICIT WAIT. If you have used implicit
wait in your test case then you do not require to write any extra
conditional statement to wait for element visibility. But in some cases, if
any element is taking too much
time to be visible on page then you can use EXPLICIT WAIT condition in
your test case.
If you have a scenario to wait till element visible on page then selenium
webdriver/Selenium
2
has
its
own
method
named visibilityOfElementLocated(By locator) to check the visibility of
element on page. We can use this method with explicit webdriver wait
condition to wait till element visible of present on page. However, we can
wait for element to be clickable using elementToBeClickable(By locator)
method as described in THIS ARTICLE.
Syntax to wait till element visible on page is as bellow. It will wait max 15
seconds for element. As soon as element visible on page, webdriver will
go for executing next statement.
WebDriverWait wait = new WebDriverWait(driver, 15);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//input
[@id='text3']")));
Here is practical example of wait for element visible. Execute it once and
then use it for your software web application test scenario.
Copy bellow given @Test method part of wait for visibility of element
located example and replace it with the @Test method part of example
given on THIS PAGE.(Note : @Test method is marked with pink color in that
linked page).
@Test
public void test () throws InterruptedException, IOException
{
//To wait for element visible
WebDriverWait wait = new WebDriverWait(driver, 15);

wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//input
[@id='text3']")));
driver.findElement(By.xpath("//input[@id='text3']")).sendKeys("Text box
is visible now");
System.out.print("Text box text3 is now visible");
}
How to apply wait in webdriver till element becomes invisible or hidden
As you know, WebDriver is software web application regression testing
tool and you will face many problems during your webdriver test case
creation and execution. You must knows alternate solution if one not
works for your test scenario. For example, you have used IMPLICIT WAIT in
your test case but if it is
not sufficient to handle your condition of waiting till element becomes
invisible from page then you can use it's alternative way of using EXPLICIT
WAIT in your test case.
In
my
PREVIOUS
POST,
I
have
describe
use
of visibilityOfElementLocated(By locator) method with explicit wait to wait
till element becomes visible (not hidden) on page. Now let we look at
opposite side. If you wants webdriver to wait till element becomes
invisible
or
hidden
from
page
then
we
can
use invisibilityOfElementLocated(By locator) method with wait condition.
Syntax for wait till element invisible from page is as bellow.
WebDriverWait wait = new WebDriverWait(driver, 15);
wait.until(ExpectedConditions.invisibilityOfElementLocated(By.xpath("//inp
ut[@id='text4']")));
In above syntax, you can change webdriver wait time from 15 to 20, 30 or
more as per your requirement. Also you can use any OTHER ELEMENT
LOCATING METHODS except By.xpath. Practical example of webdriver wait
till element becomes invisible is as bellow.
Copy bellow given @Test method part of wait till element invisible and
replace it with the @Test method part of example given on THIS PAGE.
(Note : @Test method is marked with pink color in that linked page).
@Test
public void test () throws InterruptedException, IOException
{
//Wait for element invisible
WebDriverWait wait = new WebDriverWait(driver, 15);

wait.until(ExpectedConditions.invisibilityOfElementLocated(By.xpath("//inp
ut[@id='text4']")));
System.out.print("Text box text4 is now invisible");
}
Day 7 - WebDriver Other Examples
12. WebDriver Other Examples Selenium WebDriver : Difference Between findElement and findElements
with example
We have seen many examples of webdriver's findElement() in my previous
posts. You will find syntax of findElement() with example on THIS PAGE if
you wants to use it in your software web application test case. Selenium
WebDriver has one more related command findElements. Now main
question
is
what
is
the
difference between findElement and findElements methods in selenium 2?
First of all let me provide you difference description and then example.
findElement() method

We need to use findElement method frequently in our webdriver test


case because this is the only way to locate any element in
webdriver.

findElement method is useful to locating targeted single element.

If targeted element is not found on the page then it will


throw NoSuchElementException.

findElements() method

We are using findElements method just occasionally.

findElements method will return list of all the matching elements


from current page as per given element locator mechanism.

If not found any element on current page as per given element


locator mechanism, it will return empty list.

Now let me provide you simple practical example of findElement method


and findElements method to show you clear difference. You can VIEW ALL
PRACTICAL EXAMPLES OF SELENIUM WEBDRIVER one by one.
Copy bellow given @Test method part of findElement and findElements
method examples and replace it with the @Test method part of example
given on THIS PAGE. (Note : @Test method is marked with pink color
in that linked page).
@Test
public void test () throws InterruptedException
{
WebElement option =
driver.findElement(By.xpath("//option[@id='country5']"));
System.out.print(option.getAttribute("id")+" - "+option.getText());
List<WebElement> options= driver.findElements(By.xpath("//option"));
System.out.println(options.size());
for(int i=0;i<=options.size();i++)
{
String str = options.get(i).getAttribute("id")+" "+options.get(i).getText();
System.out.println(str);
}
}
In above example, findElement will locate only targeted element and then
print its id and text in console while findElements will locate all those
elements of current page which are under given xpath = //option. for loop
is used to print all those element's id and text in console.
Same way you can locate all input elements, link elements etc..
using findElements method.
How To Generate And Insert Log In Selenium Webdriver Using log4j Jar
Assume you have prepared test case for your software web application
test scenario (using selenium webdriver with eclipse and junit) and now
you wants generate log file to insert your execution time log messages in
to it. How you will do it? Selenium webdriver do not have any built in
function
or
method
to
generate log file. In this case you can use apache logging service. Let me
describe you steps to generate log file in selenium webdriver.
Steps To Generate And Insert Log In Selenium Webdriver
1. Download log4j jar file from logging.apache.org

Click Here to go to log4j jar file downloading page. (This Link URL
may change in future).

Click on Zip folder link as shown in bellow image. Current version


of log4j jar file is log4j-1.2.17. Version of log4j jar file may be
different in future due to the frequent version change.

When you click on zip folder link, it will show you zip mirror links to
download folder. Download and save zip folder by clicking on mirror
link.

Now Extract that zip folder and look inside that extracted folder. You
will find log4j-1.2.17.jar file in it.

2. Import log4j-1.2.17.jar file in your eclipse project from

Right click on your project folder and go to Build Path -> Configure
Build path. It will open java build path window as shown in bellow
image.

Click on Add External JARs button and select log4j-1.2.17.jar file. It


will add log4j-1.2.17.jar file in your build path.

Click on OK button to close java build path window.

3. Create Properties folder under your project folder and


add log4j.properties file in it.

Create folder with name = Properties under your project by right


clicking on your project folder.

Click Here to download log4j.properties file and save it in Properties


folder which is created under your project folder.

Now your properties folder under project folder will looks like bellow.

4. Set Run Configuration


This is optional step. You need to set your Run configure if log file is not
generated and display bellow given warning message in your console
when you run your test case.
log4j:WARN No appenders could be found for logger (dao.hsqlmanager).

Go to Run -> Run Configurations -> Classpath

Select User Entries -> Click on 'Advanced' button -> Select Add
Folder -> And then select Properties folder from your project and
click on OK. Now your Class tab will looks like bellow.

5. Create example(Sample) test case under your project.


Create your own test case or copy example test case from here and paste
it in your class file.
6. Import log4j header file in your project
Import bellow given header file in your test case class file.
import org.apache.log4j.*;
7. Replace bellow given syntax in your class file and Run your test case.
@Test
public void test () throws InterruptedException
{
Logger log;
driver.findElement(By.id("text1")).sendKeys("My First Name");
log = Logger.getLogger(Mytesting.class);
log.info("Type In Text field.");
Select mydrpdwn = new Select(driver.findElement(By.id("Carlist")));
mydrpdwn.selectByVisibleText("Audi");
log = Logger.getLogger(Mytesting.class);
log.info("Select value from drop down.");
WebDriverWait wait = new WebDriverWait(driver, 15);
wait.until(ExpectedConditions.elementToBeClickable(By.id("text2")));
}
When your test case is executed, Go to folder = C:\Logs. log.log file will be
created over there. Open that file and look in to it. Log written in your test
case will be inserted in your log file. In above example, Syntax marked
with Pink color are written for inserting log. Now you can write log at any
place in your test case as shown in above example.
Creating Object Repository Using Properties File In Selenium WebDriver
In selenium WebDriver, There Is not any built In facility to create object
repository. So maintenance of page objects(Page element locators)

becomes very hard If you will write all objects of page on code level. Let
me give you one simple example - You have one search button and you
have used It(Using Id locator) In many
of your test cases. Now supposing someone has changed Its Id In your
application then what you will do? You will go for replacing Id of that
element In all test cases wherever It Is used? It will create overhead for
you. Simple solution to remove this overhead Is creating object repository
using properties File support of java. In properties file, First we can write
element locator of web element and then we can use It In our test cases.
Let us try to create object repository for simple calculator application
given on THIS PAGE and then will try to create test case for that calc
application using object repository..
How to create new properties file
To create new properties file, Right click on your project package -> New
-> Other .

It will open New wizard. Expand General folder In New wizard and select
File and click on Next button.

Give file name objects.properties on next window and click on Finish


button.

It will add object.properties file under your package. Now copy paste
bellow
given
lines
in
objects.properties
file.
So
now
this objects.properties file Is object repository for your web application
page calc.
objects.properties file
#Created unique key for Id of all web elements.
# Example 'one' Is key and '1' Is ID of web element button 1.
one=1
two=2
three=3

four=4
five=5
six=6
seven=7
eight=8
nine=9
zero=0
equalsto=equals
cler=AC
result=Resultbox
plus=plus
minus=minus
mul=multiply
In above file, Left side value Is key and right side value Is element
locator(by Id) of all web elements of web calculator. You can use other
element locator methods too like xpath, css ect.. VISIT THIS LINK to view
different element locator methods of webdriver.
Now let us create webdriver test case to perform some operations on
calculation. In bellow given example, All the element locators are coming
from objects.properties file using obj.getProperty(key). Here key Is
reference of element locator value in objects.properties file.
package ObjectRepo;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;
import
import
import
import
import
import

org.openqa.selenium.By;
org.openqa.selenium.WebDriver;
org.openqa.selenium.firefox.FirefoxDriver;
org.testng.annotations.AfterMethod;
org.testng.annotations.BeforeMethod;
org.testng.annotations.Test;

public class CalcTest {


WebDriver driver = new FirefoxDriver();
@BeforeMethod
public void openbrowser() throws IOException {
driver.manage().window().maximize();
driver.get("http://only-testing-blog.blogspot.in/2014/04/calc.html");
}
@AfterMethod
public void closebrowser() {

driver.quit();
}
@Test
public void Calc_Operations() throws IOException{
//Create Object of Properties Class.
Properties obj = new Properties();
//Create Object of FileInputStream Class. Pass file path.
FileInputStream objfile = new
FileInputStream(System.getProperty("user.dir")
+"\\src\\ObjectRepo\\objects.properties");
//Pass object reference objfile to load method of Properties object.
obj.load(objfile);
//Sum operation on calculator.
//Accessing element locators of all web elements using
obj.getProperty(key)
driver.findElement(By.id(obj.getProperty("eight"))).click();
driver.findElement(By.id(obj.getProperty("plus"))).click();
driver.findElement(By.id(obj.getProperty("four"))).click();
driver.findElement(By.id(obj.getProperty("equalsto"))).click();
String i =
driver.findElement(By.id(obj.getProperty("result"))).getAttribute("value");
System.out.println(obj.getProperty("eight")+" +
"+obj.getProperty("four")+" = "+i);
driver.findElement(By.id(obj.getProperty("result"))).clear();
//Subtraction operation on calculator.
//Accessing element locators of all web elements using
obj.getProperty(key)
driver.findElement(By.id(obj.getProperty("nine"))).click();
driver.findElement(By.id(obj.getProperty("minus"))).click();
driver.findElement(By.id(obj.getProperty("three"))).click();
driver.findElement(By.id(obj.getProperty("equalsto"))).click();
String j =
driver.findElement(By.id(obj.getProperty("result"))).getAttribute("value");
System.out.println(obj.getProperty("nine")+" - "+obj.getProperty("three")
+" = "+j);
}
}
Run above given example In your eclipse and observe execution.
Now supposing I have many such test cases and some one has changed Id
of any button of calc application then what I have to do? I have to modify
all test cases? Answer Is No. I just need to modify objects.properties file
because I have not use element's Id directly In any test case but I have
Used just Its key reference In all test cases.

This way you can create object repository of all your web elements In
one .properties file. You can VIEW MORE TUTORIALS about selenium
webdriver.
14.SeleniumWebDriverTest
think all those who are interested to attend webdriver interview should
aware about few basic interview questions with their correct answers. I
have created frequently asked webdriver/selenium 2 interview questions
test. It is not only for interview purpose but it can improve your basic
knowledge too. For detailed
knowledge on webdriver/selenium 2, you can refer my webdriver tutorial
posts one by one.
Use of webdriver/Selenium 2 is increasing day by day and now many
companies using webdriver for software application automation. Now
webdriver is going to be essential element of software testing process.
Many companies hiring webdriver professionals now a days so now it is
important for
all
of
us
to
know webdriver
very closely.
You can go through JUNIT WITH WEBDRIVER
WEBDRIVER tutorials if you have any related query.

or

TESTNG

WITH

Go through this simple test, and i hope it will help you for your next
interview preparation.
Loading...
Posted by P
Email ThisBlogThis!Share to TwitterShare to FacebookShare to Pinterest
Day 8 - TestNG Framework Tutorials
15. Introduction Of TestNG
Introduction Of TestNG - Unit Testing Framework For Selenium WebDriver
TestNG is unit testing framework and it has been most popular in very sort
time among java developers and selenium webdriver automation test
engineers. I can say, TestNG has not only most of all the features of JUnit
but also many more advanced features in terms of selenium webdriver
testing framework. Basically,
TestNG's development is inspired from combination of NUnit and JUnit. You
can VIEW JUNIT WITH WEBDRIVER TUTORIALS AND EXAMPLES before
going to learn TestNG framework. There are many new features in TestNG
which makes it more powerful, stronger and easier to use. VIEW
SIMILARITIES AND DIFFERENCES between TestNG and JUnit.
TestNG Major Features

TestNG has a built in multiple Before and After and other


annotations
like @BeforeSuite,
@AfterSuite,
@BeforeTest,
@BeforeGroups, @DataProvider, @Parameters, @Test etc.. All
the TestNG annotations are very easy to understand and implement.
We will look each and every annotation with detailed description in
my latter posts.

We can configure dependent test methods in TestNG means


TestTwo() is dependent to TestOne(). We can also configure that if
earlier test method (TestOne()) fails during execution then
dependent test method(TestTwo()) has to be executed or not.

There is not required to extend any class in TestNG.

We can configure our test suite using test methods, classes,


packages, groups, etc.. in single testng.xml file.

Support of configuring test groups like backendtest-group,


frontendtest-group etc.. and we can tell TestNG to execute only
specific group/groups.

TestNG is supported by many tools and plug-ins like Eclipse, Maven,


IDEA, etc..

TestNG
support parallel
testing,
Parameterization
(Passing
parameters values through XML configuration), Data Driven
Testing(executing same test method multiple times using different
data) .

TestNG has built in HTML report and XML report generation facility. It
has also built in logging facility.

VIEW

MORE

TESTNG

TUTORIALS

All these are major features of TestNG and some of them are available in
JUnit too. I recommend you to use TestNG framework with WebDriver test
because there are many useful features available in it compared to JUnit.
Read my latter posts to learn TestNG framework with its detailed features.
16.TestNGInstallationSteps
Steps Of Downloading And Installing Testng In Eclipse For WebDriver
To use TestNG Framework in Eclipse, First of all we have to install it.
Installation of TestNG in Eclipse is very easy process. As I described in
my PREVIOUS POST, TestNG is very powerful and easy to use framework
and it is supported by tools like Eclipse, Maven, IDEA, etc.. Here we are
going
to
use
TestNG

Framework with Eclipse so obviously you must have installed latest Java
development kit (JDK) in your system and you must have Eclipse. CLICK
HERE to view steps of downloading JDK and Eclipse.
Once you have installed JDK and Eclipse in your system, You are ready to
install TestNG in Eclipse. Bellow given steps will describe you how to install
TestNG in Eclipse.
TestNG Installation Steps In Eclipse
Step 1 : Open Eclipse and go to Menu Help -> Install New Software.

It will open new software installation window as shown in bellow given


image.
Step 2 : In new software installation window, Type URL =
http://beust.com/eclipse exactly in Work with field and click on Add button
as shown in bellow given image.

It will show you option TestNG with check box. Select that check box and
click on Next Button as shown in above image.
When you click on Next button, it will check for requirements and
dependency first.

When it completes requirement and dependency test, click on Next


button. On Next screen, it will ask you to accept TestNg terms and license
agreement. Accept it and click on Finish button as shown in bellow given
image.

TestNG will take few minutes to finish its installation when you click on
finish button.
Step 3 : Now you need to verify that TestNG is installed in your eclipse or
not.
To verify Go to Eclipse's Menu Window -> Show View -> Others as shown
in bellow given image.

It will open Show View window. Expand java folder as shown in bellow
given image and verify that TestNG is available inside it or not. If it is there
means TestNG is installed successfully in eclipse.

17.SimilaritiesandDifferenceBetweenTestNGandJUnit
What Are The Similarities/Difference Between Junit and TestNG Framework
For WebDriver
As you know, JUnit and TestNG are very popular unit testing frameworks
for java developers and we can use them in our webdriver test execution.
Till now, I have described all WEBDRIVER TUTORIALS with junit framework.
Many peoples are asking me to describe the similarities and difference
between JUnit and
TestNG Framework. First of all let me give you few similarities
of JUnit and TestNG frameworks and then I will tell you difference between
both of them.
(Note : Bellow given similarities and differences are based on JUnit 4
version.)
Similarities Between JUnit and TestNG
1. We can create test suite in JUnit and TestNG both frameworks.
2. Timeout Test Is possible very easily in both the frameworks.
3. We can ignore specific test case execution from suite in both the
frameworks.
4. It is possible to create expected exception test in both the
frameworks.

5. Annotations - Few annotations are similar in both frameworks suite


like @Test, @BeforeClass, @AfterClass. JUnit's Annotations @Before
and @After are similar to TestNG's @BeforeMethod and
@AfterMethod annotations.
Difference Between JUnit and TestNG
1. In TestNG, Parameterized test configuration is very easy while It is
very hard to configure Parameterized test in JUnit.
2. TestNG support group test but it is not supported in JUnit.
3. TestNG has a feature to configure dependency test. Dependency
test configuration is not possible in JUnit.
4. TestNG support @BeforeTest, @AfterTest, @BeforeSuite, @AfterSuite,
@BeforeGroups, @AfterGroups which are not supported in JUnit.
5. Test prioritization, Parallel testing is possible in TestNG. It is not
supported by JUnit.
6. View more features of TestNG @ THIS LINK .
If you knows more differences or features then you can post it by
commenting bellow.
18.CreateAndRunFirstTestNG-WebDriverTest
How To Create And Run First TestNG-WebDriver Test Case In Eclipse
Our next step to do is - TestNG test case creation in eclipse after
installation of TestNG in eclipse. You can VIEW TESTNG INSTALLATION
STEPS in my earlier post if you have not configured TestNG in your eclipse.
Now let me describe you steps of writing your first test case with TestNG.
Step 1 : Create New Project And Package
First of all, Create new java project in your eclipse with name =
"TestNGOne" and create package "TestNGOnePack" under your project.
VISIT THIS POST If you don't know how to create new java project and
package in eclipse.
Step 2 : Add TestNG Library
For adding TestNG library,

Go to your project's Properties -> Java Build Path -> Libraries Tab.

Click on Add Library button -> Select TestNG from Add Library popup
and then click on Next and Finish buttons.

It will add TestNg library in your project as shown in bellow image. Now
click on OK button to close that window.

Step 3 : Create TestNG Class


To add TestNg class

Right click on package "TestNGOnePack" -> New -> Other. It will


open New wizard window as bellow.

Select TestNg from New wizard window and click on Next button.

On next screen, add class name = ClassOne

It will add new class (ClassOne) under package as shown in bellow


given image.

Step 4 : Add webdriver's external jar file in your project.


To Run webdriver test, you need to add webdriver's jar files as external jar
file in your project. VIEW THIS POST to know how to download webdriver
jar files and add external jar file to java build path.
(Note : Do not add junit jar file as external jar file. Now its not required in
TestNG framework).
This is it. Now you are ready to write your webdriver test script inside your
class.
Step 5 : Add/write sample webdriver test script.
Write your own test script or add bellow given script in your class file.
package TestNGOnePack;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
public class ClassOne {
WebDriver driver = new FirefoxDriver();
//@BeforeMethod defines this method has to run before every @Test
methods
@BeforeMethod
public void openbrowser() {
driver.manage().window().maximize();
driver.get("http://only-testing-blog.blogspot.in/2013/11/new-test.html");
}

//@AfterMethod defines this method has to run after every @Test


methods
@AfterMethod
public void closebrowser() {
System.out.print("\nBrowser close");
driver.quit();
}
@Test
public void testmethodone() {
String title = driver.getTitle();
System.out.print("Current page title is : "+title);
System.out.print("\n'TestNGOne -> TestNGOnePack -> ClassOne ->
testmethodone' has been executed successfully");
}
}
Step 6 : Run Webdriver test script with TestNG
Go to Run -> Run As -> And Click on TestNg Test as shown in bellow given
image.

It will run your webdriver test with TestNG. When execution completed,
You will see result as shown in bellow given image.

Step 7 : View test execution HTML report generated by TestNG


To view test execution report,

Right click on "TestNGOne" project folder in eclipse and select


Refresh.

Folder with name = "test-output" will be created under your project


folder as shown in bellow given Image.

Explore that folder and open it with web Browser as shown in above
image. It will open report in eclipse as shown in bellow given image.

19.TestNgannotationswithexamples
TestNG Annotations With Selenium WebDriver Examples
As you know, TestNG is the framework which is very useful to use with
selenium WebDriver. I have shared all selenium webdriver with testng
tutorials on THIS LINK. The main reason behind TestNG's popularity is we
can create and configure test case and test suite very easily using many
different
annotations
of
TestNG.
Few annotations are similar in TestNG and junit and you can view junit
annotations with example on this JUNIT ANNOTATIONS POST.
Annotations are those things in TestNG which guides it for what to do next
or which method should be executed next. TestNG has also facility to pass
parameters with annotations. Let we look at TestNG annotations list with
its functional description.
@Test
@Test annotation describes method as a test method or part of your test.
VIEW PRACTICAL EXAMPLE OF @Test ANNOTATION
@BeforeMethod
Any method which is marked with @BeforeMethod annotation will be
executed before each and every @test annotated method.
VIEW PRACTICAL EXAMPLE OF @BeforeMethod ANNOTATION
@AfterMethod
Same as @BeforeMethod, If any method is annotated with @AfterMethod
annotation then it will be executed after execution of each and every
@test annotated method.
VIEW PRACTICAL EXAMPLE OF @AfterMethod ANNOTATION
@BeforeClass
Method annotated using @BeforeClass will be executed before first @Test
method execution. @BeforeClass annotated method will be executed once
only
per
class
so
don't
be
confused.
VIEW PRACTICAL EXAMPLE OF @BeforeClass ANNOTATION

@AfterClass
Same as @BeforeClass, Method annotated with @AfterClass annotation
will be executed once only per class after execution of all @Test annotated
methods
of
that
class.
VIEW PRACTICAL EXAMPLE OF @AfterClass ANNOTATION
@BeforeTest
@BeforeTest annotated method will be executed before the any @Test
annotated method of those classes which are inside <test> tag in
testng.xml file.
@AfterTest
@AfterTest annotated method will be executed when all @Test annotated
methods completes its execution of those classes which are inside <test>
tag in testng.xml file.
@BeforeSuite
Method marked with @BeforeSuite annotation will run before the all suites
from test.
VIEW PRACTICAL EXAMPLE OF @BeforeSuite ANNOTATION
@AfterSuite
@AfterSuite annotated method will start running when execution of all
tests executed from current test suite.
VIEW PRACTICAL EXAMPLE OF @AfterSuite ANNOTATION
@DataProvider
When you use @DataProvider annotation for any method that means you
are using that method as a data supplier. Configuration of @DataProvider
annotated method must be like it always return Object[][] which we can
use in @Test annotated method.
VIEW PRACTICAL EXAMPLE OF @DataProvider ANNOTATION
@BeforeGroups
@BeforeGroups annotated method will run before the first test run of that
specific group.
@AfterGroups
@AfterGroups annotated method will run after all test methods of that
group completes its execution.
@Parameters
When you wants to pass parameters in your test methods, you need to
use @Parameters
annotation.
VIEW PRACTICAL EXAMPLE OF @Parameters ANNOTATION
@Factory

When you wants to execute specific group of test cases with different
values, you need to use @Factory annotation. An array of class objects is
returned by @Factory annotated method and those TestNG will those
objects as test classes.
@Listeners
@Listeners are used to with test class. It is helpful for logging purpose.
20.CreatingAndunningWebDriverTestuitUsingtestng.xmlFile
Creating And Running WebDriver Test Suit Using testng.xml File
Introduction Of testng.xml File
In TestNG framework, We need to create testng.xml file to create and
handle multiple test classes. testng.xml is the file where we can configure
our webdriver test, set test dependency, include or exclude any test
method or class or package, set priority etc.. We will learn each and every
thing about TestNG usage in
my future posts. Right now let me describe you how to create testng.xml
Creating testng.xml File

First of all Create a project and webdriver test case as described in


my PREVIOUS POST.

To create testng.xml file, Right click on project folder and Go to New


-> File as shown in bellow given image. It will open New File wizard.

In New file wizard, select "TestNGOne" project and add file name =
"testng.xml" as shown in bellow given image and click on Finish
button.

It will add testng.xml file under your project folder. Now add bellow
given lines in your testng.xml file.

<suite name="Suite One" >


<test name="Test One" >
<classes>
<class name="TestNGOnePack.ClassOne" />
</classes>
</test>
</suite>
Now your testng.xml file will looks like bellow.

In above testng.xml code,

<suite> : suite tag defines the TestNG suite. You can give any name
to your suite using 'name' attribute. In above given example, We
have given "Suite One" to our test suite.

<test> : test tag defines the TestNG test. You can give any name to
your test using 'name' attribute. In above given example, We have
given "Test One" to our test.

<classes> : classes tag defines multiple class. We can multiple test


class under classes tag. In our example we have only one class.

<class> : class tag defines the class name which you wants to
consider in test execution. In above given example, we have defined
name="TestNGOnePack.ClassOne" where 'TestNGOnePack' describes
package name and 'ClassOne' describes class name.

This way, above given testng.xml file will execute only ClassOne class
from TestNGOnePack package.
Executing testng.xml File
To Run
Right click on testng.xml file -> Run As -> Select TestNG Suite as shown in
bellow given image.

It will start execution of defined test class 'ClassOne' from


'TestNGOnePack' package.
When execution completed, You can view test execution HTML report as
described in my PREVIOUS POST. Test execution HTML report will looks like
bellow.

This is the one simple example of creating and running testng.xml file in
eclipse for webdriver. We will see different examples of testng.xml file to
configure our test in my future post.
--20.1CreatingSingleOrMultipleTestsForMultipleClasses
testng.xml : Creating Single Or Multiple Tests For Multiple Classes In
WebDriver

As i have described in my previous post, We can configure our webdriver


test or webdriver test suits in testng.xml file. In my PREVIOUS POST, we
have seen how to create testng.xml file to run single test class. Also If you
don't know how to create and run first TestNG-WebDriver test, You can
VIEW THIS POST.
Now supposing you have two/multiple classes in your test suite then how
will you run them? We can run both the classes in same test as well in 2
different tests too.
First of all, Create 3 classes under project = TestNGOne and package
= TestNGOnePack as bellow.

"BaseClassOne" will be used for initializing and closing webdriver


instance,

"ClassOne" and "ClassTwo" will be used as test classes.

VIEW ALL WEBDRIVER-TESTNG TUTORIAL POSTS


1. BaseClassOne.java
package TestNGOnePack;
import java.util.concurrent.TimeUnit;
import
import
import
import

org.openqa.selenium.WebDriver;
org.openqa.selenium.firefox.FirefoxDriver;
org.testng.annotations.AfterSuite;
org.testng.annotations.BeforeSuite;

public class BaseClassOne {


//Declared as public static to use same webdriver instance publicly
public static WebDriver driver = new FirefoxDriver();
//@BeforeSuite annotation describes this method has to run before all
suites
@BeforeSuite
public void setup() throws Exception {
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
driver.get("http://only-testing-blog.blogspot.in/2013/11/newtest.html");
}
//@AfterSuite annotation describes this method has to run after
execution of all suites
@AfterSuite
public void tearDown() throws Exception {
driver.quit();

}
}
Above class will be used as base class to initialize and close webdriver
instance.
2. ClassOne.java
package TestNGOnePack;
import org.testng.annotations.Test;
public class ClassOne extends TestNGOnePack.BaseClassOne{
//@Test annotation describes this method as a test method
@Test
public void testmethodone() {
String title = driver.getTitle();
System.out.print("\nCurrent page title is : "+title);
String Workdir = System.getProperty("user.dir");
String Classpackname = this.getClass().getName();
System.out.print("\n'"+Workdir+" -> "+Classpackname+" ->
testmethodone' has been executed successfully");
}
}
Above ClassOne is inherited from BaseClassOne.
3. ClassTwo.java
package TestNGOnePack;
import org.testng.annotations.Test;
public class ClassTwo extends TestNGOnePack.BaseClassOne{
//@Test annotation describes this method as a test method
@Test
public void testmethodone() {
driver.navigate().to("http://only-testingblog.blogspot.in/2014/01/textbox.html");
String title = driver.getTitle();
System.out.print("\nCurrent page title is : "+title);
String Workdir = System.getProperty("user.dir");
String Classpackname = this.getClass().getName();
System.out.print("\n'"+Workdir+" -> "+Classpackname+" ->
testmethodone' has been executed successfully");
}
}

Above ClassTwo is also inherited from BaseClassOne.


Now your class structure will be looks like bellow in eclipse.

Configure testng.xml to run two classes in one test


Now let me show you how to configure testng.xml to run both classes in
single test. Copy-paste bellow given lines in your testng.xml file and then
Run it as TestNg Suite. Here, both classes are included in single test (Test
One).
<suite name="Suite One" >
<test name="Test One" >
<classes>
<class name="TestNGOnePack.ClassOne" />
<class name="TestNGOnePack.ClassTwo" />
</classes>
</test>
</suite>
When execution completed, View execution result reports. It will looks like
bellow.

Configure testng.xml to run two classes in two tests

Now if you wants to run both classes as separate test then you have to
configure
your
testng.xml
file
as
bellow.
<suite name="Suite One" >
<test name="Test One" >
<classes>
<class name="TestNGOnePack.ClassOne" />
</classes>
</test>
<test name="Test Two" >
<classes>
<class name="TestNGOnePack.ClassTwo" />
</classes>
</test>
</suite>
Here, "ClassOne" is included in 'Test One" test and "ClassTwo" is included
in 'Test Two" test. Now run bellow given testng.xml file and verify result.

Now compare both the results. In 1st example, Both classes are executed
under same test but in 2nd example both classes are executed under
separate tests. This way you can configure testng.xml file as per your
requirement.
--20.2CreatingTestSuiteUsingClassFromDifferentPackages
testng.xml : Creating WebDriver Test Suite Using Classes From Different
Packages
Now you are already aware about HOW TO CREATE testng.xml FILE to
configure and run your webdriver test. The main reason behind popularity
of TestNG framework for webdriver is we can configure our test as per our

requirements. I have listed some Similarities/Differences between Junit


and TestNG
framework In THIS POST. In my previous post, We have already seen
example of how to configure testng.xml file to run single/multiple
webdriver test classes of same package. Now let me show you an
example of how to create test suite using classes from different packages.
First of all let we create new packages and classes as described in bellow
given 3 steps.
Step
1.
Create
package
=
= BaseClassOne.java, ClassOne.java
described in my PREVIOUS POST.

"TestNGOnePack"
with
classes
and ClassTwo.java
exactly
as

Step 2. Create package = "TestNGTwoPack" under same project and


add ClassOne.java and ClassTwo.java files with bellow given code lines.
ClassOne.java
package TestNGTwoPack;
import org.testng.annotations.Test;
public class ClassOne extends TestNGOnePack.BaseClassOne{
@Test
public void testmethodone() {
String title = driver.getTitle();
System.out.print("\nCurrent page title is : "+title);
String Workdir = System.getProperty("user.dir");
String Classpackname = this.getClass().getName();
System.out.print("\n'"+Workdir+" -> "+Classpackname+" ->
testmethodone' has been executed successfully");
}
}
ClassTwo.java
package TestNGTwoPack;
import org.testng.annotations.Test;
public class ClassTwo extends TestNGOnePack.BaseClassOne{
@Test
public void testmethodone() {
driver.navigate().to("http://only-testingblog.blogspot.in/2014/01/textbox.html");
String title = driver.getTitle();
System.out.print("\nCurrent page title is : "+title);
String Workdir = System.getProperty("user.dir");

String Classpackname = this.getClass().getName();


System.out.print("\n'"+Workdir+" -> "+Classpackname+" ->
testmethodone' has been executed successfully");
}
}
Above
given
both
classes
from TestNGOnePack.BaseClassOne
to
use
initialization and closing the webdriver.

are
webdriver

inherited
instance,

Step 3. Create package = "TestNGThreePack" under same project and


add ClassOne.java and ClassTwo.java files with above given code lines.
You need to change package name in both class(TestNGTwoPack to
TestNGThreePack) to use them in "TestNGThreePack" package.
So now, my package and class hierarchy is as bellow for project
TestNgOne.

Now supposing I do not want to execute all class of all packages and I
wants
to
execute
only
few
of
them
like TestNGOnePack.ClassOne, TestNGTwoPack.ClassTwo, TestNGThreePack.
ClassOne and TestNGThreePack.ClassTwo. How can we do that? You need
to configure your testng.xml file as bellow.
<suite name="Suite One">
<test name="Test One" >
<classes>
<class name="TestNGOnePack.ClassOne" />
<class name="TestNGTwoPack.ClassTwo" />
<class name="TestNGThreePack.ClassOne" />
<class name="TestNGThreePack.ClassTwo" />
</classes>
</test>
</suite>

Above given file will run only described 4 classes out of total 6 classes
under single test (Test One). You can divide them in multiple tests too as
described in my previous post.
Now execute above given testng.xml file and verify result. It will looks like
as shown in bellow given image.

This way we can configure our test suite using only specific class from
different packages.
--20.3CreatingTestSuiteUsingSelectedOrAllPackages
Configure testng.xml In Eclipse For Selenium WebDriver To Run All Or
Specific Package
TestNG is very useful and powerful framework for selenium webdriver. We
need to configure our tests based on our requirements or test scenarios.
We are going very slowly with TestNG framework to understand each and
everything clearly with examples so that it can help you to configure your
test in any
king of situations. In my previous posts, we have learnt about HOW TO
RUN SPECIFIC CLASS FROM DIFFERENT PACKAGE USING testng.xml and
HOW TO RUN SINGLE OR MULTIPLE CLASSES FROM ONE PACKAGE USING
testng.xml. So now you can configure your testng.xml file to run any
specific class from any package if you have read both previous posts.
Configure TestNGOne Project In Eclipse
In testng.xml file, You can also configure to run specific package or all
packages of project. Let we see both examples. First of all, Create bellow
given three packages with required classes, methods and code same as
described in my PREVIOUS POST.

1. TestNGOnePack(package) ->
BaseClassOne.java, ClassOne.java, ClassTwo.java
2. TestNGTwoPack(package) -> ClassOne.java, ClassTwo.java
3. TestNGThreePack(package) -> ClassOne.java, ClassTwo.java
So now your project structure should be as shown in bellow given image.

Configure testng.xml to run selected packages from all packages of


webdriver project in single test suite
From three packages, I wants to run only two packages ->
"TestNGTwoPack" and "TestNGThreePack". For that we need to configure
testng.xml as bellow.
<suite name="Suite One">
<test name="Test One" >
<packages>
<package name="TestNGTwoPack" />
<package name="TestNGThreePack" />
</packages>
</test>
</suite>
In above given testng.xml code, <packages> tag packages is used to
describe group of packages and <package> tag package is used to add

specific package in our test suite. So when you run above testng.xml file,
It will run only targeted two packages(TestNGTwoPack, TestNGThreePack).
Other (TestNGOnePack)package(s) will be excluded from execution.
Execution report will looks like bellow.

As you see, "TestNGOnePack" package is not executed as shown in above


report image.
Configure testng.xml to run all packages of project in single test suite
If you wants to run all packages of your project, you can configure your
testng.xml using wildcard(.*) with package tag as bellow.
<suite name="Suite One">
<test name="Test One" >
<packages>
<package name=".*" />
</packages>
</test>
</suite>
Above given testng.xml file will execute all packages of your selenium
webdriver project and test result report will looks like bellow.

As you see in report, Now all the packages are executed. This way, we can
use wild card to include all webdriver test packages in our test.
--20.4 Including Only Selected Test Methods In Selenium WebDriver-TestNg
Test
Include/Exclude Only Selected Test Methods In Selenium WebDriver-TestNg
Test Suite Using testng.xml
If you are using selenium webdriver with TestNg framework then you can
easily run your selected test methods from selected classes. Supposing
you have a two classes in your package and first class have three test
methods and second class have five test methods. Now you wants to run
only one test method from first
class and two test methods from second class then you can configure it
very easily in testng.xml file. Let me show you how to do it with simple
webdriver test configured by testng.xml file.
Configure TestNGOne Project In Eclipse
1. First of all, Configure TestNGOne project in eclipse as described in
PREVIOUS POST.
2. Add testmethodtwo() bellow the testmethodone() as shown bellow
in ClassOne.java and ClassTwo.java file of all three packages.
public class ClassTwo extends TestNGOnePack.BaseClassOne{
@Test
public void testmethodone() {

driver.navigate().to("http://only-testingblog.blogspot.in/2014/01/textbox.html");
String title = driver.getTitle();
System.out.print("\nCurrent page title is : "+title);
String Workdir = System.getProperty("user.dir");
String Classpackname = this.getClass().getName();
System.out.print("\n'"+Workdir+" -> "+Classpackname+" ->
testmethodone' has been executed successfully");
}
//Add testmethodtwo() here
@Test
public void testmethodtwo() {
driver.findElement(By.xpath("//input[@value='female']"));
String Workdir = System.getProperty("user.dir");
String Classpackname = this.getClass().getName();
System.out.print("\n'"+Workdir+" -> "+Classpackname+" ->
testmethodtwo' has been executed successfully");
}
}
Now your TestNGOne project's structure will looks like bellow.

Configure testng.xml file to Include and run selected webdriver test


methods from few classes
Now supposing, I wants to run only

testmethodone() method from TestNGOnePack -> ClassOne.java

testmethodone()
and testmethodtwo()
from TestNGTwoPack -> ClassTwo.java

methods

testmethodone()
and
testmethodtwo()
from TestNGThreePack -> ClassOne.java

methods

testmethodone()
and
testmethodtwo()
from TestNGThreePack -> ClassTwo.java

methods

To perform above action, I have to configure my testng.xml file as bellow.


<suite name="Suite One">
<test name="Test One" >
<classes>
<class name="TestNGOnePack.ClassOne" />
<methods>
<include name="testmethodone" />
</methods>
<class name="TestNGTwoPack.ClassTwo" />
</classes>
<packages>
<package name="TestNGThreePack" />
</packages>
</test>
</suite>
In above given testng.xml file, methods and include tags are new to learn.
You can read about TestNg Framework's <suite>, <test>, <classes> and
<class> tags in THIS POST and <packages>, <package> tags in THIS
POST. <methods> tag defines the group of methods and <include> tag
defines which method you wants to include in execution. Now execute this
testng.xml file and verify the result report.

If you see in above result, Only test testmethodone() is executed


from TestNGOnePack -> ClassOne.java. This way we can include any
specific method in our test suite to execute from any class.
Configure testng.xml file to exclude specific test method from class
Sameway, To exclude specific test method from class, We can use
<exclude> tag inside <methods> tag as bellow.
<suite name="Suite One">
<test name="Test One" >
<classes>
<class name="TestNGOnePack.ClassOne" />
<methods>
<include name="testmethodone" />
</methods>
<class name="TestNGTwoPack.ClassTwo" />
<methods>
<exclude name="testmethodone" />
</methods>
</classes>
<packages>
<package name="TestNGThreePack" />
</packages>
</test>
</suite>
When you run above given testng.xml file, it will exclude testmethodone()
test method of TestNGTwoPack -> ClassTwo.jav from execution and will
execute only ClassTwo.java file as shown in bellow given test result report.

This way we can configure our testng.xml file to include or exclude any
specific test method from execution.
--20.5 testng.xml - Include/Exclude Selenium WebDriver Test Package
Include/Exclude Selenium WebDriver Test Package From Test Suite Using
testng.xml
Now you are already aware about HOW TO INCLUDE OR EXCLUDE
SELECTED TEST METHODS IN TEST SUITE. Now our next tutorial is about
how to include or exclude selected package from execution of test suite.
Supposing you have multiple packages in your webdriver test suite and
you
wants to run only specific selected package then how will you do it? Let
we look at simple example for the same.
First of all configure project "TestNGOne" with 3 packages as described in
my PREVIOUS POST.
Configuring testng.xml file to include only specific package in test suite
from multiple packages
As described in my THIS POST, we can use wildcard(.*) with package tag
to run all packages but then immediately we will use include to run
specific package from all the packages as bellow.
<suite name="Suite One">
<test name="Test One" >
<packages>
<package name=".*">
<include name="TestNGOnePack" />
</package>
</packages>
</test>
</suite>
When you run above given testng.xml file, it will run only
"TestNGOnePack" package from all packages of "TestNGOne" project. Look
at bellow given TestNg result report.

If you see in above test result of webdriver testng suite, only classes and
methods of "TestNGOnePack" package are executed. remaining 2
packages(TestNGTwoPack and TestNGThreePack) are not executed.
Configuring testng.xml file to exclude specific package from execution
To exclude specific package from execution, You need to configure your
testng.xml file as bellow. Supposing I wants to exclude "TestNGThreePack"
package from execution.
<suite name="Suite One">
<test name="Test One" >
<packages>
<package name=".*">
<exclude name="TestNGThreePack" />
</package>
</packages>
</test>
</suite>
Above given testng.xml file with exclude "TestNGThreePack" package from
execution and will execute remaining two packages as shown in bellow
given report image.

This way we can include or exclude full package from execution.


--20.6 testng.xml - Using Regular Expression To Include/Exclude Test
Method
TestNg With Selenium WebDriver : Using Regular Expression To
Include/Exclude Test Method From Execution
It is very important for us to know the each and every way of testng.xml
configuration to include/exclude selected test methods or packages in
execution. You can view my posts to know how to include/exclude
SELECTED PACKAGE or SELECTED TEST METHODS from selenium
webdriver test suite
execution. There is also one another way of including or excluding
selected test method using regular expression. Let me describe it with one
simple example.
For that you need to configure "TestNGOne" project using 3 packages as
shown in THIS POST. Now let we configure testng.xml file.
Including/Excluding test methods using regular expression
Supposing, I wants to Include testmethodtwo() from TestNGOnePack
-> ClassOne.java file and Exclude testmethodtwo() from TestNGTwoPack
-> ClassTwo.java file using regular expression. For that my testng.xml file
configuration will be looks like bellow.
<suite name="Suite One">

<test name="Test One" >


<classes>
<class name="TestNGOnePack.ClassOne">
<methods>
<include name=".*two.*"/>
</methods>
</class>
<class name="TestNGTwoPack.ClassTwo">
<methods>
<exclude name=".*two.*"/>
</methods>
</class>
</classes>
</test>
</suite>
If you see in above testng.xml file, ".*two.*" is regular expression used for
test methods. Means test methods containing "two" word will be
considered for inclusion/exclusion in test suite execution.. Now when I will
run above testng.xml file, Selenium webdriver test execution report will
looks like bellow.

If you see in above given test execution report, only two methods has
been executed as per our expectation. This way you can use regular
expressions for method's inclusion or exclusion.
--20.7 testng.xml - Skip Test Intentionally Using SkipException()
How To Skip WebDriver Test In TestNG

If you remember, I have posted many posts on TestNG Framework and you
will find all those posts on THIS LINK or you can VIEW THIS PAGE for all
related posts listing. Study all of them one by one on posted date order for
your better understanding. Till now we have learnt about how to Include
or
exclude
TEST METHOD, PACKAGE from execution. We have also learnt REGULAR
EXPRESSION USAGE for Including or Excluding Test methods from
execution. Now supposing you wants to skip specific test Intentionally
from execution then how can you do It?
Skipping WebDriver Test Intentionally
One way of skipping selenium webdriver test method Is using throw new
SkipException() exception - TestNG Exception. Sometimes you need to
check some condition like If some condition match then skip test else
perform some action In your webdriver test. In this kind of situation, you
can use SkipException() exception.
Let us look at simple webdriver test case example where I have placed
SkipException() Inside if condition to Intentionally skip that test. Please
note one thing here : once SkipException() thrown, remaining part of that
test method will be not executed and control will goes directly to next test
method execution.
In bellow given example, If condition will match so throw
new SkipException() part will be executed and due to that
exception, "After If Else" statement will be not printed. Intensional_Skip()
method will be displayed as skipped in Testng report.
Run bellow given example In your eclipse and observe result.
package Testng_Pack;
import
import
import
import
import
import
import
import

java.util.concurrent.TimeUnit;
org.openqa.selenium.By;
org.openqa.selenium.WebDriver;
org.openqa.selenium.firefox.FirefoxDriver;
org.testng.SkipException;
org.testng.annotations.AfterTest;
org.testng.annotations.BeforeTest;
org.testng.annotations.Test;

public class Test_NG {


public static WebDriver driver = new FirefoxDriver();
@BeforeTest
public void setup() throws Exception {
driver.manage().window().maximize();

driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
driver.get("http://only-testing-blog.blogspot.in/2013/11/newtest.html");
}
@Test
public void Intensional_Skip(){
System.out.println("In Verify_Title");
String titl = driver.getTitle();
if(titl.equals("Only Testing: New Test")){
//To Skip Test
throw new SkipException("Test Check_Checkbox Is Skipped");
}else{
System.out.println("Check the Checkbox");
driver.findElement(By.xpath("//input[@value='Bike']")).click();
}
System.out.println("After If Else");
}
@Test
public void Radio_check(){
System.out.println("In Check_Radio");
driver.findElement(By.xpath("//input[@value='male']")).click();
}
@AfterTest
public void tearDown() throws Exception {
driver.quit();
}
}
testng.xml CLICK HERE to view how to create testng.xml
<suite name="Simple Suite">
<test name="Simple Skip Test">
<classes>
<class name = "Testng_Pack.Test_NG"/>
</classes>
</test>
</suite>
Result will be as bellow:

Posted by P
Email ThisBlogThis!Share to TwitterShare to FacebookShare to Pinterest
Related Articles : Selenium 2, selenium webdriver, Test
--20.8 Data driven Testing using @DataProvider Annotation Of TestNG
WebDriver Test Data Driven Testing Using TestNG @DataProvider
Annotation
Data driven testing Is most Important topic for all software testing
automation tools because you need to provide different set of data In your
tests. If you are selenium IDE user and you wants to perform data driven
testing IN YOUR TEST then THESE POSTS will helps you. For Selenium
Webdriver, Data driven testing
using excel file Is very easy. For that you need support of Java Excel API
and It Is explained very clearly In THIS POST. Now If you are using TestNG
framework for selenium webdriver then there Is one another way to
perform data driven testing.
TestNG @DataProvider Annotation
@DataProvider Is TestNG annotation. @DataProvider Annotation of testng
framework provides us a facility of storing and preparing data set In
method. Task of @DataProvider annotated method Is supplying data for a
test method. Means you can configure data set In that method and then
use that data In your test method. @DataProvider annotated method must
return an Object[][] with data.
Let us see simple example of data driven testing using @DataProvider
annotation. We have to create 2 dimensional array In @DataProvider
annotated method to store data as shown In bellow given example. You
can VIEW THIS POST to know more about two dimensional array In java.
Bellow given example will retrieve userid and password one by one from
@DataProvider annotated method and will feed them In LogIn_Test(String
Usedid, String Pass) one by one. Run this example In your eclipse and
observe result.
package Testng_Pack;
import java.util.concurrent.TimeUnit;

import
import
import
import
import
import
import

org.openqa.selenium.By;
org.openqa.selenium.WebDriver;
org.openqa.selenium.firefox.FirefoxDriver;
org.testng.annotations.AfterTest;
org.testng.annotations.BeforeTest;
org.testng.annotations.DataProvider;
org.testng.annotations.Test;

public class Sample_Login {


WebDriver driver = new FirefoxDriver();
@BeforeTest
public void setup() throws Exception {
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
driver.get("http://only-testing-blog.blogspot.in/2014/05/login.html");
}
@AfterTest
public void tearDown() throws Exception {
driver.quit();
}
//This method will return two dimensional array.
//This method behaves as data provider for LogIn_Test method.
@DataProvider
public Object[][] LoginCredentials(){
//Created two dimensional array with 4 rows and 2 columns.
//4 rows represents test has to run 4 times.
//2 columns represents 2 data parameters.
Object[][] Cred = new Object[4][2];
Cred[0][0] = "UserId1";
Cred[0][1] = "Pass1";
Cred[1][0] = "UserId2";
Cred[1][1] = "Pass2";
Cred[2][0] = "UserId3";
Cred[2][1] = "Pass3";
Cred[3][0] = "UserId4";
Cred[3][1] = "Pass4";
return Cred; //Returned Cred
}
//Give data provider method name as data provider.
//Passed 2 string parameters as LoginCredentials() returns 2 parameters
In object.

@Test(dataProvider="LoginCredentials")
public void LogIn_Test(String Usedid, String Pass){
driver.findElement(By.xpath("//input[@name='userid']")).clear();
driver.findElement(By.xpath("//input[@name='pswrd']")).clear();
driver.findElement(By.xpath("//input[@name='userid']")).sendKeys(Usedid)
;
driver.findElement(By.xpath("//input[@name='pswrd']")).sendKeys(Pass);
driver.findElement(By.xpath("//input[@value='Login']")).click();
String alrt = driver.switchTo().alert().getText();
driver.switchTo().alert().accept();
System.out.println(alrt);
}
}
testng.xml file to run this example Is as bellow.
<suite name="Simple Suite">
<test name="Simple Skip Test">
<classes>
<class name = "Testng_Pack.Sample_Login"/>
</classes>
</test>
</suite>
When you will run above example In eclipse, It will enter UserID and
passwords one by one In UserId and password test box of web page.
TestNG result report will looks like bellow.

Posted by P
Email ThisBlogThis!Share to TwitterShare to FacebookShare to Pinterest
Related Articles : Data Driven Testing in webdr

--20.9 Parallel test execution In multiple browsers using @Parameters


annotation
Selenium WebDriver Parallel Tests Execution Using TestNG - @Parameters
Browser compatibility testing Is most Important thing for any web
application and generally you have to perform browser compatibility
testing before 1 or 2 days of final release of application. In such a sort
time period, you have to verify each Important functionality In every
browsers suggested by client. If you will go
for running your all webdriver tests In each browsers one by one then It
will take too much time to complete your test and you may not complete
It before release. In such situation, Running your tests In all required
browsers at same time will helps you to save your time efforts. So
question Is - Can we run our tests parallel In all required browsers using
webdriver? Answer Is yes.
Before learning how to run webdriver test parallel in multiple browsers,
You must have knowledge about how to run test In webdriver using TestNg
framework. You will find links of TestNG tutorial post with examples on
THIS PAGE. I have described testng configuration with detailed
explanation on those links so read them carefully one by one. You can
read webdriver related more tutorials on THIS LINK.
Parallelism In TestNG
You can configure your testng.xml file In such a way to run your test suite
or tests or methods In seperate browsers Is known as parallelism In
TestNG. Interviewer can ask you this question. Now let us look at example
of parellel test execution In webdriver using testng. Bellow given example
will run the test In Mozilla Firefox and Google chrome browser parallel.
Created Test_Parallel.java class file for testing application and configured
testng.xml file to run tests parallel as shown In bellow given example. In
testng.xml file, parallel="tests" Inside <suite> tag will Instruct TestNG to
consider bunch of methods of each <test> tag as separate thread. Means
If you wants to run your test In 2 different browsers then you need to
create two <test> blocks for each browser Inside testng.xml file and
Inside each <test> tag block, define one more tag "parameter" with same
name(In both <test> block) but with different values. In bellow given
testng.xml file, each <test> block has "parameter" tag with same name
= browser but different values(FFX and CRM).
In testcase, I have used @Parameters annotation to pass parameter In
method. Values of this parameter will be feed by testng.xml file. and then
If condition will check that value to decide which driver to use for test.
This way, example testng.xml file will feed two values(FFX and CRM) In

parameter so It will open Firefox and Google chrome browsers and run test
In both browsers. (For running test In google chrome, You need to
download chromedriver.exe. VIEW THIS POST to know more how to run
webdriver test In google chrome browser).
Run bellow given test In your eclipse with testng to see how It runs your
test In 2 browsers at same time.
Test_Parallel.java
package Testng_Pack;
import org.junit.Assert;
public class Test_Parallel {
private WebDriver driver=null;
@BeforeClass
//parameter value will retrieved from testng.xml file's <parameter> tag.
@Parameters ({"browser"})
public void setup(String browser){//Method will pass value of parameter.
if (browser.equals("FFX")) {//If value Is FFX then webdriver will open
Firefox Browser.
System.out.println("Test Starts Running In Firefox Browser.");
driver = new FirefoxDriver();
}else if (browser.equals("CRM")){//If value Is CRM then webdriver will
open chrome Browser.
System.out.println("Test Starts Running In Google chrome.");
System.setProperty("webdriver.chrome.driver",
"D:\\chromedriver_win32_2.3\\chromedriver.exe");
driver = new ChromeDriver();
}
driver.manage().window().maximize();
driver.get("http://only-testing-blog.blogspot.in/2014/05/login.html");
}
//Both bellow given tests will be executed In both browsers.
@Test
public void verify_title(){
String title = driver.getTitle();
Assert.assertEquals("Only Testing: LogIn", title);
System.out.println("Title Is Fine.");
}
@Test
public void verify_message(){
driver.findElement(By.xpath("//input[@name='userid']")).sendKeys("UID1")
;
driver.findElement(By.xpath("//input[@type='password']")).sendKeys("pass
1");
driver.findElement(By.xpath("//input[@value='Login']")).click();

String alert = driver.switchTo().alert().getText();


driver.switchTo().alert().accept();
Assert.assertEquals("UserId Is : UID1 Password Is : pass1", alert);
System.out.println("Alert Is Fine.");
}
@AfterClass
public void closebrowser(){
driver.quit();
}
}
testng.xml
<suite name="webDriver" parallel="tests">
<test name="Test In FireFox" >
<parameter name="browser" value="FFX" />
<classes>
<class name="Testng_Pack.Test_Parallel" />
</classes>
</test>
<test name="Test In Google Chrome" >
<parameter name="browser" value="CRM"></parameter>
<classes>
<class name="Testng_Pack.Test_Parallel"></class>
</classes>
</test>
</suite>
If you wants to run your test In one more browser then you need to create
new <test> tag block in testng.xml file and set another parameter value
and then put one more if else condition in class file to check and run your
test.
This way you can your test parallel In multiple browsers at same time to
reduce your time efforts.
Day 9 - WebDriver Assertions With TestNG
Hard Assertions
20.1 assertEquals Assertion With Example
Assert.assertEquals TestNG With Selenium WebDriver Example
There are many assertions available in Selenium WebDriver with TestNG
framework and we will look at all of then one by one. Assertions are
important and very useful in any automation tools to assert something
during your test execution. If you know, Selenium IDE has many built in
assertion commands and if you are

selenium IDE user then you can view set of selenium IDE assertion
command examples on THIS LINK.
Difference between Assertion and verification
Verification and assertion is little different so don't be confused.
Verification will just verify but assertion will first verify and if result is not
as per expectation then it will stop execution of that specific test method.
Today let we look at assertEquals assertion in selenium webdriver.
Assert.assertEquals(actual, expected) assertion
This assertion is useful to compare expected and actual values in
selenium webdriver. If both values match then its fine and will continue
execution. But if fails then immediately it will mark that specific test
method as fail and exit from that test method.
You can use different types of values in actual and expected
like boolean, byte[], char, double, float, int, etc.. but function is same for
all. Let we look at simple example to understand it better.
Steps :

First of all, create 3 classes (BaseClassOne.java and ClassTwo.java)


as describe in THIS POST if you don't have created.

Now copy paste bellow given lines in your ClassTwo.java file.

Assertion and Verification Example Of Selenium WebDriver With TestNg


package TestNGOnePack;
import
import
import
import

org.openqa.selenium.By;
org.testng.Assert;
org.testng.annotations.BeforeClass;
org.testng.annotations.Test;

public class ClassTwo extends TestNGOnePack.BaseClassOne{


String Actualtext;
@BeforeClass
public void load_url(){
driver.navigate().to("http://only-testingblog.blogspot.in/2014/01/textbox.html");
}
//Method Example For Assertion
@Test
public void assertion_method_1() {
Actualtext = driver.findElement(By.xpath("//h2/span")).getText();
Assert.assertEquals(Actualtext, "Tuesday, 28 January 2014");
System.out.print("\n assertion_method_1() -> Part executed");

}
//Method Example For Assertion
@Test
public void assertion_method_2() {
Assert.assertEquals(Actualtext, "Tuesday, 29 January 2014");
System.out.print("\n assertion_method_2() -> Part executed");
}
//Method Example For Verification
@Test
public void verification_method() {
String time =
driver.findElement(By.xpath("//div[@id='timeLeft']")).getText();
if (time == "Tuesday, 28 January 2014")
{
System.out.print("\nText Match");
}
else
{
System.out.print("\nText does Match");
}
}
}
testng.xml example to run single class
To Run above example using testng.xml file, you will have to configure it
as bellow.
<suite name="Suite One" configfailurepolicy="continue">
<test name="Test One">
<classes>
<class name="TestNGOnePack.ClassTwo" />
</classes>
</test>
</suite>
If you run above example, assertion_method_1() will display pass in result
but assertion_method_2() will display fail because here expected and
actual values will not match with each other.

If you will look in console, Only "assertion_method_1() -> Part executed"


will be printed over there. "assertion_method_2() -> Part executed" will be
not there because execution of current method was skipped after
assertion failure. Last verification_method() is just simple verification
method which verifies text and print message based on result.
20.2 assertNotEquals Assertion With Example
Example Of assertNotEquals In Selenium WebDriver With TestNG
As described in my PREVIOUS POST, assertEquals assertion is useful to
compare two string, boolean, byte[], char, double, float, int, etc.. and
based on assertion result, Your test method will pass or fail. This pass or
fail indication will helps you in your testing process. So this is the very
good function in selenium
WebDriver which helps us to find and log issue. Please note one thing
once more is - Use hard assertions in selenium webdriver only when you
wants to skip remaining test execution on assertion fail. If you wants to
continue execution on assertion failure, you can use TestNg soft
assertions. We will discuss about it in my upcoming post.
You can VIEW SELENIUM IDE ASSERTION EXAMPLES for your reference.
Assert.assertNotEquals(actual, expected, message) assertion
Other one assertion in selenium WebDriver is assertNotEquals assertion.
It's function is opposite to assertEquals assertion. Means if both sides
values will not match then this assertion will pass else it will fail. Here you
can write your own message for failure condition. Simplest example
of Assert.assertNotEquals in selenium webdriver is as bellow.

Replace bellow given test methods (assertion_method_1() and


assertion_method_2()) with example given in my PREVIOUS POST and
then run it using testng.xml file.
//Assertion Method
@Test
public void assertion_method_1() {
Actualtext = driver.findElement(By.xpath("//h2/span")).getText();
Assert.assertNotEquals(Actualtext, "Tuesday, 28 January 2014",
"Expected and actual match in assertion_method_1");
System.out.print("\n assertion_method_1() -> Part executed");
}
//Assertion Method
@Test
public void assertion_method_2() {
Assert.assertNotEquals(Actualtext, "Tuesday, 29 January 2014",
"Expected and actual match in assertion_method_2");
System.out.print("\n assertion_method_2() -> Part executed");
}
You test execution result will looks like bellow..

Here, test method assertion_method_1() will fail because actual string text
and expected string text will match. Assertion message will be printed in
test result report as marked with green color in above image.
20.3 assertTrue Assertion With Example

Selenium WebDriver assertTrue assertion example with TestNG


Previously we have learnt two assertions of selenium webdriver. You can
view practical example pages of selenium webdriver assertions
- assertEquals and assertNotEquals before learning assertTrue(condition)
assertion.
There
is
also
one
another
related
assertion
is assertFalse(condition) assertion but we will look
about it in my next post.
assertTrue(condition) Assertion
assertTrue assertion is generally used for boolean condition true. It will
pass if condition returns "true". If it will return false then it will fail and skip
test execution from that specific method. Syntax for assertTrue assertion
is as bellow.
Assert.assertTrue(condition);
Supposing you have one check box on page. You wants to check its status
like it is checked or not. And if it is not checked then you wants to skip
execution from that method and wants to fail that method in testng
report. This thing can be done very easily using assertTrue assertion. Let
we look at practical example of assertTrue assertion.
Replace bellow given variables and 3 methods with example given on my
THIS POST and then run it using testng.xml file.
WebElement chk1, chk2;
@BeforeClass
public void load_url(){
driver.get("http://only-testing-blog.blogspot.in/2014/02/attributes.html");
chk1 = driver.findElement(By.xpath("//input[@name='option1']"));
chk2 = driver.findElement(By.xpath("//input[@name='option2']"));
}
//Assertion Method - will pass
@Test
public void asserttrue1() {
System.out.print("\n"+chk1.isSelected());
Assert.assertTrue(chk1.isSelected());
System.out.print("\n asserttrue1 - > Executed - means assertion is
pass");
}
//Assertion Method - will fail
@Test
public void asserttrue2() {
System.out.print("\n"+chk2.isSelected());
Assert.assertTrue(chk2.isSelected());

System.out.print("\n asserttrue2 - > Executed - means assertion is


pass");
}
When you run above example in eclipse and get result, asserttrue1()
method will display pass and method asserttrue2() will display fail as
shown in bellow given image.

asserttrue1() will pass because 1st check box is checked on page


so chk1.isSelected() will return true.
asserttrue2() will fail because 2nd check box is not checked on page
so chk2.isSelected() will return false. In assertion failure case, code written
after Assert.assertTrue(chk2.isSelected()); will be not executed. Run above
example in your eclipse and verify the results then try it for your own
project.
This way, Assert.assertTrue(condition) is helps use to assert boolean
condition true.
20.4 assertFalse Assertion With Example
Example Of Assert.assertFalse Assertion In Selenium WebDriver With
TestNG
When you are working with selenium webdriver, you must be aware about
different kind of assertions which are available. If you have a enough
knowledge about webdriver assertions, You can create very effective test
cases
for
your
test
scenarios. assertEquals, assertNotEquals and
assertTrue assertions are already

explained in my previous posts. Now let we try to understand assertFalse


assertion for selenium webdriver.
Assert.assertFalse(condition) Assertion
It will check boolean value returned by condition and will pass if returned
value is "False". If returned value is pass then this assertion will fail and
skip execution from current test method. Syntax for assertFalse assertion
is as bellow.
Assert.assertFalse(condition);
In sort, assertFalse and assertTrue assertions are opposite to each other.
When you wants to assert "True" value - you can use assertTrue assertion.
And when you wants to assert false value - you can use assertFalse
assertion in your selenium webdriver test.
Let we try to use assertFalse assertion with simple example. Supposing we
have two checkboxs on page one from them is checked and another one is
not checked. Let we apply assertFalse assertion on both of these check
boxes for its checked status.
Replace bellow given example methods with example of THIS PAGE. and
run it with testng.xml as described on that post.
WebElement chk1, chk2;
@BeforeClass
public void load_url(){
driver.get("http://only-testing-blog.blogspot.in/2014/02/attributes.html");
chk1 = driver.findElement(By.xpath("//input[@name='option1']"));
chk2 = driver.findElement(By.xpath("//input[@name='option2']"));
}
//Assertion Method - will Fail
@Test
public void assertfalse1() {
System.out.print("\n"+chk1.isSelected());
Assert.assertFalse(chk1.isSelected());
}
//Assertion Method - will Pass
@Test
public void assertfalse2() {
System.out.print("\n"+chk1.isSelected());
Assert.assertFalse(chk2.isSelected());
}
In this case, assertfalse1() method will fail because it is already checked
so chk1.isSelected() will return true value. assertfalse2() method will pass
because 2nd checkbox is not checked so it will return false value.
Execution result will looks like bellow.

20.4 assertNull Assertion With Example


Selenium WebDriver Assertion assertNull Example With TestNG
Assertions are very useful to check your expected result and skip
execution if assertion fails on run time. If you are selenium IDE user, you
can read all these selenium IDE ASSERTION COMMANDS examples posts
to use them in your test cases for your web application. Before describing
about assertNull command,
I recommend you all to READ OTHER WEBDRIVER ASSERTION METHOD
examples for your reference.
assertNull(object) WebDriver Assertion
assertNull(object) assertion will check and verify that object is null. It will
pass if object found null. If object found not null then it will return error
message like "java.lang.AssertionError: expected [null] but found [true]".
Whenever your assertion fails, it will mark that specific test method as fail
in TestNG result.
Let me present here one simple example of assertNull assertion. We have
two text boxes. 1st text box is enabled and 2nd is disabled. Now let me
use assertNull assertion in my test script to assert that textbox1 is
enabled and textbox2 is disabled. Here we use textbox's disabled attribute
for this assertion.
Copy and replace bellow given test methods with example given on THIS
PAGE and then run it with testng.xml file
WebElement txt1, txt2;

@BeforeClass
public void load_url(){
driver.get("http://only-testing-blog.blogspot.in/2014/02/attributes.html");
txt1 = driver.findElement(By.xpath("//input[@id='text1']"));
txt2 = driver.findElement(By.xpath("//input[@id='text2']"));
}
//Example Of Assertion Method - will Pass
@Test
public void null1() {
System.out.print("\n"+txt1.getAttribute("disabled"));
Assert.assertNull(txt1.getAttribute("disabled"));
}
//Example Assertion Method - will Fail
@Test
public void null2() {
System.out.print("\n"+txt2.getAttribute("disabled"));
Assert.assertNull(txt2.getAttribute("disabled"));
}
In above given example, txt1.getAttribute("disabled") object will return
"null" because there is not any disabled attribute with 1st textbox. So that
assertion
will
pass.
And
method
null1()
will
pass
too.
txt2.getAttribute("disabled") object will return "true" because disabled
attribute is available with textbox2. So in this case that assertion and
method null2() will fail as shown in bellow given image.

20.4 assertNotNull Assertion With Example


TestNG Assertion assertNotNull With WebDriver Example

As you know, there are many assertions in TestNG and you will find most
of them on THIS PAGE. Each of these TestNG assertions are designed to
fulfill different kind of conditions. I have described mostly used all
assertions with very clear examples with selenium webdriver test. If you
will see on that link, you will find
example of assertNull assertion. assertNotNull assertion works opposite to
assertNull assertion means it will assert not null condition.
TestNG Assertion assertNotNull(object) WebDriver Assertion
assertNotNull assertion is designed to check and verify that values
returned by object is not null. Means it will be pass if returned value is not
null. Else it will fail.
Best example to experiment assertNotNull assertion is assertion of
enabled and disabled text fields. Let me give you simple example where
we will assert "disabled" attribute of text box to verify is it disabled or not
using assertNotNull assertion.
Copy paste bellow given code in example given on THIS PAGE and then
run it using testng.xml file.
WebElement txt1, txt2;
@BeforeClass
public void load_url(){
driver.get("http://only-testing-blog.blogspot.in/2014/02/attributes.html");
txt1 = driver.findElement(By.xpath("//input[@id='text1']"));
txt2 = driver.findElement(By.xpath("//input[@id='text2']"));
}
//Example Of Assertion Method - will Fail
@Test
public void notnull1() {
System.out.print("\n"+txt1.getAttribute("disabled"));
Assert.assertNotNull(txt1.getAttribute("disabled"));
}
//Example Of Assertion Method - will Pass
@Test
public void notnull2() {
System.out.print("\n"+txt2.getAttribute("disabled"));
Assert.assertNotNull(txt2.getAttribute("disabled"));
}
In above example, assertNotNull assertion of notnull1() method will fail
because expected was not null but textbox text1 is not disabled so
returned null. assertNotNull assertion of notnull2() will pass because
expected was not null and textbox text2 is disabled so it has return true
value means not null.

Sameway, You can use assertNotNull assertion to assert checkbox is


checked or not, to assert textbox is visible or hidden, etc..
Soft Assertion
20.4 Applying TestNG Soft Assertion With Example
Soft Assertion For Selenium WebDriver With TestNG
If you know, we have already learn about testng hard assertions (Example
assertEquals, assertNotEquals, etc..) which we can use In our webdriver
test. Hard assertion examples links are given on THIS PAGE. View all those
examples one by one to learn hard assertions. Let me tell you one thing
about hard assertions, When hard assertion will fail Inside any test
method, remaining execution of that specific test method will be aborted.
Now If you wants to continue remaining test part execution even If
assertion fails and also you wants to report assertion failure In testng
result report then you can use testng soft assertion method.
Soft Assertions In Selenium WebDriver
To use testng soft assertion, you have to use testng SoftAssert class. This
class will helps to not throw an exception on assertion failure and
recording failure. If you will use soft assertion then your test execution will
remain continue even If any assertion fails. Another most Important thing
Is your assertion failure will be reported In report so that you can view It at
end of test. You can use soft assertion when you are using multiple
assertions In same test method and you wants to execute all of them even
If any one In between fails.
Let us look at very simple example of testng hard assertion and soft
assertion to see the difference between both of them. In bellow give

example, hard_assert_text() and soft_assert_text() each have 4 assertions.


Used hard assertions In hard_assert_text() method and soft assertions In
soft_assert_text() method to describe difference between both of them.
Run bellow given example In your eclipse with testng framework.
package Testng_Pack;
import
import
import
import
import
import
import
import
import
import

org.openqa.selenium.By;
org.openqa.selenium.WebDriver;
org.openqa.selenium.firefox.FirefoxDriver;
org.openqa.selenium.support.ui.ExpectedConditions;
org.openqa.selenium.support.ui.WebDriverWait;
org.testng.Assert;
org.testng.annotations.AfterClass;
org.testng.annotations.BeforeClass;
org.testng.annotations.Test;
org.testng.asserts.SoftAssert;

public class Soft_Assert {


//Created object of testng SoftAssert class to use It's Properties.
SoftAssert s_assert = new SoftAssert();
String Actualtext;
WebDriver driver = new FirefoxDriver();
@BeforeClass
public void load_url(){
driver.manage().window().maximize();
driver.get("http://only-testing-blog.blogspot.in/2014/01/textbox.html");
}
@Test
//In this method, If any assertion fails then execution will be aborted.
public void hard_assert_text() {
Actualtext = driver.findElement(By.xpath("//h2/span")).getText();
//Text on expected side Is written Incorrect intentionally to get fail this
assertion.
Assert.assertEquals(Actualtext, "Tuesday, 01 January 2014", "1st assert
failed.");
System.out.println("Hard Assertion -> 1st pagetext assertion
executed.");
Assert.assertEquals(Actualtext, "Tuesday, 28 January 2014", "2nd assert
failed.");
System.out.println("Hard Assertion -> 2nd pagetext assertion
executed.");
driver.findElement(By.xpath("//input[@value='Show Me Alert']")).click();
String Alert_text = driver.switchTo().alert().getText();

driver.switchTo().alert().accept();
Assert.assertEquals(Alert_text, "Hi.. is alert message!", "Alert Is
InCorrect");
System.out.println("Hard Assertion -> 1st alert assertion executed.");
Assert.assertEquals(Alert_text, "Hi.. This is alert message!", "Alert Is
Correct");
System.out.println("Hard Assertion -> 2nd alert assertion executed.");
}
@Test
//In this method, Test execution will not abort even If any assertion fail.
Full Test will be executed.
public void soft_assert_text() {
Actualtext = driver.findElement(By.xpath("//h2/span")).getText();
//Text on expected side Is written Incorrect intentionally to get fail this
assertion.
s_assert.assertEquals(Actualtext, "Tuesday, 01 January 2014", "1st
assert failed.");
System.out.println("Soft Assertion -> 1st pagetext assertion executed.");
s_assert.assertEquals(Actualtext, "Tuesday, 28 January 2014", "2nd
assert failed.");
System.out.println("Soft Assertion -> 2nd pagetext assertion
executed.");
driver.findElement(By.xpath("//input[@value='Show Me Alert']")).click();
String Alert_text = driver.switchTo().alert().getText();
driver.switchTo().alert().accept();
//Alert expected text Is written Incorrect intentionally to get fail this
assertion.
s_assert.assertEquals(Alert_text, "Hi.. is alert message!", "Alert Is
InCorrect");
System.out.println("Soft Assertion -> 1st alert assertion executed.");
s_assert.assertEquals(Alert_text, "Hi.. This is alert message!", "Alert Is
Correct");
System.out.println("Soft Assertion -> 2nd alert assertion executed.");
s_assert.assertAll();
}
@Test
public void wait_and_click(){
WebDriverWait wait = new WebDriverWait(driver, 15);
wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//input[@id
='submitButton']")));
driver.findElement(By.xpath("//input[@id='submitButton']")).click();

}
@AfterClass
public void Closebrowser(){
driver.quit();
}
}
On execution completion, you will get bellow given result In console.
Soft Assertion -> 1st pagetext assertion executed.
Soft Assertion -> 2nd pagetext assertion executed.
Soft Assertion -> 1st alert assertion executed.
Soft Assertion -> 2nd alert assertion executed.
PASSED: wait_and_click
FAILED: hard_assert_text
As per console result, soft_assert_text() method Is executed full and
printed all statements even failed 2 assertions. On other
side, hard_assert_text() method has not printed any statement In console
because execution aborted on first assertion failure.
Now If you look at testng test result report, both failures of soft assertion
has been reported In testng report (You can view this post to see HOW TO
VIEW TESTNG TEST RESULT REPORT). That means your assertion failure
has been reported without test abortion. Look at bellow give our testng
test result report.

Day 10 Common Functions To Use In WebDriver Test


20.1 Common Function To Compare Two Strings

General Function To Comparing Two Strings In Selenium WebDriver


TestCase
When you will use selenium webdriver to automate real world
applications, Many times you have to compare two strings like page title,
product name or any other string. And based on comparison result you
have to take specific action. Simple example of such scenario Is, You are
navigating on any view product
page to add product In to basket. But before adding product In basket, You
wants to verify product's name to check It Is correct product or not.
Many time you have to compare strings In automating any single
application. So What you will do? You will write same code multiple time In
your different scripts? General way(Which I am using) Is to create common
method In base class (Which Is accessible from all test classes) to
compare two strings. Then we can call that method by passing actual and
expected string to compare strings whenever required In out tests.
Let me explain you how to do It.
VIEW MORE WEBDRIVER TUTORIALS STEP BY STEP
Step 1 : Create CommonFunctions Class In your package which can be
accessible by any other class.
Step 2 : Create method compareStrings which can accept two string
values. Also Create object of TestNG SoftAssert class to assert assertion
softly as shown In bellow given example.
package Testng_Pack;
import org.testng.Assert;
import org.testng.asserts.SoftAssert;
public class CommonFunctions {
SoftAssert Soft_Assert = new SoftAssert();
public boolean compareStrings(String actualStr, String expectedStr){
try{
//If this assertion will fail, It will throw exception and catch block will be
executed.
Assert.assertEquals(actualStr, expectedStr);
}catch(Throwable t){
//This will throw soft assertion to keep continue your execution even
assertion failure.
//Use here hard assertion "Assert.fail("Failure Message String")" If you
wants to stop your test on assertion failure.
Soft_Assert.fail("Actual String '"+actualStr+"' And Expected String
'"+expectedStr +"' Do Not Match.");

//If Strings will not match, return false.


return false;
}
//If Strings match, return true.
return true;
}
}
Step 3 : Now we can call compareStrings method In our test class
whenever required as shown In bellow given example. We have Inherited
CommonFunctions class to use Its function In Common_Functions_Test.
Also call Soft_Assert.assertAll() method at last of your test to mark your
test fail If both strings not match. Read More about usage of TestNG Soft
Assertion In webdriver.
package Testng_Pack;
import
import
import
import
import

org.openqa.selenium.WebDriver;
org.openqa.selenium.firefox.FirefoxDriver;
org.testng.annotations.AfterTest;
org.testng.annotations.BeforeTest;
org.testng.annotations.Test;

//Used Inheritance
public class Common_Functions_Test extends CommonFunctions{
WebDriver driver;
@BeforeTest
public void StartBrowser_NavURL() {
driver = new FirefoxDriver();
driver.get("http://only-testing-blog.blogspot.in/2014/05/login.html");
}
@AfterTest
public void CloseBrowser() {
driver.quit();
}
@Test
public void testToCompareStrings(){
String actualTitle = driver.getTitle();
//Call compareStrings method Inside If condition to check string match or
not.
if(compareStrings(actualTitle, "Only Testing: LogIn")){
//If strings match, This block will be executed.
System.out.println("Write Action taking lines In this block when title
match.");
}else{
//If strings not match, This block will be executed.

System.out.println("Write Action taking lines In this block when title not


match.");
}
//To mark test fail In report at the end of execution If strings not match.
Soft_Assert.assertAll();
}
}
Above given example will compare actual and expected title strings and
mark test failure at the end of test execution If both strings not match
without any Interruption In execution. Now you can call compareStrings
method any time to compare strings. You just need to provide expected
and
actual
string
values.
Note : You can use hard assertion In your common function catch block at
place of soft assertion If you wants to stop test on failure. See bellow. If
you will use bellow given syntax In catch block then It will stop test
execution
on
failure.
Assert.fail("Actual String '"+actualStr+"' And Expected String
'"+expectedStr+"' Do Not Match.");
20.2 Common Function To Compare Two Integers
Method To Compare Two Integer Values In Selenium WebDriver Test
We have learnt how to create common function to compare two strings In
my PREVIOUS POST. Same way, Many times you need to compare two
Integer values. And based on comparison result, You can perform your
next step of test execution. You can also stop or continue your test
execution on assertion
failure by using soft or hard TestNG assertions. In this post, we will see
how to compare two Integer values using common function.
Main Intention of creating this kind of common functions Is to minimize
your code size. You have to create It only once and then you can call It
again and again whenever required In your test. And for that, You have to
create common class which should be accessible from all the test classes.
If you are retrieving text(which Is Integer value) from web page using
webdriver's .getText() function then It will be string and you have to
convert It In Integer value using bellow given syntax before comparision.
String actualValString = driver.findElement(By.xpath("//*[@id='post-body8228718889842861683']/div[1]/table/tbody/tr[1]/td[2]")).getText();
//To convert actual value string to Integer value.

int actualVal = Integer.parseInt(actualValString);


Bellow given example will explain you how to create common function to
compare two Integers In your CommonFunctions class.
package Testng_Pack;
import org.testng.Assert;
import org.testng.asserts.SoftAssert;
public class CommonFunctions {
SoftAssert Soft_Assert = new SoftAssert();
public boolean compareIntegerVals(int actualIntegerVal, int
expectedIntegerVal){
try{
//If this assertion will fail, It will throw exception and catch block will be
executed.
Assert.assertEquals(actualIntegerVal, expectedIntegerVal);
}catch(Throwable t){
//This will throw soft assertion to keep continue your execution even
assertion failure.
//Un-comment bellow given hard assertion line and commnet soft
assertion line If you wants to stop test execution on assertion failure.
//Assert.fail("Actual Value '"+actualIntegerVal+"' And Expected Value
'"+expectedIntegerVal+"' Do Not Match.");
Soft_Assert.fail("Actual Value '"+actualIntegerVal+"' And Expected
Value '"+expectedIntegerVal+"' Do Not Match.");
//If Integer values will not match, return false.
return false;
}
//If Integer values match, return true.
return true;
}
}
Now you can call compareIntegerVals() function In your test to compare
two Integer values as shown In bellow given example.
package Testng_Pack;
import
import
import
import
import

org.openqa.selenium.By;
org.openqa.selenium.WebDriver;
org.openqa.selenium.firefox.FirefoxDriver;
org.testng.annotations.AfterTest;
org.testng.annotations.BeforeTest;

import org.testng.annotations.Test;

public class Common_Functions_Test extends CommonFunctions{


WebDriver driver;
@BeforeTest
public void StartBrowser_NavURL() {
driver = new FirefoxDriver();
driver.get("http://only-testing-blog.blogspot.in/2014/05/form.html");
}
@AfterTest
public void CloseBrowser() {
driver.quit();
}
@Test
public void testToCompareIntegers(){
String actualValString = driver.findElement(By.xpath("//*[@id='postbody-8228718889842861683']/div[1]/table/tbody/tr[1]/td[2]")).getText();
//To convert actual value string to Integer value.
int actualVal = Integer.parseInt(actualValString);
//Call compareIntegerVals method Inside If condition to check Integer
values match or not.
if(compareIntegerVals(actualVal, 5)){
//If values match, This block will be executed.
System.out.println("Write Action taking lines In this block when Values
match.");
}else{
//If values not match, This block will be executed.
System.out.println("Write Action taking lines In this block when Values
not match.");
}
//To mark test fail In report at the end of execution If values not match.
Soft_Assert.assertAll();
}
}
20.3 Common Function To Compare Two Doubles
Common Function To Compare Two Double Values In Selenium WebDriver
Comparison of double values Is not much more different than comparison
of Integer values as described In my PREVIOUS POST but let me give you
example of same so that you can get It better. Let me tell you one thing
that comparison of different data types (compare two strings, compare
two Integers, etc..) Is

pure java concept and It has not any relation with selenium webdriver. My
main Intention Is to show you that how to handle rest of test execution
based on execution result and how to mark your test fail In webdriver test
report without any Interruption In execution.
Let me try to describe you how to compare two double values with
example.
As explained In my previous post, If you are retrieving value from web
page then It will be always In string format because webdriver's .getText()
function Is returning It as a string. So my first task Is to convert It from
string to double using bellow given syntax.
String actualValString = driver.findElement(By.xpath("//*[@id='post-body4292417847084983089']/div[1]/table/tbody/tr[2]/td[4]")).getText();
//To convert actual value string to Double value.
double actualVal = Double.parseDouble(actualValString);
Second task Is to create general function In CommonFunctions class to
compare two double values. Latter on I will use this function whenever
required In my test. Main work of this function Is to accept two double
values then compare them and return true or false based on comparison
result. See bellow given example.
package Testng_Pack;
import org.testng.Assert;
import org.testng.asserts.SoftAssert;
public class CommonFunctions {
SoftAssert Soft_Assert = new SoftAssert();
public boolean compareDoubleVals(double actualDobVal, double
expectedDobVal){
try{
//If this assertion will fail, It will throw exception and catch block will be
executed.
Assert.assertEquals(actualDobVal, expectedDobVal);
}catch(Throwable t){
//This will throw soft assertion to keep continue your execution even
assertion failure.
//Un-comment bellow given hard assertion line and commnet soft
assertion line If you wants to stop test execution on assertion failure.
//Assert.fail("Actual Value '"+actualDobVal+"' And Expected Value
'"+expectedDobVal+"' Do Not Match.");
Soft_Assert.fail("Actual Value '"+actualDobVal+"' And Expected Value
'"+expectedDobVal+"' Do Not Match.");

//If double values will not match, return false.


return false;
}
//If double values match, return true.
return true;
}
}
Now I can use compareDoubleVals function In my test whenever required
as described In bellow given example.
package Testng_Pack;
import
import
import
import
import
import

org.openqa.selenium.By;
org.openqa.selenium.WebDriver;
org.openqa.selenium.firefox.FirefoxDriver;
org.testng.annotations.AfterTest;
org.testng.annotations.BeforeTest;
org.testng.annotations.Test;

public class Common_Functions_Test extends CommonFunctions{


WebDriver driver;
@BeforeTest
public void StartBrowser_NavURL() {
driver = new FirefoxDriver();
driver.get("http://only-testing-blog.blogspot.in/2014/01/textbox.html");
}
@AfterTest
public void CloseBrowser() {
driver.quit();
}
@Test
public void testToCompareDoubles(){
String actualValString = driver.findElement(By.xpath("//*[@id='postbody-4292417847084983089']/div[1]/table/tbody/tr[2]/td[4]")).getText();
//To convert actual value string to Double value.
double actualVal = Double.parseDouble(actualValString);
//Call compareDoubleVals method Inside If condition to check Double
values match or not.
if(compareDoubleVals(actualVal, 20.63)){
//If values match, This block will be executed.
System.out.println("Write Action taking lines In this block when Values
match.");
}else{

//If values not match, This block will be executed.


System.out.println("Write Action taking lines In this block when Values
not match.");
}
//To mark test fail In report at the end of execution If values not match.
Soft_Assert.assertAll();
}
}
Above test will call compareDoubleVals function and It will return false
because actual and expected values will not match. So test will be marked
as fail. You can use hard assertion too Inside compareDoubleVals function
to stop your test on assertion failure.

Anda mungkin juga menyukai