Selenium Webdriver Tutorials
Selenium Webdriver Tutorials
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
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
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.
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
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.
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.
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};
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.
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;
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.
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.
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;
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.
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
You can not use access modifiers with local variables because they
are limited to that method or constructor block only.
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.
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.
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.
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.
constructor
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
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.
Any class can Implement Interface but can not extend Interface.
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() {
java.io.BufferedReader;
java.io.BufferedWriter;
java.io.File;
java.io.FileReader;
java.io.FileWriter;
java.io.IOException;
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.
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
Selenium RC
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.
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.
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.
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'.
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 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
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
Now you are ready to run your script from Run menu as shown bellow.
Script Explanation
Above script will
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
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.
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.
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;
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;
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.
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
org.junit.After;
org.junit.Before;
org.junit.Test;
org.openqa.selenium.*;
org.openqa.selenium.firefox.FirefoxDriver;
}
@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
Same
as @Before
annotation, Test
method
marked
with
@After annotation will be executed after the each @Test method.
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;
@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
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.
because
because
we
have
there
placed
was
not
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.
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.
Now build file configuration is finished and finally you are ready to
run your build.xml file and generate your test report.
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.
View my Next Post to see how to configure and run build.xml file to
generate your test case report in HTML view.
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
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;
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.
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.
}
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.
Select By Value
Select By Index
Deselect by Value
Deselect by Index
Deselect All
isMultiple()
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();
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;
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;
}
@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;
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.
}
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;
//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.
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.
@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
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;
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']"));
}
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("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
@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);
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;
@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;
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;
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;
@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.
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;
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.
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;
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;
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;
@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.
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.
}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,
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.
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;
@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.
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;
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.
It will open New wizard. Expand General folder In New wizard and select
File and click on Next 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.
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;
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.
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
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.
{
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.
On completion of zip folder download, extract that zip folder. You will
find jxl.jar file inside it.
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);
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
Select By Value
Select By Index
Deselect by Value
Deselect by Index
Deselect All
isMultiple()
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.
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;
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
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;
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;
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 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;
}
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
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
findElements() method
Click Here to go to log4j jar file downloading page. (This Link URL
may change in future).
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.
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.
Now your properties folder under project folder will looks like bellow.
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.
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.
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;
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
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 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.
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.
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.
Select TestNg from New wizard window and click on Next button.
It will run your webdriver test with TestNG. When execution completed,
You will see result 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
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> : 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.
<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.
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
org.openqa.selenium.WebDriver;
org.openqa.selenium.firefox.FirefoxDriver;
org.testng.annotations.AfterSuite;
org.testng.annotations.BeforeSuite;
}
}
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");
}
}
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
"TestNGOnePack"
with
classes
and ClassTwo.java
exactly
as
are
webdriver
inherited
instance,
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.
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 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.
testmethodone()
and testmethodtwo()
from TestNGTwoPack -> ClassTwo.java
methods
testmethodone()
and
testmethodtwo()
from TestNGThreePack -> ClassOne.java
methods
testmethodone()
and
testmethodtwo()
from TestNGThreePack -> ClassTwo.java
methods
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.
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;
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;
@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
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();
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 :
org.openqa.selenium.By;
org.testng.Assert;
org.testng.annotations.BeforeClass;
org.testng.annotations.Test;
}
//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.
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
@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.
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.
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;
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.
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.
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;
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.");
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;