Professional Documents
Culture Documents
Webdriver Tutorials PDF
Webdriver Tutorials PDF
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
Soft Assertion
20.4 Applying TestNG Soft Assertion With Example
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.
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 d1 = 56.2354;
double d2 = 12456;
char datatype
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 :
Created bellow given example for all these datatypes. Run it in your
eclipse and verify results.
Bellow given result will display in your console at the end of execution.
If you don't know, Let me tell you that we have to work with strings very
frequently In selenium WebDriver tests. So you must have knowledge of
useful functions of String class to use them In your selenium webdriver
test development. Let us take simple example of String to understand
different methods of String class.
//Comparing two strings. Return true If both match else return false.
System.out.println("st1 equals to st2? -> "+st1.equals(st2));
//Split string.
String splt[] = st1.split("Very");
System.out.println("String Part 1 Is -> "+splt[0]);
System.out.println("String Part 2 Is -> "+splt[1]);
//Trim String.
System.out.println("Trimmed st2 -> "+st2.trim());
}
}
Length Of String
st1.length() will return lenght of string st1.
Split String
String splt[] = st1.split("Very") will split string st1 from word 'Very' and
store both strings In array.
Trim String
If string has white space at beginning or end of the string then you can
use trim function like st2.trim() to remove that white space.
if, if else and nested if else statements are useful to take the decision
based on conditional match.When you wants to execute some part of code
if condition returns true then you need to use this kind of conditional
statements.
Simple If Statement
Part of code will be executed only if specified condition returns true. If
condition will return false then that code will be not executed.
Example :
if (i<j)
System.out.println("Value Of i("+i+") Is Smaller Than Value Of j("+j+")." );
In above given example, message will be printed only and only if value of
variable i is less than value of variable j.
If else Statement
If condition returns true then part of if block will be executed. If condition
returns false then part of else block will be executed.
Example :
if (i>=j)
{
System.out.println("Value Of i("+i+") Is Greater Than Or Equals To Value
Of j("+j+")." );
}else
{
System.out.println("Value Of i("+i+") Is Smaller Than Value Of j("+j+")." );
}
In above given example, if block's message will be printed if value of
variable i is greater than or equals to value of variable j. else block will be
executed if value of variable i is less than value of variable j.
if (k<i)
{
System.out.println("Value Of k("+k+") Is Less Than Value Of i("+i+")" );
}else if (k>=i && k<=j)
{
System.out.println("Value Of k("+k+") Is In Between Value Of i("+i+") And
Value Of Value Of j("+j+")" );
}else
{
System.out.println("Value Of k("+k+") Is Greater Than Value Of
j("+j+")" );
}
In above given example, first (if) block will be executed if value of variable
k is less than the value of variable i. Second (else if) block will be executed
if value of variable k is greater than or equals to value of variable i and
less than or equals to value of variable j. Third (else) block will be
executed if value of variable k is greater than value of value of variable j.
You can make a chain of if else statement if you wants to check more
conditions.
This way, You can use any of above conditional statement based on your
requirement. Run bellow given example in your eclipse by changing the
values of variables.
public class IfStatements {
int i = 25;
int j = 50;
int k = 24;
//Simple If statement
System.out.println("***Simple If Statement Example***");
if (i<j) //Bellow given message will be printed only if value of variable i is
less than value of variable j.
System.out.println("Value Of i("+i+") Is Smaller Than Value Of
j("+j+")." );
Bellow given output will be printed in your eclipse console when you will
run above example.
Let me describe you for loop in this post and you can view my NEXT POST
for reading about while loop.
for Loop
There are three parts inside for loop. 1. Variable Initialization, 2. Condition
To Terminate and 3. Increment/Decrements variable. for loop will be
terminated when condition to terminate will becomes false.
Example :
for(int i=0; i<=3; i++){
System.out.println("Value Of Variable i is " +i);
}
Bellow given example is simple example of for loop. run it in your eclipse
and verify the result.
System.out.println("");
int i=0;
int k = 200;
for(int j=3; j>=i; j--){ //This loop will be executed 4 times
System.out.println("Value Of Variable j is " +j);
k = k-10;
}
System.out.println("");
System.out.println("Value Of Variable k is " +k);
When you will run above given example, you will get bellow given output.
Value Of Variable i is 0
Value Of Variable i is 1
Value Of Variable i is 2
Value Of Variable i is 3
Value Of Variable j is 3
Value Of Variable j is 2
Value Of Variable j is 1
Value Of Variable j is 0
while Loop
Block of code which is written inside while loop will be executed till the
condition of while loop remains true.
Example :
int i = 0;
while(i<=3){
System.out.println("Value Of Variable i Is "+i);
i++;
}
In above given example, while loop will be executed four times.
do while Loop
Same as while loop, do while loop will be executed till the condition
returns true.
Example :
int j=0;
do{
System.out.println("Value Of Variable j Is "+j);
j=j-1;
}while(j>0);
In above given example, while loop will be executed only one time.
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.
int i = 0;
while(i<=3){
System.out.println("Value Of Variable i Is "+i);
}
Above given while loop will be executed infinite time because variable is
not incremented inside while loop block.
Bellow given full example of while and do while loops will clear out your all
doubts. Simple run it in your eclipse and verify result.
public class Whileloop {
public static void main(String[] args) {
//do while loop - will be executed minimum one time without considering
condition.
System.out.println("");
System.out.println("***do while loop example***");
int j=3; //Variable initialization
do{
System.out.println("Value Of Variable j Is "+j);
j=j-1;//Decrementing value of j by 1;
}while(j>=0);
}
}
What is Array?
As we have learnt in my post about DIFFERENT DATA TYPES, We can store
values in variables based on type of data like int i=5; double d = 12.254;
etc. Now if you wants to store multiple values (10 or 15 or more different
values) in different variables then it will be overhead for you to create and
initialize different
variables for each value. In this situation, you can use array to store
multiple different values in array. An array can store multiple value of
same data type(int, char, String) at the same time and each stored data
location has unique Index. There are two types of array as bellow.
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 {
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
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 {
When you will run this example in eclipse, It will return bellow given result
in console.
User1
Password1
User2
Password2
User3
Password3
7. Methods In Java
What Is Method?
In Selenium webdriver test suite, You need to perform some actions
multiple time or in multiple test cases like Login in to Account, Place Order
or any other action. If you will write this kind of (same repeated) actions In
all the test cases then It will becomes overhead for you and will Increase
size of your code.
Instead of that, If you create methods for this kind of operations and then
call that method whenever required then It will be very easy to maintain
your test cases.
public static void Test1(){ //Simple Method - Called from main method.
System.out.println("Test1 Method Executed.");
}
public static void Test2(){ //Simple Method - Not called from main
method.
System.out.println("Test2 Method Executed.");
}
If you will run above example then console output will looks like bellow.
Test1 Method Executed.
As per the console output, We can say that Test1() method is executed but
Test2() method is not executed because It Is not called from main method.
Methods will have bellow given different components.
2. Return Type Of Method : Any method can have return types like int,
String, double etc.. based on returning value's data type. void means
method is not returning any value.
VIEW EXAMPLE OF RETURN TYPE
Example :
3. Static or non static method : Method can be static or non static. If you
wants to keep your method as static then you need to use static keyword
with method. If you wants to create non static method then do not write
static keyword with method. VIEW FULL DESCRIPTION ON STATIC AND
NON STATIC.
Example :
4. Method Name : You can give any name to your method. Always use
method name relative to its functional work.
Example :
public static void Login(String user, String Pass){ //Login is the method
name.
//Block of code
}
Access modifiers are the keywords in java by which we can set the level of
access for class, methods, variables and constructors. There are 4
different access modifiers available in java. Now let me try to describe you
how can we use them to set the access for the methods and variables.
First of all let me tell you
meaning of each access modifier keyword and then will give you examples
for them.
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;
//Method with private access modifier. Can be accessible from same class
only.
private static void Testing_pri(){
System.out.println("Testing_pri() Executed");
}
package Test_Package1;
System.out.println();
System.out.println("Value Of i Is "+Accessmodif.i); //Can access public
variables outside the class or package.
//System.out.println("Value Of str Is "+Accessmodif.str); - Can not access
private variables outside the class
System.out.println("Value Of d Is "+Accessmodif.d); //Can access
protected variables inside same package class.
System.out.println("Value Of c Is "+Accessmodif.c); //Can access no
modifier variables inside same package class.
}
}
package Test_Package2;
import Test_Package1.Accessmodif;
System.out.println();
System.out.println("Value Of i Is "+i); //Can access public variables
outside the package.
//System.out.println("Value Of str Is "+str); - Can not access private
variables outside the class.
System.out.println("Value Of d Is "+d); //Can access protected variables
inside child class.
//System.out.println("Value Of c Is "+c); - Can not access no access
modifier variables outside the package.
}
}
As per above example, Now its clear that based on access modifiers, we
can access variables, methods, etc.. in any other package or class. If you
will un comment the commented methods or variables from above given
classes, It will show you error related to access level.
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;
static int c;
static double d;
public static void main(String[] args) {
Mul(2,3);
Div(7,3);
System.out.println("Value of c Is "+c);
System.out.println("Value of d Is "+d);
Message();
}
//This method is returning integer value. It's return type is int.
public static int Mul(int a, int b){
c=a*b;
return c;
}
//This method is returning double value. It's return type is double.
public static double Div(double a, double b){
d=a/b;
return d;
}
//This method is returning nothing so there is used void return type.
public static void Message(){
System.out.println("Test Message");
}
}
If you see in above example, I have used three methods (Mul, Div and
Message) and called all three methods in main method to execute them.
Method Mul is returning multiplied integer value in variable c so I
have used int data type as return type with Mul method.
Java Tutorials For Selenium WebDriver - Static And Non Static Methods
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.
package Test_Package1;
public class static_nonstatic {
//Can not access non static variables directly inside static method.
//System.out.println("Main static method : wheels = "+price);
//Can not access non static methods directly inside static method.
//byke2();
//Created object of class to access non static stuff Inside static method.
static_nonstatic sn = new static_nonstatic();
//Now We can access non static methods of class Inside static methods
using object reference.
sn.byke2();
//Now We can access non static variables of class Inside static methods
using object reference.
System.out.println("Main static method : price = "+sn.price);
//Can not access non static variables directly inside static method.
//System.out.println(price);
//Can access non static variable directly inside non static method.
System.out.println("byke2 Non static method : price = "+price);
//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);
//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.
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..
}
//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.
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 {
1. Local Variables
You can not use access modifiers with local variables because they
are limited to that method or constructor block only.
Need to initialize the value of local variables before using It because
there Is not any default value assigned to local variables.
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.
//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";
}
Console output will looks like bellow.
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.
We can do same thing using single object creation too using this()
keyword as bellow.
Till now we have learnt many tutorials on java like Methods, Access
Modifiers, Static and Non Static, Object, Constructor, and Many More
Tutorials On Java... All these java object oriented concept tutorials are very
much useful in selenium webdriver test case development. That's why I
recommend you all
to learn them very carefully. All these tutorials will also helps you to pass
selenium webdriver Interview. Now let me take you one step ahead to
Inheritance In java.
extends keyword Is used to Inherit child class from parent class. Let me
show you very simple example of Inheritance In java. In this example, Car
class Is parent class of Audi class so all the non private properties of Car
class are Inherited and able to use In Audi class.
Parent Class
Wheels Of Audi = 4
Speed Of Audi = 150
Car Seats = 4
Color Of Audi = blue
Fuel Of Audi = Petrol
If you will study above example carefully, You can understand It easily that
In child class, we can access only non private members of parent class.
This Is just basic example of Inheritance In Java.
Overriding
In sub class, When you create a method with same signature, return types
and arguments of parent class's method then that sub class's method Is
known as overridden method and It Is called as overriding In java.
Overriding Is useful to change to the behavior of parent class methods.
Let me show you simple example of method overriding In java.
Consider same above given example. Generally all cars have 4 seats so
we have created Seats() method with 4 seat variable. But supposing ford
car has 6 seats and I wants to print 6 seats for Ford car. In this case we
can use method overriding In Ford class as bellow. For this example,
Consider Car class of above example as parent class of Ford class. Here
method Seats() Is overridden In sub class.
public class Ford extends Car{//Ford Is child Class Of Car Class.
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.
Any class can Implement Interface but can not extend Interface.
College.java
Computer.java
@Override
public void StudentResult() {
System.out.println("Computer Dept. Student Result Part");
}
}
Mechanical.java
@Override
public void StudentDetails() {
System.out.println("Mechanical Dept. Student Detail Part");
}
@Override
public void StudentResult() {
System.out.println("Mechanical Dept. Student Result Part");
}
}
TestCollege.java
Now If you will run TestCollege.java file, Output will looks like bellow.
In THIS POST, I have described about one and two dimensional array In
Java. Then question Is what Is arraylist In java and why we need It?
Interviewer can ask you this question then you can give him answer like :
arraylist Is a class that Implements list Interface In java which supports
dynamic array means size of
array can grow as needed. As you know, We can create only fixed size
array to store values Inside It and that Is the limitation/drawback of array
because when you don't know how many values you needs to store In
array then how can you provide/define size of array? ArrayList helps us to
overcome this limitation of array because It can re-size automatically by
Itself.
So finally we can say that when you don't know how many values you
have to store In array, You can use ArrayList at place of simple array. We
have to use arraylist many times In our selenium webdriver test case
development. Example : Store all links from page, store all buttons Id from
page etc.. In all such case, You will not aware about how many values you
have to store.
VIEW NEXT POST to learn about hashtable In Java for selenium webdriver
Bellow given example will show you how to create and work with arraylist
class In java. Same thing we will use In selenium WebDriver test case
development to store values.
System.out.println("*************************");
//To get the Index of an Item from arraylist.
int ItemIndex = Sample.indexOf("button3");
System.out.println("Index Of button3 Item = "+ItemIndex);
System.out.println("*************************");
What Is Hashtable?
Hashtable Is a class In java and provides us a structure to store key and its
value as a pair In table format. Means we can store value with Its key and
can access that value using Its key. There Is not any Index of value In
Hashtable. Key's Hashcode will be used to map the value with key In
Heshtable. Let me show you very simple example of Hashtable.
Need More Tutorials On Java And Selenium WebDriver? VISIT THIS PAGE
It Is very easy to Create, Write and read text file In java. We can use java
built in class File to create new file, FileWriter and BufferedWriter class to
write In to file, FileReader and BufferedReader class to read text file.
Bellow given example will first of all create temp.txt file In D: drive and
then write two line In to It. Then It will read both lines one by one from
text file using while loop and print In console. You can use bellow given
example code for reading or writing text file In your selenium webdriver
test case whenever needed.
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
//Writing In to file.
//Create Object of java FileWriter and BufferedWriter class.
FileWriter FW = new FileWriter(TestFile);
BufferedWriter BW = new BufferedWriter(FW);
BW.write("This Is First Line."); //Writing In To File.
BW.newLine();//To write next string on new line.
BW.write("This Is Second Line."); //Writing In To File.
BW.close();
//Loop to read all lines one by one from file and print It.
while((Content = BR.readLine())!= null){
System.out.println(Content);
}
}
}
This way we can read and write text file In java for your selenium
webdriver test case development.
Anyone don't like exceptions and at the same time, anyone can not hide
himself from exceptions when running webdriver tests because (What Is
An Exception? :->) exception Is an error event generated during the
execution of webdriver test case or java program which disrupts test
execution In between. Exception
can arise due to the many reasons like, network connection or hardware
failure, Invalid data entered by user, DB server down etc.. So all these
things can happens any time when you run your selenium webdriver test
case and we can not stop It. So Instead of thinking about stopping
exception(Which Is not possible) during run time, Think about handling
exceptions. Java provides very good exception handling mechanism to
recover from this kind of errors. Let us learn different ways of handling
exception In java.
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.
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.
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");
}
}
}
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 2 supports most of all browsers to run your test cases and many
programming languages like C#, Java, Python, Ruby, .Net, Perl, PHP, etc..
to create and modify your test scripts. Selenium 2(WebDriver) controls
browser directly from operating system level so it is interacting very fast
and with more realistic way with browsers. Major people in world using
Selenium webdriver with java.
WebDriver
Selenium RC
Click here to read more about WebDriver. You can read my next post
about selenium webdriver download install.
(Do you wants to be master of selenium IDE in just 7 days? If yes then
Read this Selenium IDE tutorials)
addLocationStrategy
addLocationStrategyAndWait
addScript
addScriptAndWait
addSelection
addSelectionAndWait
allowNativeXpath
allowNativeXpathAndWait
altKeyDown
altKeyDownAndWait
altKeyUp
altKeyUpAndWait
answerOnNextPrompt
assertAlert
assertAlertNotPresent
assertAlertPresent
assertAllButtons
assertAllFields
assertAllLinks
assertAllWindowIds
assertAllWindowNames
assertAllWindowTitles
assertAttribute
assertAttributeFromAllWindows
assertBodyText
assertChecked
assertConfirmation
assertConfirmationNotPresent
assertConfirmationPresent
assertCookie
assertCookieByName
assertCookieNotPresent
assertCookiePresent
assertCursorPosition
assertEditable
assertElementHeight
assertElementIndex
assertElementNotPresent
assertElementPositionLeft
assertElementPositionTop
assertElementPresent
assertElementWidth
assertEval
assertExpression
assertHtmlSource
assertLocation
assertMouseSpeed
assertNotAlert
assertNotAllButtons
assertNotAllFields
assertNotAllLinks
assertNotAllWindowIds
assertNotAllWindowNames
assertNotAllWindowTitles
assertNotAttribute
assertNotAttributeFromAllWindows
assertNotBodyText
assertNotChecked
assertNotConfirmation
assertNotCookie
assertNotCookieByName
assertNotCursorPosition
assertNotEditable
assertNotElementHeight
assertNotElementIndex
assertNotElementPositionLeft
assertNotElementPositionTop
assertNotElementWidth
assertNotEval
assertNotExpression
assertNotHtmlSource
assertNotLocation
assertNotMouseSpeed
assertNotOrdered
assertNotPrompt
assertNotSelectOptions
assertNotSelectedId
assertNotSelectedIds
assertNotSelectedIndex
assertNotSelectedIndexes
assertNotSelectedLabel
assertNotSelectedLabels
assertNotSelectedValue
assertNotSelectedValues
assertNotSomethingSelected
assertNotSpeed
assertNotTable
assertNotText
assertNotTitle
assertNotValue
assertNotVisible
assertNotWhetherThisFrameMatchFrameExpression
assertNotWhetherThisWindowMatchWindowExpression
assertNotXpathCount
assertOrdered
assertPrompt
assertPromptNotPresent
assertPromptPresent
assertSelectOptions
assertSelectedId
assertSelectedIds
assertSelectedIndex
assertSelectedIndexes
assertSelectedLabel
assertSelectedLabels
assertSelectedValue
assertSelectedValues
assertSomethingSelected
assertSpeed
assertTable
assertText
assertTextNotPresent
assertTextPresent
assertTitle
assertValue
assertVisible
assertWhetherThisFrameMatchFrameExpression
assertWhetherThisWindowMatchWindowExpression
assertXpathCount
assignId
assignIdAndWait
break
captureEntirePageScreenshot
captureEntirePageScreenshotAndWait
check
checkAndWait
chooseCancelOnNextConfirmation
chooseOkOnNextConfirmation
chooseOkOnNextConfirmationAndWait
click
clickAndWait
clickAt
clickAtAndWait
close
contextMenu
contextMenuAndWait
contextMenuAt
contextMenuAtAndWait
controlKeyDown
controlKeyDownAndWait
controlKeyUp
controlKeyUpAndWait
createCookie
createCookieAndWait
deleteAllVisibleCookies
deleteAllVisibleCookiesAndWait
deleteCookie
deleteCookieAndWait
deselectPopUp
deselectPopUpAndWait
doubleClick
doubleClickAndWait
doubleClickAt
doubleClickAtAndWait
dragAndDrop
dragAndDropAndWait
dragAndDropToObject
dragAndDropToObjectAndWait
dragdrop
dragdropAndWait
echo
fireEvent
fireEventAndWait
focus
focusAndWait
goBack
goBackAndWait
highlight
highlightAndWait
ignoreAttributesWithoutValue
ignoreAttributesWithoutValueAndWait
keyDown
keyDownAndWait
keyPress
keyPressAndWait
keyUp
keyUpAndWait
metaKeyDown
metaKeyDownAndWait
metaKeyUp
metaKeyUpAndWait
mouseDown
mouseDownAndWait
mouseDownAt
mouseDownAtAndWait
mouseDownRight
mouseDownRightAndWait
mouseDownRightAt
mouseDownRightAtAndWait
mouseMove
mouseMoveAndWait
mouseMoveAt
mouseMoveAtAndWait
mouseOut
mouseOutAndWait
mouseOver
mouseOverAndWait
mouseUp
mouseUpAndWait
mouseUpAt
mouseUpAtAndWait
mouseUpRight
mouseUpRightAndWait
mouseUpRightAt
mouseUpRightAtAndWait
open
openWindow
openWindowAndWait
pause
refresh
refreshAndWait
removeAllSelections
removeAllSelectionsAndWait
removeScript
removeScriptAndWait
removeSelection
removeSelectionAndWait
rollup
rollupAndWait
runScript
runScriptAndWait
select
selectAndWait
selectFrame
selectPopUp
selectPopUpAndWait
selectWindow
sendKeys
setBrowserLogLevel
setBrowserLogLevelAndWait
setCursorPosition
setCursorPositionAndWait
setMouseSpeed
setMouseSpeedAndWait
setSpeed
setSpeedAndWait
setTimeout
shiftKeyDown
shiftKeyDownAndWait
shiftKeyUp
shiftKeyUpAndWait
store
storeAlert
storeAlertPresent
storeAllButtons
storeAllFields
storeAllLinks
storeAllWindowIds
storeAllWindowNames
storeAllWindowTitles
storeAttribute
storeAttributeFromAllWindows
storeBodyText
storeChecked
storeConfirmation
storeConfirmationPresent
storeCookie
storeCookieByName
storeCookiePresent
storeCursorPosition
storeEditable
storeElementHeight
storeElementIndex
storeElementPositionLeft
storeElementPositionTop
storeElementPresent
storeElementWidth
storeEval
storeExpression
storeHtmlSource
storeLocation
storeMouseSpeed
storeOrdered
storePrompt
storePromptPresent
storeSelectOptions
storeSelectedId
storeSelectedIds
storeSelectedIndex
storeSelectedIndexes
storeSelectedLabel
storeSelectedLabels
storeSelectedValue
storeSelectedValues
storeSomethingSelected
storeSpeed
storeTable
storeText
storeTextPresent
storeTitle
storeValue
storeVisible
storeWhetherThisFrameMatchFrameExpression
storeWhetherThisWindowMatchWindowExpression
storeXpathCount
submit
submitAndWait
type
typeAndWait
typeKeys
typeKeysAndWait
uncheck
How to download and install Selenium Webdriver with Eclipse and Java
Step By Step
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.
Downloaded 'webDriver Java client driver' will be in zip format. Extract and
save it in your system at path D:\selenium-2.33.0. There will be 'libs'
folder, 2 jar files and change log in unzipped folder as shown in bellow
figure. We will use all these files for configuring webdriver in eclipse.
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.
Create new package
Right click on project name 'testproject' and select New > Package. Give
your package name = 'mytestpack' and click on finish button. It will add
new package with name 'mytestpack' under project name 'testproject'.
Right click on package 'mytestpack' and select New > Class and set class
name = 'mytestclass' and click on Finish button. It will add new class
'mytestclass' under package 'mytestpack'.
Now your Eclipse window will looks like bellow.
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.
Now you are ready to run your script from Run menu as shown bellow.
Script Explanation
Above script will
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
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.
Generally you do not need to install junit with eclipse if you have already
added external jar files of webdriver with eclipse. Because required jar file
for junit will be already there with webdriver jar files.
How to verify that required jar file for junit is in my build path or not
For junit jar file verification, Right click on your project -> Build Path ->
Configure build path
It will open java build path window as shown in bellow image. In that
window, go to Libraries tab. Here you will see all your jar files. In jar file
tree view, look for the jar file name which is starting with junit.
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.
Now you are ready to use junit with eclipse for your webdriver test of
software application. Click here to view all articles on webdriver.
Creating and running webdriver test with junit and eclipse step by step
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.
package Testjunit;
import org.junit.Test;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
@Test
public void test() {
driver.manage().window().maximize();
System.out.print("Window maximise");
driver.get("http://only-testing-blog.blogspot.in/");
System.out.print("Site Open");
driver.quit();
System.out.print("End of Test");
}
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.
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.
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
@Test
public void test() throws InterruptedException {
driver.manage().window().maximize();
driver.get("http://only-testing-blog.blogspot.in/2013/11/new-test.html");
driver.findElement(By.xpath("//input[@name='fname']")).sendKeys("junitte
st1 executed");
Thread.sleep(2000);
System.out.print("junittest1 class is executed");
driver.quit();
}
}
Step 3 - Create 2nd test case
Same way, Create 2nd test class with name = junittest2 under package =
junitpack as bellow.
package junitpack;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.Ignore;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
@Before
public void setup () {
driver.manage().window().maximize();
driver.get("http://only-testing-blog.blogspot.in/2013/11/new-test.html");
}
@After
public void aftertest() {
driver.quit();
}
@Test
public void test1() throws InterruptedException{
driver.findElement(By.xpath("//input[@name='fname']")).sendKeys("junitte
st2 class-test1");
System.out.print("\njunittest2 class-test1 method is executed");
Thread.sleep(2000);
}
@Test
public void test2() throws InterruptedException {
driver.findElement(By.xpath("//input[@name='fname']")).sendKeys("junitte
st2 class-test2");
Thread.sleep(2000);
System.out.print("\njunittest2 class-test2 method is executed");
}
}
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.
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
1. @Before Annotation
As name suggest. method written under @Before annotation will be
executed before the method written under @Test annotation. Based on
@Before annotation, JUnit framework will execute that before method first.
Generally method under @Before annotation is used to initializing website
and other environment related setup. @Before annotation method will be
executed before each @Test annotation method means if there are two
@Test methods in your class then @Before method will be executed two
times.
2. @After
Method under @After annotation is known as after method and execution
of @After method will start as soon as completion of @Test method
execution completion. Same as @Before , @After annotation method will
be executed two times if there are two @Test methods in your class.
3. @Test
Method under @Test annotation is known as test method. Execution of
@Test method will start as soon as @Before method execution completed.
Generally we are writing all testing related activity under @Test. We can
use multiple @Test methods in single class too.
4. @BeforeClass
Methods under @BeforeClass annotation will be executed before the any
test method starts execution. It will be executed only once even if there
are multiple @Test methods in your class.
5. @AfterClass
@AfterClass method will be run on completion of all the test method's
execution from that class. Same as @BeforeClass, @AfterClass method
will be executed once only.
package Testjunit;
import java.util.concurrent.TimeUnit;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.*;
import org.openqa.selenium.firefox.FirefoxDriver;
@Before
public void beforetest() {
driver.manage().window().maximize();
driver.get("http://only-testing-blog.blogspot.in/2013/11/new-test.html");
}
@After
public void aftertest() {
driver.quit();
}
@Test
public void test() {
driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
driver.findElement(By.xpath("//input[@value='Bike']")).click();
boolean str1 =
driver.findElement(By.xpath("//input[@value='Bike']")).isSelected();
if(str1 = true) {
System.out.print("Checkbox is checked");
}
else
{
System.out.print("Checkbox is not checked");
}
}
Here @After method is written before @Test method but JUnit Framework
will tells eclipse to execute @Test method first and then @After method
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
@Before
public void openbrowser() {
System.out.print("\nBrowser open");
driver = new FirefoxDriver();
driver.manage().window().maximize();
driver.get("http://only-testing-blog.blogspot.in/2013/11/new-test.html");
}
@After
public void closebrowser() {
System.out.print("\nBrowser close");
driver.quit();
}
@Test
public void test1() throws InterruptedException{
driver.findElement(By.xpath("//input[@name='fname']")).sendKeys("junitte
st2 class-test1");
System.out.print("\njunittest2 class-test1 method is executed");
Thread.sleep(2000);
}
@Test
public void test2() throws InterruptedException {
driver.findElement(By.xpath("//input[@name='fname']")).clear();
driver.findElement(By.xpath("//input[@name='fname']")).sendKeys("junitte
st2 class-test2");
Thread.sleep(2000);
System.out.print("\njunittest2 class-test2 method is executed");
}
}
When you execute above example in eclipse, Bellow given result will be
displayed in console.
Console Output :
Browser open
junittest2 class-test1 method is executed
Browser close
Browser open
junittest2 class-test2 method is executed
Browser close
Based on above given console output, we can say each @Before method
is executed before each @Test method and each @After method is
executed after each @Test method. Now let we replace @Before
annotation with @BeforeClass and @After annotation with @AfterClass in
same example and then observe result. Replace bellow given
@BeforeClass and @AfterClass part with @Before and @After part in
above example as bellow.
@BeforeClass
public static void openbrowser() {
System.out.print("\nBrowser open");
driver = new FirefoxDriver();
driver.manage().window().maximize();
driver.get("http://only-testing-blog.blogspot.in/2013/11/new-test.html");
}
@AfterClass
public static void closebrowser() {
System.out.print("\nBrowser close");
driver.quit();
}
Now run above example and look at console result. Console result will be
as bellow.
Console Output :
Browser open
junittest2 class-test1 method is executed
junittest2 class-test2 method is executed
Browser close
@Ignore annotation
We can use JUnit's has inbuilt @Ignore annotation before @Test method to
Ignore that specific webdriver test from execution. Let we apply @Ignore
annotation practically in our test and then observe its execution result.
@Ignore
@Test
public void test1() throws InterruptedException{
}
driver.findElement(By.xpath("//input[@name='fname']")).sendKeys("junitte
st2 class-test1");
System.out.print("\njunittest2 class-test1 method is executed");
Thread.sleep(2000);
}
This way, Junit's @Ignore annotation will help us to ignore specific test
from execution.
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.
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();
}
Step 3 : Set Runtime JRE
Go to JRE tab. Here you need to set Runtime JRE = JDK at place of
JRE as shown in bellow image.
If JDK is not display in Separate JRE list then you can add it by
- Click on Installed JREs button. It will open Preferences dialog.
- Click on Add button from Preferences dialog. It will open Add JRE
dialog.
- Select Standard VM from Add JRE dialog and click on next button
as shown in bellow image.
On Next window, Select JDK folder path(Which is located at
C:\Program Files\Java\ in my system) In JRE home field and click on
Finish button. It will add JDK option in Separate JRE drop down.
Now build file configuration is finished and finally you are ready to
run your build.xml file and generate your test report.
Step 4 : Run build.xml
Now you can run build.xml file in 3 ways.
1st way : Run from External Tools Configuration dialog as shown.
2nd way : Run directly from build.xml file
3rd way : Run from Menu icons
Step 5 : View Report
When you run build.xml file, eclipse will run your junit test case and
on completion of execution report file will be generated in your junit
folder which is located in your project folder as bellow.
Open index.html file. It will looks like bellow.
Eclipse And Ant Configuration Steps To Generate webdriver test
execution report using JUnit : Part - 2
Webdriver test result generation is very important and essential part
of automation testing and for that you need to configure your
eclipse accordingly. Before eclipse and ant configuration, you need
to configure your system as described in Part - 1. Now let me
describe you the steps of eclipse configuration to generate web
driver test execution report using JUnit. Perform bellow given steps.
Step 1 : Create new JUnit Test Case
First of all, you need to create JUnit test case in eclipse as described
in JUnit Test Creation Post 1 and Post 2.
Step 2 : Set Ant Home Entries
To set ant home entries,
- Go to eclipse Menu -> Window -> Preferences. It will open eclipse
preference dialog.
- Select Ant -> Runtime from left side preference tree. Now select
Classpath at right side.
- Select 1st class path Ant Home Entries and click on Ant Home
button and select 'apache-ant-1.9.2' folder path and then click on
OK as shown in bellow image.
Step 3 : Set junit.jar path in Blobal Entries of Ant Runtime Preference
if it is not there
As described above, Go to Ant -> Runtime preference settings and
select Global Entries.
Now click on Add External Jars button and select 'junit.jar' located at
eclipse -> plugins -> org.junit_4.11.0.v201303080030 (This folder
name may be different if you have different version of junit) ->
junit.jar. and then click on OK as shown in bellow image.
Step 4 : Generate build.xml for your project
Now you need to generate build.xml for your project. To generate it,
Right click on your project folder and select Export. It will open
Export dialog as shown in bellow image.
Select Ant Buildfiles from export dialog and clicking on Next button
will show you all your projects list. On Next dialog, select your
current project and click on Finish button as shown bellow.
Look in above image. When you will run build.xml file, your test
reports will be saved in JUnit output directory = 'junit' folder. It will
be created automatically in your project folder when you run
build.xml file. We will learn how to run build.xml file in my next post.
When you click on Finish button, build.xml file will be generated
inside your project folder as shown bellow.
View my Next Post to see how to configure and run build.xml file to
generate your test case report in HTML view.
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
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.
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.
driver.findElement(By.id("submitButton"));
Bellow given example will show you how to locate element by id and then
how to click on it. Copy bellow given @Test method part and replace it
with the @Test method part of example given on this page.(Note : @Test
method is marked with pink color in that example).
@Test
public void test() {
driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
for (int i = 0; i<=20; i++)
{
WebElement btn = driver.findElement(By.id("submitButton"));//Locating
element by id
if (btn.isEnabled())
{
//if webelement's attribute found enabled then this code will be
executed.
System.out.print("\nCongr8s... Button is enabled and webdriver is
clicking on it now");
}
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();
}
}
}
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"));
@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.
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.
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.
driver.findElement(By.className("date-header"));
import java.util.concurrent.TimeUnit;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
@Before
public void beforetest() {
@After
public void aftertest() {
driver.quit();
@Test
public void test()
{
driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
String datentime = driver.findElement(By.className("date-
header")).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.
driver.findElement(By.tagName("select"));
@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);
}
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();
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.
}
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.
}
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.
}
As you know, Locators in selenium are main elements and CSS Locator is
another alternative of Xpath element locator, ID or Name locator or any
other element locators in selenium. Full form of CSS is "Cascading Style
Sheets" and it define that how to display HTML elements on webpage.
Click here to read more about CSS. There are few advantages and also few
disadvantages of using CSS element locators at
place of Xpath element locators in selenium.
Note : Need good working examples on selenium IDE? Visit this link for
great tutorials on selenium IDE.
Now let me come to our main point - How to write CSS locator syntax
manually for selenium. I have derived couple of CSS locator syntax with
example as bellow. I written CSS locator syntax for three elements(Search
text box, Select language drop down and "Go" button) of wikipedia
website home page as shown in bellow image.
CSS locator Examples
css=input[id=searchInput] \\\\ This syntax will find "input" tag node which
contains "id=searchInput" attribute.
(All three CSS path examples given above will locate Search text box.)
(All three CSS path examples given above will locate Search text box.)
I have already posted Selenium WebDrier Tutorials posts how to setup web
driver with eclipse and Run first test with webdriver, how to configure junit
with eclipse to generate webdriver test report. We have also learn
different methods of locating elements in webdriver. All these things are
very basic
things and you need to learn all of them before starting your test case
creation in selenium 2. Now we are ready to learn next step of performing
basic actions in web driver with java for your software web application.
VIEW STEP BY STEP TUTORIALS ON SELENIUM WEBDRIVER
driver.get("http://only-testing-blog.blogspot.in/2013/11/new-test.html");
This syntax will open specified URL in web browser. VIEW PRACTICAL
EXAMPLE OF OPEN URL
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
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
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
Select By Value
Select By Index
Deselect by Value
Deselect All
isMultiple()
driver.navigate().to("http://only-testing-
blog.blogspot.in/2014/01/textbox.html");
driver.navigate().back();
driver.navigate().forward();
1st command will navigate to specific URL, 2nd will navigate one step
back and 3rd command will navigate one step forward. VIEW PRACTICAL
EXAMPLES OF NAVIGATION COMMANDS.
Boolean iselementpresent =
driver.findElements(By.xpath("//input[@id='text2']")).size()!= 0;
It will return true if element is present on page, else it will return false in
variable iselementpresent. VIEW PRACTICAL EXAMPLE OF VERIFY ELEMENT
PRESENT.
File screenshot =
((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(screenshot, new File("D:\\screenshot.jpg"));
It will capture page screenshot and store it in your D: drive. VIEW
PRACTICAL EXAMPLE ON THIS PAGE.
2. Extract parent and child window handle from all window handles.
driver.switchTo().window(window2);
Above given steps with helps you to get window handle and then how to
switch from one window to another window. VIEW PRACTICAL EXAMPLE OF
HANDLING MULTIPLE WINDOWS IN WEBDRIVER
boolean fname =
driver.findElement(By.xpath("//input[@name='fname']")).isEnabled();
System.out.print(fname);
Above syntax will verify that element (text box) fname is enabled or not.
You can use it for any input element. VIEW PRACTICAL EXAMPLE OF VERIFY
ELEMENT IS ENABLED OR NOT.
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.
driver.findElement(By.xpath("//input[@name='Company']")).submit();
It will submit the form. VIEW PRACTICAL EXAMPLE OF SUBMIT FORM.
driver.switchTo().alert().accept();
To accept alert. VIEW PRACTICAL EXAMPLE OF ALERT ACCEPT
driver.switchTo().alert().dismiss();
To dismiss confirmation. VIEW PRACTICAL EXAMPLE OF CANCEL
CONFIRMATION
driver.switchTo().alert().sendKeys("This Is John");
To type text In text box of prompt popup.
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.
Run bellow given example In eclipse with testng and observe the result.
package Testng_Pack;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
@BeforeTest
public void setup() throws Exception {
driver =new FirefoxDriver();
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
driver.get("http://only-testing-blog.blogspot.in/2014/01/textbox.html");
}
@AfterTest
public void tearDown() throws Exception {
driver.quit();
}
@Test
public void Text() throws InterruptedException {
//Alert Pop up Handling.
driver.findElement(By.xpath("//input[@value='Show Me Alert']")).click();
//To locate alert.
Alert A1 = driver.switchTo().alert();
//To read the text from alert popup.
String Alert1 = A1.getText();
System.out.println(Alert1);
Thread.sleep(2000);
//To accept/Click Ok on alert popup.
A1.accept();
This way you can handle different kind of alerts very easily using Alert
Interface of selenium webdriver. NEXT POST will show you how to handle
unexpected alerts In selenium webdriver.
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.
Run bellow given example In eclipse with testng and observe the result.
package Testng_Pack;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
@BeforeTest
public void setup() throws Exception {
driver =new FirefoxDriver();
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
driver.get("http://only-testing-blog.blogspot.in/2014/06/alert_6.html");
}
@AfterTest
public void tearDown() throws Exception {
driver.quit();
}
@Test
public void Text() throws InterruptedException {
//To handle unexpected alert on page load.
try{
driver.switchTo().alert().dismiss();
}catch(Exception e){
System.out.println("unexpected alert not present");
}
driver.findElement(By.xpath("//input[@name='fname']")).sendKeys("fname
");
driver.findElement(By.xpath("//input[@name='lname']")).sendKeys("lname
");
driver.findElement(By.xpath("//input[@type='submit']")).click();
}
}
Above given webdriver code Is just for example. It Is just explaining the
way of using try catch block to handle unexpected alert. You can use such
try catch block In that area where you are facing unexpected alerts very
frequently.
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.
driver.findElement(By.className("date-header"));
import java.util.concurrent.TimeUnit;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
@Before
public void beforetest() {
@After
public void aftertest() {
driver.quit();
@Test
public void test()
{
driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
String datentime = driver.findElement(By.className("date-
header")).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.
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.
Locating UI Element By ID
If your webpage element has unique and static ID then you can locate
your page element by ID. Look in to bellow given image. You can verify
that your webelement has any id or not using the firebug.
In above image, Submit Query button has unique id = 'submitButton'. I
can use that id to locate button as bellow.
driver.findElement(By.id("submitButton"));
Bellow given example will show you how to locate element by id and then
how to click on it. Copy bellow given @Test method part and replace it
with the @Test method part of example given on this page.(Note : @Test
method is marked with pink color in that example).
@Test
public void test() {
driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
for (int i = 0; i<=20; i++)
{
WebElement btn = driver.findElement(By.id("submitButton"));//Locating
element by id
if (btn.isEnabled())
{
//if webelement's attribute found enabled then this code will be
executed.
System.out.print("\nCongr8s... Button is enabled and webdriver is
clicking on it now");
}
else
{
//if webelement's attribute found disabled then this code will be
executed.
System.out.print("\nSorry but Button is disabled right now..");
}
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
* Submitting Form Using .submit() Method
Submitting Form Using submit() Method Of Selenium WebDriver
You will find many forms In any website like Contact Us form, New User
Registration Form, Inquiry Form, LogIn Form etc.. Supposing you are
testing one site where you have to prepare Login form submission test
case In selenium webdriver then how will you do It? Simplest way Is
described In THIS POST. If you will
see In that example post, we have used .click() method to click on Login
button.
Selenium Webdriver has one special method to submit any form and that
method name Is submit(). submit() method works same as clicking on
submit button.
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 org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
@BeforeTest
public void setup() throws Exception {
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
driver.get("http://only-testing-blog.blogspot.in/2014/05/form.html");
}
@AfterTest
public void tearDown() throws Exception {
driver.quit();
}
@Test
public void LogIn_Test(){
driver.findElement(By.xpath("//input[@name='FirstName']")).sendKeys("M
yFName");
driver.findElement(By.xpath("//input[@name='LastName']")).sendKeys("M
yLName");
driver.findElement(By.xpath("//input[@name='EmailID']")).sendKeys("My
Email ID");
driver.findElement(By.xpath("//input[@name='MobNo']")).sendKeys("My
Mob No.");
driver.findElement(By.xpath("//input[@name='Company']")).sendKeys("My
Comp Name");
//To submit form.
//You can use any other Input field's(First Name, Last Name etc.) xpath
too In bellow given syntax.
driver.findElement(By.xpath("//input[@name='Company']")).submit();
String alrt = driver.switchTo().alert().getText();
driver.switchTo().alert().accept();
System.out.println(alrt);
}
}
Above example will simply submit the form and retrieve submission alert
to print. So this way we can use webdriver's submit method to submit any
form. You can try different form for your better understanding.
* Store Text Of Element
Element Locators In Selenium 2 or WebDriver - Locating Element By Tag
Name
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.
driver.findElement(By.tagName("select"));
@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);
}
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"));
@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
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.
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();
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.
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?
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;
Last 2 syntax will get current page URLs and Print it in console.
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.
Let me provide you simple example of how to get current page URL using
driver.getCurrentUrl(); and how to get domain name using
JavascriptExecutor.
Example : Get current URL of page and domain name in selenium
webdriver
Copy bellow given @Test method part of get current page URL using
javascript example and replace it with the @Test method part of example
given on THIS PAGE. (Note : @Test method is marked with pink color
in that linked page).
@Test
public void test ()
{
String CurrentURL = driver.getCurrentUrl();
System.out.println("My Current URL Is : "+CurrentURL);
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.
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.
Copy bellow given @Test method part of generate alert using javascript
example and replace it with the @Test method part of example given
on THIS PAGE. (Note : @Test method is marked with pink color in that
linked page).
Example 3 : JavascriptExecutor to generate alert in selenium webdriver
@Test
public void test () throws InterruptedException
{
//Generating Alert Using Javascript Executor
JavascriptExecutor javascript = (JavascriptExecutor) driver;
javascript.executeScript("alert('Test Case Execution Is started Now..');");
Thread.sleep(2000);
driver.switchTo().alert().accept();
}
In above example, Java Script Executor will simply execute the javascript
and generate alert. You can your own alert text in it. Try it in your own
software application test if required.
First of all let me show you difference between visible text, value and
index of list box option. Bellow given image will show you clear difference
between value, visible text and index.
1. Select Option By Value In WebDriver
Syntax for selecting option by value in webdriver is as bellow. First syntax
will locate the select element from page and 2nd syntax will select the
option from select box by value = Italy.
Select listbox = new
Select(driver.findElement(By.xpath("//select[@name='FromLB']")));
listbox.selectByValue("Italy");
Execute bellow given example in your eclipse and verify result. Try to use
it in different applications.
driver.findElement(By.xpath("//input[@value='->']")).click();
WebDriverWait wait = new WebDriverWait(driver, 15);
wait.until(ExpectedConditions.elementToBeClickable(By.id("text2")));
If you know, In selenium IDE we can select value from drop down list using
"select" or "addSelection" command. Now let me give you example of how
to select value from drop down list in webdriver.
Now we can use "Select" class to identify drop down from web page by
writing bellow given syntax.
Now we can select any value from selected drop down as bellow.
mydrpdwn.selectByVisibleText("Audi");
package junitreportpackage;
import java.util.concurrent.TimeUnit;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.Select;
import org.openqa.selenium.support.ui.WebDriverWait;
@Before
public void beforetest() {
driver.manage().window().maximize();
driver.get("http://only-testing-blog.blogspot.in/2014/01/textbox.html");
}
@After
public void aftertest() {
driver.quit();
@Test
public void test () throws InterruptedException
{
driver.findElement(By.id("text1")).sendKeys("My First Name");
}
Same thing we can do for list box to select option from list box by visible
text.
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.
driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
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.
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']")));
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.
@Test
public void test () throws InterruptedException
{
for (int i=1; i<6; i++)
{
Now you can easily select or deselect any specific option from select box
or drop down as described in my earlier POST 1, POST 2 and POST 3. All
these three posts will describe you different alternative ways of selecting
options from list box or drop down. Now let me take you one step ahead to
describe you the use
of deselectAll() and isMultiple() methods in selenium webdriver.
deselectAll() Method
deselectAll() method is useful to remove selection from all selected
options of select box. It will works with multiple select box when you need
to remove all selections. Syntax for deselectAll() method is as bellow.
Select listbox = new
Select(driver.findElement(By.xpath("//select[@name='FromLB']")));
listbox.deselectAll();
isMultiple() Method
isMultiple() method is useful to verify if targeted select box is multiple
select box or not means we can select multiple options from that select
box or not. It will return boolean (true or false) value. We can use it with if
condition before working with select box. Syntax is as bellow.
Select listbox = new
Select(driver.findElement(By.xpath("//select[@name='FromLB']")));
boolean value = listbox.isMultiple();
System.out.print(value);
Bellow given example will show you use of isMultiple() and deselectAll()
methods very clearly in selenium webdriver.
@Test
public void test () throws InterruptedException
{
Select listbox = new
Select(driver.findElement(By.xpath("//select[@name='FromLB']")));
//To verify that specific select box supports multiple select or not.
if(listbox.isMultiple())
{
System.out.print("Multiple selections is supported");
listbox.selectByVisibleText("USA");
listbox.selectByValue("Russia");
listbox.selectByIndex(5);
Thread.sleep(3000);
In above example, if condition will check that listbox is multiple select box
or not? Used listbox.deselectAll(); to remove all selected options.
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.
2. Deselect By Value
You can also deselect option from list box by value. 2nd syntax will
deselect option by value = Mexico.
3. Deselect By Index
Bellow given syntax will remove selection by index = 5.
Copy bellow given @Test method part of deselect option by visible text or
value or index and replace it with the @Test method part of example given
on THIS PAGE.(Note : @Test method is marked with pink color in that
linked page).
@Test
public void test () throws InterruptedException
{
driver.findElement(By.id("text1")).sendKeys("My First Name");
listbox.selectByValue("Japan");
listbox.selectByValue("Mexico");
Thread.sleep(1000);
listbox.selectByIndex(4);
listbox.selectByIndex(5);
Thread.sleep(1000);
//To deselect by index
listbox.deselectByIndex(5);
Thread.sleep(1000);
driver.findElement(By.xpath("//input[@value='->']")).click();
Thread.sleep(1000);
}
}
Let me try to describe you how to compare two double values with
example.
package Testng_Pack;
import org.testng.Assert;
import org.testng.asserts.SoftAssert;
public class CommonFunctions {
package Testng_Pack;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
@BeforeTest
public void StartBrowser_NavURL() {
driver = new FirefoxDriver();
driver.get("http://only-testing-blog.blogspot.in/2014/01/textbox.html");
}
@AfterTest
public void CloseBrowser() {
driver.quit();
}
@Test
public void testToCompareDoubles(){
String actualValString = driver.findElement(By.xpath("//*[@id='post-
body-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.
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;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
@BeforeTest
public void StartBrowser_NavURL() {
driver = new FirefoxDriver();
driver.get("http://only-testing-blog.blogspot.in/2014/05/form.html");
}
@AfterTest
public void CloseBrowser() {
driver.quit();
}
@Test
public void testToCompareIntegers(){
String actualValString = driver.findElement(By.xpath("//*[@id='post-
body-8228718889842861683']/div[1]/table/tbody/tr[1]/td[2]")).getText();
//To convert actual value string to Integer value.
int actualVal = Integer.parseInt(actualValString);
//Call compareIntegerVals method Inside If condition to check Integer
values match or not.
if(compareIntegerVals(actualVal, 5)){
//If values match, This block will be executed.
System.out.println("Write Action taking lines In this block when Values
match.");
}else{
//If values not match, This block will be executed.
System.out.println("Write Action taking lines In this block when Values
not match.");
}
//To mark test fail In report at the end of execution If values not match.
Soft_Assert.assertAll();
}
}
package Testng_Pack;
import org.testng.Assert;
import org.testng.asserts.SoftAssert;
package Testng_Pack;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import 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.
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 org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
@BeforeTest
public void setup() throws Exception {
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
driver.get("http://only-testing-blog.blogspot.in/2014/05/form.html");
}
@AfterTest
public void tearDown() throws Exception {
driver.quit();
}
@Test
public void Handle_Dynamic_Webtable() {
//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.
This Is only example for your reference. You will find this kind of ajax drop
lists In many sites.
//*[@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
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 org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
@BeforeTest
public void setup() throws Exception {
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
driver.get("http://www.google.com");
}
@AfterTest
public void tearDown() throws Exception {
driver.quit();
}
@Test(dataProvider="search-data")
public void Search_Test(String Search){
driver.findElement(By.xpath("//input[@id='gbqfq']")).clear();
driver.findElement(By.xpath("//input[@id='gbqfq']")).sendKeys(Search);
int i=1;
int j=i+1;
try{
//for loop will run till the
NoSuchElementException exception.
for(i=1; i<j;i++)
{
//Value of variable i Is used for
creating xpath of drop list's different elements.
String suggestion =
driver.findElement(By.xpath("//*[@id='gsr']/table/tbody/tr[1]/td[2]/table/tb
ody/tr["+i+"]/td/div/table/tbody/tr/td[1]/span")).getText();
System.out.println(suggestion);
j++;
}
}catch(Exception e){//Catch block will catch
and handle the exception.
System.out.println("***Please search for
another word***");
System.out.println();
}
}
}
This way you can also select specific from that suggestion for your
searching purpose. It Is very simple In selenium webdriver. You can use
other or more search values In above example. To do It simply modify
@DataProvider annotation method.
Submitting Form Using submit() Method Of Selenium WebDriver
You will find many forms In any website like Contact Us form, New User
Registration Form, Inquiry Form, LogIn Form etc.. Supposing you are
testing one site where you have to prepare Login form submission test
case In selenium webdriver then how will you do It? Simplest way Is
described In THIS POST. If you will
see In that example post, we have used .click() method to click on Login
button.
Selenium Webdriver has one special method to submit any form and that
method name Is submit(). submit() method works same as clicking on
submit button.
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 org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
@BeforeTest
public void setup() throws Exception {
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
driver.get("http://only-testing-blog.blogspot.in/2014/05/form.html");
}
@AfterTest
public void tearDown() throws Exception {
driver.quit();
}
@Test
public void LogIn_Test(){
driver.findElement(By.xpath("//input[@name='FirstName']")).sendKeys("M
yFName");
driver.findElement(By.xpath("//input[@name='LastName']")).sendKeys("M
yLName");
driver.findElement(By.xpath("//input[@name='EmailID']")).sendKeys("My
Email ID");
driver.findElement(By.xpath("//input[@name='MobNo']")).sendKeys("My
Mob No.");
driver.findElement(By.xpath("//input[@name='Company']")).sendKeys("My
Comp Name");
//To submit form.
//You can use any other Input field's(First Name, Last Name etc.) xpath
too In bellow given syntax.
driver.findElement(By.xpath("//input[@name='Company']")).submit();
String alrt = driver.switchTo().alert().getText();
driver.switchTo().alert().accept();
System.out.println(alrt);
}
}
Above example will simply submit the form and retrieve submission alert
to print. So this way we can use webdriver's submit method to submit any
form. You can try different form for your better understanding.
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.
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.
Same way In any web table, Number of <td> tags from any <tr> tag
describes the number of columns of table as shown In bellow given Image.
Now we have row count and column count. One more thing you require to
read data from table Is generating Xpath for each cell of column. Look at
bellow given xpath syntax of 1st cell's 1st and 2nd rows.
//*[@id='post-body-6522850981930750493']/div[1]/table/tbody/tr[1]/td[1]
//*[@id='post-body-6522850981930750493']/div[1]/table/tbody/tr[2]/td[1]
Highlighted string Is common for both cell's xpath. Only changing Is row
number Inside tr node. So here we can pass Row_count variable's
value Inside tr node.
Same way, look at bellow given xpath syntax of 1st and 2nd cells of 1st
row. Highlighted string Is common for both cell's xpath. Only changing Is
column number Inside td node. So here we can pass Col_count variable's
value Inside td node.
//*[@id='post-body-6522850981930750493']/div[1]/table/tbody/tr[1]/td[1]
//*[@id='post-body-6522850981930750493']/div[1]/table/tbody/tr[1]/td[2]
All above thing Is applied In bellow given example. Simply run It In your
eclipse using testng and observe output In console.
package Testng_Pack;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
@AfterTest
public void tearDown() throws Exception {
driver.quit();
}
@Test
public void print_data(){
Number Of Rows = 3
Number Of Columns = 6
11 12 13 14 15 16
21 22 23 24 25 26
31 32 33 34 35 36
Here you can see, all the values of table are extracted and printed.
Sometimes you need to extract specific types of web elements from page
like extract all Links to open all of them one by one, extract all text boxes
from page to type some text In all of them or In some of them one by one.
Previously we have learnt how to extract all links from page In THIS POST.
Now supposing you have
a scenario where you needs to extract all text fields from page to send
some text In all of them how to do It In selenium WebDriver?
WebDriver's In built findelements method will help us to find all text boxes
from page. If you know, Each simple text box are Input fields and will have
always attribute type = text and If It Is password text box then It's type
will be password as shown In bellow given Image.
In short we have to find all those Input fields where type = "text" or
"password". In bellow given example, I have used findelements method to
find and store all those elements In txtfields array list and then used for
loop to type some text In all of them.
package Testng_Pack;
import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
@BeforeTest
public void StartBrowser() {
driver = new FirefoxDriver();
}
@Test
public void Text() throws InterruptedException{
driver.get("http://only-testing-blog.blogspot.in/2014/05/login.html");
//find all input fields where type = text or password and store them In
array list txtfields.
List<WebElement> txtfields =
driver.findElements(By.xpath("//input[@type='text' or
@type='password']"));
@AfterTest
public void CloseBrowser() {
driver.quit();
}
}
This way we can extract all text box from page If required In any scenario.
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..
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.
package Testng_Pack;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxProfile;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
@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.
This way you can download any file using selenium webdriver like zip file,
exe file, etc.. Just know your file's MIME type and download It as shown In
above example.
Anyone don't like exceptions and at the same time, anyone can not hide
himself from exceptions when running webdriver tests because (What Is
An Exception? :->) exception Is an error event generated during the
execution of webdriver test case or java program which disrupts test
execution In between. Exception
can arise due to the many reasons like, network connection or hardware
failure, Invalid data entered by user, DB server down etc.. So all these
things can happens any time when you run your selenium webdriver test
case and we can not stop It. So Instead of thinking about stopping
exception(Which Is not possible) during run time, Think about handling
exceptions. Java provides very good exception handling mechanism to
recover from this kind of errors. Let us learn different ways of handling
exception In java.
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.
Always use try catch block to log your exception In selenium webdriver
reports.
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");
}
}
}
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
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.
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.
package Testng_Pack;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxProfile;
import org.openqa.selenium.firefox.internal.ProfilesIni;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
@BeforeTest
public void StartBrowser() {
//Create object of webdriver's inbuilt class ProfilesIni to access Its method
getProfile.
ProfilesIni firProfiles = new ProfilesIni();
//Get access of newly created profile WebDriver_Profile.
FirefoxProfile wbdrverprofile = firProfiles.getProfile("WebDriver_Profile");
//Pass wbdrverprofile parameter to FirefoxDriver.
driver = new FirefoxDriver(wbdrverprofile);
}
@Test
public void OpenURL(){
driver.get("http://only-testing-blog.blogspot.in/2014/05/login.html");
}
@AfterTest
public void CloseBrowser() {
driver.quit();
}
}
When you will run above given example, It will open Firefox browser with
newly created profile settings.
If you have any example where we need to set Firefox profile properties
then you can share It with world by commenting bellow.
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.
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 org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
@BeforeTest
public void setup() throws Exception {
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
driver.get("http://only-testing-blog.blogspot.in/2014/05/login.html");
}
@AfterTest
public void tearDown() throws Exception {
driver.quit();
}
Cred[0][0] = "UserId1";
Cred[0][1] = "Pass1";
Cred[1][0] = "UserId2";
Cred[1][1] = "Pass2";
Cred[2][0] = "UserId3";
Cred[2][1] = "Pass3";
Cred[3][0] = "UserId4";
Cred[3][1] = "Pass4";
return Cred; //Returned Cred
}
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);
}
}
When you will run above example In eclipse, It will enter UserID and
passwords one by one In UserId and password test box of web page.
TestNG result report will looks like bellow.
Creating Object Repository Using Properties File In Selenium WebDriver
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 org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
@BeforeMethod
public void openbrowser() throws IOException {
driver.manage().window().maximize();
driver.get("http://only-testing-blog.blogspot.in/2014/04/calc.html");
}
@AfterMethod
public void closebrowser() {
driver.quit();
}
@Test
public void Calc_Operations() throws IOException{
//Create Object of Properties Class.
Properties obj = new Properties();
//Create Object of FileInputStream Class. Pass file path.
FileInputStream objfile = new
FileInputStream(System.getProperty("user.dir")
+"\\src\\ObjectRepo\\objects.properties");
//Pass object reference objfile to load method of Properties object.
obj.load(objfile);
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.
Now you can easily select or deselect any specific option from select box
or drop down as described in my earlier POST 1, POST 2 and POST 3. All
these three posts will describe you different alternative ways of selecting
options from list box or drop down. Now let me take you one step ahead to
describe you the use
of deselectAll() and isMultiple() methods in selenium webdriver.
deselectAll() Method
deselectAll() method is useful to remove selection from all selected
options of select box. It will works with multiple select box when you need
to remove all selections. Syntax for deselectAll() method is as bellow.
Select listbox = new
Select(driver.findElement(By.xpath("//select[@name='FromLB']")));
listbox.deselectAll();
isMultiple() Method
isMultiple() method is useful to verify if targeted select box is multiple
select box or not means we can select multiple options from that select
box or not. It will return boolean (true or false) value. We can use it with if
condition before working with select box. Syntax is as bellow.
Select listbox = new
Select(driver.findElement(By.xpath("//select[@name='FromLB']")));
boolean value = listbox.isMultiple();
System.out.print(value);
Bellow given example will show you use of isMultiple() and deselectAll()
methods very clearly in selenium webdriver.
@Test
public void test () throws InterruptedException
{
Select listbox = new
Select(driver.findElement(By.xpath("//select[@name='FromLB']")));
//To verify that specific select box supports multiple select or not.
if(listbox.isMultiple())
{
System.out.print("Multiple selections is supported");
listbox.selectByVisibleText("USA");
listbox.selectByValue("Russia");
listbox.selectByIndex(5);
Thread.sleep(3000);
In above example, if condition will check that listbox is multiple select box
or not? Used listbox.deselectAll(); to remove all selected options.
]
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.
2. Deselect By Value
You can also deselect option from list box by value. 2nd syntax will
deselect option by value = Mexico.
3. Deselect By Index
Bellow given syntax will remove selection by index = 5.
Copy bellow given @Test method part of deselect option by visible text or
value or index and replace it with the @Test method part of example given
on THIS PAGE.(Note : @Test method is marked with pink color in that
linked page).
@Test
public void test () throws InterruptedException
{
driver.findElement(By.id("text1")).sendKeys("My First Name");
listbox.selectByValue("Japan");
listbox.selectByValue("Mexico");
Thread.sleep(1000);
listbox.selectByIndex(4);
listbox.selectByIndex(5);
Thread.sleep(1000);
driver.findElement(By.xpath("//input[@value='->']")).click();
Thread.sleep(1000);
}
}
Execute bellow given example in your eclipse and verify result. Try to use
it in different applications.
driver.findElement(By.xpath("//input[@value='->']")).click();
WebDriverWait wait = new WebDriverWait(driver, 15);
wait.until(ExpectedConditions.elementToBeClickable(By.id("text2")));
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 .
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()];
//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);
}
document.getElementsByName('fname')[0].setAttribute('disabled', '');
document.getElementsByName('lname')[0].removeAttribute('disabled');
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);
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);
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);
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.
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.
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);
@Test
public void test () throws InterruptedException
{
driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
driver.findElement(By.xpath("//b[contains(.,'Open New Page')]")).click();
driver.findElement(By.xpath("//input[@name='fname']")).sendKeys("Name
Changed");
Thread.sleep(5000);
driver.close();
How To Get/Extract All Links From Web Page Using Selenium WebDriver
As we all knows, Each and every software web application contains many
number of different links/URLs. Some of them are redirecting to some
page of same website and others are redirecting to any external website.
One of my blog reader has requested the webdriver test script example
for printing all these links in
console. I have created and published many different WEBDRIVER
EXAMPLE SCRIPTS on this blog but requested example by blog reader is
not pushed till now so I have created example for the same to share with
all of you.
You can look at example of EXTRACTING TABLE DATA USING SELENIUM
WEBDRIVER.
Copy bellow given @Test method part of extract all links from web
page and replace it with the @Test method part of example given on THIS
PAGE.(Note : @Test method is marked with pink color in that linked page).
@Test
public void test () throws InterruptedException
{
try {
List<WebElement> no = driver.findElements(By.tagName("a"));
int nooflinks = no.size();
System.out.println(nooflinks);
for (WebElement pagelink : no)
{
String linktext = pagelink.getText();
String link = pagelink.getAttribute("href");
System.out.println(linktext+" ->");
System.out.println(link);
}
}catch (Exception e){
System.out.println("error "+e);
}
THIS LINK will show you many other basic action command examples.
I have already posted Selenium WebDrier Tutorials posts how to setup web
driver with eclipse and Run first test with webdriver, how to configure junit
with eclipse to generate webdriver test report. We have also learn
different methods of locating elements in webdriver. All these things are
very basic
things and you need to learn all of them before starting your test case
creation in selenium 2. Now we are ready to learn next step of performing
basic actions in web driver with java for your software web application.
VIEW STEP BY STEP TUTORIALS ON SELENIUM WEBDRIVER
driver.get("http://only-testing-blog.blogspot.in/2013/11/new-test.html");
This syntax will open specified URL in web browser. VIEW PRACTICAL
EXAMPLE OF OPEN URL
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
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
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
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
Select By Value
Select By Index
Deselect by Value
Deselect by Index
Select listbox = new
Select(driver.findElement(By.xpath("//select[@name='FromLB']")));
listbox.deselectByIndex(5);
It will deselect option by Index = 5 from list box.
Deselect All
isMultiple()
driver.navigate().to("http://only-testing-
blog.blogspot.in/2014/01/textbox.html");
driver.navigate().back();
driver.navigate().forward();
1st command will navigate to specific URL, 2nd will navigate one step
back and 3rd command will navigate one step forward. VIEW PRACTICAL
EXAMPLES OF NAVIGATION COMMANDS.
Boolean iselementpresent =
driver.findElements(By.xpath("//input[@id='text2']")).size()!= 0;
It will return true if element is present on page, else it will return false in
variable iselementpresent. VIEW PRACTICAL EXAMPLE OF VERIFY ELEMENT
PRESENT.
File screenshot =
((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(screenshot, new File("D:\\screenshot.jpg"));
It will capture page screenshot and store it in your D: drive. VIEW
PRACTICAL EXAMPLE ON THIS PAGE.
16. Generating Mouse Hover Event In WebDriver
2. Extract parent and child window handle from all window handles.
driver.switchTo().window(window2);
Above given steps with helps you to get window handle and then how to
switch from one window to another window. VIEW PRACTICAL EXAMPLE OF
HANDLING MULTIPLE WINDOWS IN WEBDRIVER
boolean fname =
driver.findElement(By.xpath("//input[@name='fname']")).isEnabled();
System.out.print(fname);
Above syntax will verify that element (text box) fname is enabled or not.
You can use it for any input element. VIEW PRACTICAL EXAMPLE OF VERIFY
ELEMENT IS ENABLED OR NOT.
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.
driver.findElement(By.xpath("//input[@name='Company']")).submit();
It will submit the form. VIEW PRACTICAL EXAMPLE OF SUBMIT FORM.
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");
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-testing-
blog.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.
@Test
public void test () throws InterruptedException
{
driver.navigate().to("http://only-testing-
blog.blogspot.in/2014/01/textbox.html");
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.
@Test
public void test () throws InterruptedException
{
for (int i=1; i<6; i++)
{
Then we have to store it in our local drive using bellow given syntax. You
can change/provide your own file destination path and name.
FileUtils.copyFile(screenshot, new File("D:\\screenshot.jpg"));
Now we need to import bellow given header files to get support of capture
screenshot in webdriver.
import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
Copy bellow given @Test method part of Capture screen shot webdriver
example and replace it with the @Test method part of example given
on THIS PAGE. Don't forget to import above given header files in your
eclipse test.(Note : @Test method is marked with pink color in that linked
page).
@Test
public void test () throws InterruptedException, IOException
{
//Capture entire page screenshot and then store it to destination drive
File screenshot =
((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(screenshot, new File("D:\\screenshot.jpg"));
System.out.print("Screenshot is captured and stored in your D: Drive");
}
You can put above syntax under catch block of try to capture screenshot
on failure.
Selenium WebDriver is totally freeware testing tool and we can use it for
software web application regression purpose. Hovering mouse on main
menu or any other element of web page or simulating mouse movement
in webdriver is not very tough task. As you know, We can perform most of
actions and
operations directly in webdriver and you can VIEW FEW OF THEM ON THIS
PAGE. But there are also some actions which we can not perform directly
in webdriver and to perform them, we need to use some tricky
ways. Generating mouse hover event is one of them.
Above example will only move mouse on targeted element. It will not
perform click operation. To perform click operation on sub menu, we need
to use click() action before perform() as shown in bellow example.
package junitreportpackage;
import java.io.IOException;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
@Before
public void beforetest() {
driver.manage().window().maximize();
driver.get("http://only-testing-blog.blogspot.in/p/mouse-hover.html");
}
@After
public void aftertest() {
driver.quit();
@Test
public void test () throws InterruptedException, IOException
{
actions.moveToElement(moveonmenu).moveToElement(driver.findElement
(By.xpath("//div[@id='menu1choices']/a"))).click().perform();
}
* Handling Multiple Windows
Example of Handling Multiple Browser Windows in Selenium WebDriver
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.
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);
@Test
public void test () throws InterruptedException
{
driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
driver.findElement(By.xpath("//b[contains(.,'Open New Page')]")).click();
driver.findElement(By.xpath("//input[@name='fname']")).sendKeys("Name
Changed");
Thread.sleep(5000);
driver.close();
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);
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
document.getElementsByName('fname')[0].setAttribute('disabled', '');
document.getElementsByName('lname')[0].removeAttribute('disabled');
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);
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);
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.
Run bellow given example In eclipse with testng and observe the result.
package Testng_Pack;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
@BeforeTest
public void setup() throws Exception {
driver =new FirefoxDriver();
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
driver.get("http://only-testing-blog.blogspot.in/2014/01/textbox.html");
}
@AfterTest
public void tearDown() throws Exception {
driver.quit();
}
@Test
public void Text() throws InterruptedException {
//Alert Pop up Handling.
driver.findElement(By.xpath("//input[@value='Show Me Alert']")).click();
//To locate alert.
Alert A1 = driver.switchTo().alert();
//To read the text from alert popup.
String Alert1 = A1.getText();
System.out.println(Alert1);
Thread.sleep(2000);
//To accept/Click Ok on alert popup.
A1.accept();
This way you can handle different kind of alerts very easily using Alert
Interface of selenium webdriver. NEXT POST will show you how to handle
unexpected alerts In selenium webdriver.
* Handle Unexpected Alert
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 org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
@BeforeTest
public void setup() throws Exception {
driver =new FirefoxDriver();
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
driver.get("http://only-testing-blog.blogspot.in/2014/06/alert_6.html");
}
@AfterTest
public void tearDown() throws Exception {
driver.quit();
}
@Test
public void Text() throws InterruptedException {
//To handle unexpected alert on page load.
try{
driver.switchTo().alert().dismiss();
}catch(Exception e){
System.out.println("unexpected alert not present");
}
driver.findElement(By.xpath("//input[@name='fname']")).sendKeys("fname
");
driver.findElement(By.xpath("//input[@name='lname']")).sendKeys("lname
");
driver.findElement(By.xpath("//input[@type='submit']")).click();
}
}
Above given webdriver code Is just for example. It Is just explaining the
way of using try catch block to handle unexpected alert. You can use such
try catch block In that area where you are facing unexpected alerts very
frequently.
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.
driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
@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']"));
}
11.WebDriverExamples
import java.util.concurrent.TimeUnit;
import java.io.FileInputStream;
import java.io.IOException;
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.Select;
import org.openqa.selenium.support.ui.WebDriverWait;
@Before
public void beforetest() {
driver.manage().window().maximize();
driver.get("http://only-testing-blog.blogspot.in/2013/11/new-test.html");
driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
}
@After
public void aftertest() {
driver.quit();
@Test
public void test ()
{
driver.findElement(By.xpath("//input[@name='fname']")).sendKeys("My
Name");
//Wait for element to be clickable
WebDriverWait wait = new WebDriverWait(driver, 15);
wait.until(ExpectedConditions.elementToBeClickable(By.cssSelector("#sub
mitButton")));
driver.findElement(By.cssSelector("#submitButton")).click();
}
public void HighlightMyElement(WebElement element) {
for (int i = 0; i < 10; i++)
{
JavascriptExecutor javascript = (JavascriptExecutor) driver;
javascript.executeScript("arguments[0].setAttribute('style',
arguments[1]);", element, "color: orange; border: 4px solid orange;");
javascript.executeScript("arguments[0].setAttribute('style',
arguments[1]);", element, "color: pink; border: 4px solid pink;");
javascript.executeScript("arguments[0].setAttribute('style',
arguments[1]);", element, "color: yellow; border: 4px solid yellow;");
javascript.executeScript("arguments[0].setAttribute('style',
arguments[1]);", element, "");
}
}
}
*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.
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"));
}
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.
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 org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
@Before
public void beforetest() {
driver.manage().window().maximize();
driver.get("http://only-testing-blog.blogspot.in/2014/01/new-
testing.html");
}
@After
public void aftertest() {
driver.quit();
@Test
public void test ()
{
driver.findElement(By.xpath("//input[@name='fname']")).sendKeys("My
Name");
WebDriverWait wait = new WebDriverWait(driver, 15);
wait.until(ExpectedConditions.alertIsPresent());
String alrt = driver.switchTo().alert().getText();
System.out.print(alrt);
}
Above example will wait for the alert on page and as soon as alert appears
on page, it will store alert text in variable 'alrt' and then will print to it in
console.
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.
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();
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.
In any software web application's webdriver test case, you can easily wait
for presence of element using IMPLICIT WAIT. If you have used implicit
wait in your test case then you do not require to write any extra
conditional statement to wait for element visibility. But in some cases, if
any element is taking too much
time to be visible on page then you can use EXPLICIT WAIT condition in
your test case.
If you have a scenario to wait till element visible on page then selenium
webdriver/Selenium 2 has its own method
named visibilityOfElementLocated(By locator) to check the visibility of
element on page. We can use this method with explicit webdriver wait
condition to wait till element visible of present on page. However, we can
wait for element to be clickable using elementToBeClickable(By locator)
method as described in THIS ARTICLE.
Syntax to wait till element visible on page is as bellow. It will wait max 15
seconds for element. As soon as element visible on page, webdriver will
go for executing next statement.
WebDriverWait wait = new WebDriverWait(driver, 15);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//input
[@id='text3']")));
Here is practical example of wait for element visible. Execute it once and
then use it for your software web application test scenario.
Copy bellow given @Test method part of wait for visibility of element
located example and replace it with the @Test method part of example
given on THIS PAGE.(Note : @Test method is marked with pink color in that
linked page).
@Test
public void test () throws InterruptedException, IOException
{
//To wait for element visible
WebDriverWait wait = new WebDriverWait(driver, 15);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//input
[@id='text3']")));
driver.findElement(By.xpath("//input[@id='text3']")).sendKeys("Text box
is visible now");
System.out.print("Text box text3 is now visible");
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']")));
findElement() method
findElements() method
In above example, findElement will locate only targeted element and then
print its id and text in console while findElements will locate all those
elements of current page which are under given xpath = //option. for loop
is used to print all those element's id and text in console.
Same way you can locate all input elements, link elements etc..
using findElements method.
How To Generate And Insert Log In Selenium Webdriver Using log4j Jar
Assume you have prepared test case for your software web application
test scenario (using selenium webdriver with eclipse and junit) and now
you wants generate log file to insert your execution time log messages in
to it. How you will do it? Selenium webdriver do not have any built in
function or method to
generate log file. In this case you can use apache logging service. Let me
describe you steps to generate log file in selenium webdriver.
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.
5. Create example(Sample) test case under your project.
Create your own test case or copy example test case from here and paste
it in your class file.
7. Replace bellow given syntax in your class file and Run your test case.
@Test
public void test () throws InterruptedException
{
Logger log;
driver.findElement(By.id("text1")).sendKeys("My First Name");
log = Logger.getLogger(Mytesting.class);
log.info("Type In Text field.");
Select mydrpdwn = new Select(driver.findElement(By.id("Carlist")));
mydrpdwn.selectByVisibleText("Audi");
log = Logger.getLogger(Mytesting.class);
log.info("Select value from drop down.");
WebDriverWait wait = new WebDriverWait(driver, 15);
wait.until(ExpectedConditions.elementToBeClickable(By.id("text2")));
}
When your test case is executed, Go to folder = C:\Logs. log.log file will be
created over there. Open that file and look in to it. Log written in your test
case will be inserted in your log file. In above example, Syntax marked
with Pink color are written for inserting log. Now you can write log at any
place in your test case as shown in above example.
It will open New wizard. Expand General folder In New wizard and select
File and click on Next button.
Give file name objects.properties on next window and click on Finish
button.
It will add object.properties file under your package. Now copy paste
bellow given lines in objects.properties file. So now
this objects.properties file Is object repository for your web application
page calc.
objects.properties file
#Created unique key for Id of all web elements.
# Example 'one' Is key and '1' Is ID of web element button 1.
one=1
two=2
three=3
four=4
five=5
six=6
seven=7
eight=8
nine=9
zero=0
equalsto=equals
cler=AC
result=Resultbox
plus=plus
minus=minus
mul=multiply
In above file, Left side value Is key and right side value Is element
locator(by Id) of all web elements of web calculator. You can use other
element locator methods too like xpath, css ect.. VISIT THIS LINK to view
different element locator methods of webdriver.
package ObjectRepo;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
@BeforeMethod
public void openbrowser() throws IOException {
driver.manage().window().maximize();
driver.get("http://only-testing-blog.blogspot.in/2014/04/calc.html");
}
@AfterMethod
public void closebrowser() {
driver.quit();
}
@Test
public void Calc_Operations() throws IOException{
//Create Object of Properties Class.
Properties obj = new Properties();
//Create Object of FileInputStream Class. Pass file path.
FileInputStream objfile = new
FileInputStream(System.getProperty("user.dir")
+"\\src\\ObjectRepo\\objects.properties");
//Pass object reference objfile to load method of Properties object.
obj.load(objfile);
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.
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
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 has built in HTML report and XML report generation facility. It
has also built in logging facility.
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
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.
Step 1 : Open Eclipse and go to Menu Help -> Install New Software.
When you click on Next button, it will check for requirements and
dependency first.
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
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.
3. We can ignore specific test case execution from suite in both the
frameworks.
18.CreateAndRunFirstTestNG-WebDriverTest
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.
(Note : Do not add junit jar file as external jar file. Now its not required in
TestNG framework).
This is it. Now you are ready to write your webdriver test script inside your
class.
package TestNGOnePack;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
@Test
public void testmethodone() {
String title = driver.getTitle();
System.out.print("Current page title is : "+title);
System.out.print("\n'TestNGOne -> TestNGOnePack -> ClassOne ->
testmethodone' has been executed successfully");
}
}
Go to Run -> Run As -> And Click on TestNg Test as shown in bellow given
image.
It will run your webdriver test with TestNG. When execution completed,
You will see result as shown in bellow given image.
Step 7 : View test execution HTML report generated by TestNG
To view test execution report,
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
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
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.
When execution completed, You can view test execution HTML report as
described in my PREVIOUS POST. Test execution HTML report will looks like
bellow.
This is the one simple example of creating and running testng.xml file in
eclipse for webdriver. We will see different examples of testng.xml file to
configure our test in my future post.
--20.1CreatingSingleOrMultipleTestsForMultipleClasses
1. BaseClassOne.java
package TestNGOnePack;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.AfterSuite;
import org.testng.annotations.BeforeSuite;
2. ClassOne.java
package TestNGOnePack;
import org.testng.annotations.Test;
3. ClassTwo.java
package TestNGOnePack;
import org.testng.annotations.Test;
When execution completed, View execution result reports. It will looks like
bellow.
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
Now you are already aware about HOW TO CREATE testng.xml FILE to
configure and run your webdriver test. The main reason behind popularity
of TestNG framework for webdriver is we can configure our test as per our
requirements. I have listed some Similarities/Differences between Junit
and TestNG
framework In THIS POST. In my previous post, We have already seen
example of how to configure testng.xml file to run single/multiple
webdriver test classes of same package. Now let me show you an
example of how to create test suite using classes from different packages.
First of all let we create new packages and classes as described in bellow
given 3 steps.
ClassOne.java
package TestNGTwoPack;
import org.testng.annotations.Test;
@Test
public void testmethodone() {
String title = driver.getTitle();
System.out.print("\nCurrent page title is : "+title);
String Workdir = System.getProperty("user.dir");
String Classpackname = this.getClass().getName();
System.out.print("\n'"+Workdir+" -> "+Classpackname+" ->
testmethodone' has been executed successfully");
}
}
ClassTwo.java
package TestNGTwoPack;
import org.testng.annotations.Test;
@Test
public void testmethodone() {
driver.navigate().to("http://only-testing-
blog.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 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
Above given testng.xml file will execute all packages of your selenium
webdriver project and test result report will looks like bellow.
As you see in report, Now all the packages are executed. This way, we can
use wild card to include all webdriver test packages in our test.
--20.4 Including Only Selected Test Methods In Selenium WebDriver-TestNg
Test
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.
@Test
public void testmethodone() {
driver.navigate().to("http://only-testing-
blog.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");
}
In above given testng.xml file, methods and include tags are new to learn.
You can read about TestNg Framework's <suite>, <test>, <classes> and
<class> tags in THIS POST and <packages>, <package> tags in THIS
POST. <methods> tag defines the group of methods and <include> tag
defines which method you wants to include in execution. Now execute this
testng.xml file and verify the result report.
If you see in above result, Only test testmethodone() is executed
from TestNGOnePack -> ClassOne.java. This way we can include any
specific method in our test suite to execute from any class.
When you run above given testng.xml file, it will exclude testmethodone()
test method of TestNGTwoPack -> ClassTwo.jav from execution and will
execute only ClassTwo.java file as shown in bellow given test result report.
This way we can configure our testng.xml file to include or exclude any
specific test method from execution.
--20.5 testng.xml - Include/Exclude Selenium WebDriver Test Package
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.
It is very important for us to know the each and every way of testng.xml
configuration to include/exclude selected test methods or packages in
execution. You can view my posts to know how to include/exclude
SELECTED PACKAGE or SELECTED TEST METHODS from selenium
webdriver test suite
execution. There is also one another way of including or excluding
selected test method using regular expression. Let me describe it with one
simple example.
If you see in above testng.xml file, ".*two.*" is regular expression used for
test methods. Means test methods containing "two" word will be
considered for inclusion/exclusion in test suite execution.. Now when I will
run above testng.xml file, Selenium webdriver test execution report will
looks like bellow.
If you see in above given test execution report, only two methods has
been executed as per our expectation. This way you can use regular
expressions for method's inclusion or exclusion.
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.
package Testng_Pack;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.SkipException;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
@BeforeTest
public void setup() throws Exception {
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
driver.get("http://only-testing-blog.blogspot.in/2013/11/new-
test.html");
}
@Test
public void Intensional_Skip(){
System.out.println("In Verify_Title");
String titl = driver.getTitle();
}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();
}
}
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.
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 org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
@BeforeTest
public void setup() throws Exception {
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
driver.get("http://only-testing-blog.blogspot.in/2014/05/login.html");
}
@AfterTest
public void tearDown() throws Exception {
driver.quit();
}
Cred[0][0] = "UserId1";
Cred[0][1] = "Pass1";
Cred[1][0] = "UserId2";
Cred[1][1] = "Pass2";
Cred[2][0] = "UserId3";
Cred[2][1] = "Pass3";
Cred[3][0] = "UserId4";
Cred[3][1] = "Pass4";
return Cred; //Returned Cred
}
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);
}
}
When you will run above example In eclipse, It will enter UserID and
passwords one by one In UserId and password test box of web page.
TestNG result report will looks like bellow.
Posted by P
Email ThisBlogThis!Share to TwitterShare to FacebookShare to Pinterest
Related Articles : Data Driven Testing in webdr
--20.9 Parallel test execution In multiple browsers using @Parameters
annotation
Parallelism In TestNG
You can configure your testng.xml file In such a way to run your test suite
or tests or methods In seperate browsers Is known as parallelism In
TestNG. Interviewer can ask you this question. Now let us look at example
of parellel test execution In webdriver using testng. Bellow given example
will run the test In Mozilla Firefox and Google chrome browser parallel.
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;
driver.findElement(By.xpath("//input[@name='userid']")).sendKeys("UID1")
;
driver.findElement(By.xpath("//input[@type='password']")).sendKeys("pass
1");
driver.findElement(By.xpath("//input[@value='Login']")).click();
String alert = driver.switchTo().alert().getText();
driver.switchTo().alert().accept();
Assert.assertEquals("UserId Is : UID1 Password Is : pass1", alert);
System.out.println("Alert Is Fine.");
}
@AfterClass
public void closebrowser(){
driver.quit();
}
}
testng.xml
If you wants to run your test In one more browser then you need to create
new <test> tag block in testng.xml file and set another parameter value
and then put one more if else condition in class file to check and run your
test.
This way you can your test parallel In multiple browsers at same time to
reduce your time efforts.
Hard Assertions
20.1 assertEquals Assertion With Example
Steps :
package TestNGOnePack;
import org.openqa.selenium.By;
import org.testng.Assert;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
String Actualtext;
@BeforeClass
public void load_url(){
driver.navigate().to("http://only-testing-
blog.blogspot.in/2014/01/textbox.html");
}
//Method Example For Assertion
@Test
public void assertion_method_1() {
Actualtext = driver.findElement(By.xpath("//h2/span")).getText();
Assert.assertEquals(Actualtext, "Tuesday, 28 January 2014");
System.out.print("\n assertion_method_1() -> Part executed");
}
//Method Example For Assertion
@Test
public void assertion_method_2() {
Assert.assertEquals(Actualtext, "Tuesday, 29 January 2014");
System.out.print("\n assertion_method_2() -> Part executed");
}
String time =
driver.findElement(By.xpath("//div[@id='timeLeft']")).getText();
You can VIEW SELENIUM IDE ASSERTION EXAMPLES for your reference.
//Assertion Method
@Test
public void assertion_method_1() {
Actualtext = driver.findElement(By.xpath("//h2/span")).getText();
Assert.assertNotEquals(Actualtext, "Tuesday, 28 January 2014",
"Expected and actual match in assertion_method_1");
System.out.print("\n assertion_method_1() -> Part executed");
}
//Assertion Method
@Test
public void assertion_method_2() {
Assert.assertNotEquals(Actualtext, "Tuesday, 29 January 2014",
"Expected and actual match in assertion_method_2");
System.out.print("\n assertion_method_2() -> Part executed");
}
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.
assertTrue(condition) Assertion
assertTrue assertion is generally used for boolean condition true. It will
pass if condition returns "true". If it will return false then it will fail and skip
test execution from that specific method. Syntax for assertTrue assertion
is as bellow.
Assert.assertTrue(condition);
Supposing you have one check box on page. You wants to check its status
like it is checked or not. And if it is not checked then you wants to skip
execution from that method and wants to fail that method in testng
report. This thing can be done very easily using assertTrue assertion. Let
we look at practical example of assertTrue assertion.
When you run above example in eclipse and get result, asserttrue1()
method will display pass and method asserttrue2() will display fail as
shown in bellow given image.
When you are working with selenium webdriver, you must be aware about
different kind of assertions which are available. If you have a enough
knowledge about webdriver assertions, You can create very effective test
cases for your test scenarios. assertEquals, assertNotEquals and
assertTrue assertions are already
explained in my previous posts. Now let we try to understand assertFalse
assertion for selenium webdriver.
Assert.assertFalse(condition) Assertion
It will check boolean value returned by condition and will pass if returned
value is "False". If returned value is pass then this assertion will fail and
skip execution from current test method. Syntax for assertFalse assertion
is as bellow.
Assert.assertFalse(condition);
Replace bellow given example methods with example of THIS PAGE. and
run it with testng.xml as described on that post.
Assertions are very useful to check your expected result and skip
execution if assertion fails on run time. If you are selenium IDE user, you
can read all these selenium IDE ASSERTION COMMANDS examples posts
to use them in your test cases for your web application. Before describing
about assertNull command,
I recommend you all to READ OTHER WEBDRIVER ASSERTION METHOD
examples for your reference.
Copy and replace bellow given test methods with example given on THIS
PAGE and then run it with testng.xml file
Copy paste bellow given code in example given on THIS PAGE and then
run it using testng.xml file.
Soft Assertion
20.4 Applying TestNG Soft Assertion With Example
If you know, we have already learn about testng hard assertions (Example
assertEquals, assertNotEquals, etc..) which we can use In our webdriver
test. Hard assertion examples links are given on THIS PAGE. View all those
examples one by one to learn hard assertions. Let me tell you one thing
about hard assertions, When hard assertion will fail Inside any test
method, remaining execution of that specific test method will be aborted.
Now If you wants to continue remaining test part execution even If
assertion fails and also you wants to report assertion failure In testng
result report then you can use testng soft assertion method.
Let us look at very simple example of testng hard assertion and soft
assertion to see the difference between both of them. In bellow give
example, hard_assert_text() and soft_assert_text() each have 4 assertions.
Used hard assertions In hard_assert_text() method and soft assertions In
soft_assert_text() method to describe difference between both of them.
package Testng_Pack;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.Assert;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import org.testng.asserts.SoftAssert;
@BeforeClass
public void load_url(){
driver.manage().window().maximize();
driver.get("http://only-testing-blog.blogspot.in/2014/01/textbox.html");
}
@Test
//In this method, If any assertion fails then execution will be aborted.
public void hard_assert_text() {
Actualtext = driver.findElement(By.xpath("//h2/span")).getText();
//Text on expected side Is written Incorrect intentionally to get fail this
assertion.
Assert.assertEquals(Actualtext, "Tuesday, 01 January 2014", "1st assert
failed.");
System.out.println("Hard Assertion -> 1st pagetext assertion
executed.");
driver.findElement(By.xpath("//input[@value='Show Me Alert']")).click();
String Alert_text = driver.switchTo().alert().getText();
driver.switchTo().alert().accept();
@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.");
driver.findElement(By.xpath("//input[@value='Show Me Alert']")).click();
String Alert_text = driver.switchTo().alert().getText();
driver.switchTo().alert().accept();
@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();
}
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.
package Testng_Pack;
import org.testng.Assert;
import org.testng.asserts.SoftAssert;
package Testng_Pack;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import 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.
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.
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;
package Testng_Pack;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
@BeforeTest
public void StartBrowser_NavURL() {
driver = new FirefoxDriver();
driver.get("http://only-testing-blog.blogspot.in/2014/05/form.html");
}
@AfterTest
public void CloseBrowser() {
driver.quit();
}
@Test
public void testToCompareIntegers(){
String actualValString = driver.findElement(By.xpath("//*[@id='post-
body-8228718889842861683']/div[1]/table/tbody/tr[1]/td[2]")).getText();
//To convert actual value string to Integer value.
int actualVal = Integer.parseInt(actualValString);
//Call compareIntegerVals method Inside If condition to check Integer
values match or not.
if(compareIntegerVals(actualVal, 5)){
//If values match, This block will be executed.
System.out.println("Write Action taking lines In this block when Values
match.");
}else{
//If values not match, This block will be executed.
System.out.println("Write Action taking lines In this block when Values
not match.");
}
//To mark test fail In report at the end of execution If values not match.
Soft_Assert.assertAll();
}
}
Let me try to describe you how to compare two double values with
example.
package Testng_Pack;
import org.testng.Assert;
import org.testng.asserts.SoftAssert;
package Testng_Pack;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
@BeforeTest
public void StartBrowser_NavURL() {
driver = new FirefoxDriver();
driver.get("http://only-testing-blog.blogspot.in/2014/01/textbox.html");
}
@AfterTest
public void CloseBrowser() {
driver.quit();
}
@Test
public void testToCompareDoubles(){
String actualValString = driver.findElement(By.xpath("//*[@id='post-
body-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.