Selenium Suresh V004
Selenium Suresh V004
Selenium Notes By
SURESH
SELENIUM QTP
Open source Paid Tool
Works on all OS (Windows, OS
Works only on Windows
X, Linux, Solaris,Mac)
Tests only Web applications Tests web and desktop applications
Works on almost all browsers(IE,
Works on IE
Firefox, Chrome, Safari, Opera)
Code can be made in any one of
languages such as Java, C#, Ruby, VB Script
Python, pearl, php
Object Identification Options : Name ,Id Object Identification Options : Object
, Xpath, CSS, Link text …etc properties, Repository objects
Selenium dose not have such built in
object repository, but object can be HP UFT comes with built in object
managed by using UI element user repository. Object repository development
extension like Inspect option in All and maintenance is quite easy in HP ALM
browsers
IDE sometimes does not record some Recording is a little reliable
What is Selenium?
Selenium is a free (open source) automated testing suite for web applications across different
browsers and platforms. It is quite similar to HP Quick Test Pro (QTP) only that Selenium
focuses on automating web-based applications.
Selenium is not just a single tool but a suite of softwares, each catering to different testing
needs of an organization. It has four components.
Selenium Components
Selenium IDE (Integrated Development Environment) - Record & Play back
Selenium RC- 1.0 – Server /Client (Selenium. Start /Selenium. Stop)
Selenium 2.0/3.0 / Web Driver /Advanced Selenium
Selenium Grid – To Execute scripts in Multiple Browsers & Systems
*In any of the html code starting with < symbol is considered as HTML TAG name and
which is having = symbol considered as Attributes
Locating element using TagName ,LinkText ,partial LinkText and CSS Selector
Syntax By using TagName
Here we use the actual name of the tag like <a> for anchor and <table> for table. This turns
out to be useful when we would like to get all the elements with a given tag name
Eg: tagname=<a> -- Mention the tagname details of that object
Syntax By using LinkText
linkText is very useful when you want to interact with hyperlinks. The actual text displayed
on the web page for that link is used
Eg: link = linktextdetails --- Mention the linktext details of that object
Syntax By using Partial LinkText
PartialLinkText is also used to interact with hyperlinks and is very similar to linkText
locating strategy. Instead of providing the complete text displayed for the link, this method
does a partial match
Username Textbox
Relative Xpath
Xpath with Single attribute
Xpath with Contains
Xpath with Starts-With
Xpath with Multiple
attribute
Password Textbox
Login button
Relative Xpath
Xpath with Single attribute
Xpath with Contains
Xpath with Starts-With
Xpath with Multiple
attribute
Clear button
Relative Xpath
Xpath with Single attribute
Xpath with Contains
Xpath with Starts-With
Xpath with Multiple attribute
Number of Employees
Relative Xpath
Xpath with Single attribute
Xpath with Contains
Xpath with Starts-With
Xpath with Multiple attribute
Phone number
Relative Xpath
Xpath with Single attribute
Xpath with Contains
Xpath with Starts-With
Xpath with Multiple attribute
Relative Xpath
Xpath with Single attribute
Xpath with Contains
Xpath with Starts-With
Xpath with Multiple attribute
Company Info Locations
Add button
Relative Xpath
Xpath with Single attribute
Xpath with Contains
Mr. Suresh Page 17 of 139
Selenium Training by Suresh
Xpath with Starts-With
Xpath with Multiple attribute
Delete button
Relative Xpath
Xpath with Single attribute
Xpath with Contains
Xpath with Starts-With
Xpath with Multiple
attribute
7. Write Xpath for Gmail Inbox(50) but after some time it will change to Inbox(55)
Step 3) once the download is complete, run the exe. Click Next
Step 6) Restart your PC. Go to command prompt and type javac--If you see a screen like
below' Java is installed.
Step 4: Create a workspace folder where you will contain all the program files you create.
You can choose whatever place you want for your workspace, I like to choose my own
workplace location and will place all my projects under it.
Step 5 : Now you will be able to see the welcome screen ,you can close welcome screen and
then start writing the java code
About Java programs, it is very important to keep in mind the following points.
Case Sensitivity - Java is case sensitive which means identifier Hello and hello would have
different meaning in Java.
Class Names - For all class names the first letter should be in Upper Case.
If several words are used to form a name of the class each inner words first letter should be in
Upper Case. Example class MyFirstJavaClass
Method Names - All method names should start with a Lower Case letter.
If several words are used to form the name of the method, then each inner word's first letter
should be in Upper Case. Example public void myMethodName ()
Program File Name - Name of the program file should exactly match the class name.
Example: Assume 'MyFirstJavaProgram' is the class name. Then the file should be saved as
'MyFirstJavaProgram.java'
3.Create new Package (Navigation: Perform Right click on Created project Navigate to
New and click on package optionProvide any package name(eg:examples) and click on
Finish buttonPackage will be created as below)
Class: A class can be defined as a template/ blue print that describe the behaviors/states that
object of its type support. (or) “A class is a way of binding the data and associated methods in
a single unit. (or) A Class is a combination of DataTypes and Data Variables
Syntax for defining a CLASS:
Class <clsname> {
Variable declaration;
Methods definition;
}
Class contains two parts namely variable declaration and method definitions. Variable
Declaration represents what type of data members which we use as a part of the class.
Method definition represents the type of methods which we used as the path of the class to
perform an operation.By making use of the variables, which are declared inside the class?
Every operation in JAVA must be defined with in the class only i.e. outside definition is not
possible.
Note : We have diffirent types of classes for now we need to understand below types
1.Instance classes (Need to create object to access methods from this class)
2.Static class (No need of to create object to access methods from this class ,We can access
the method by using class name )
Mr. Suresh Page 25 of 139
Selenium Training by Suresh
First Program in JAVA – To Print the statement as Welcome to JAVA
public class Hello{
public static void main(String args[]) {
System.out.println ("Welcome to JAVA "); // prints Welcome to JAVA
}
Output : Welcome to JAVA
Description for above program
Public: This is access modifier keyword which tells compiler access to class. Various values
of access modifiers can be public, protected, private or default (no value).
Class: This keyword used to declare class. Name of class (Hello) followed by this keyword.
“public static void main (String [ ] args)”: java program processing starts from the main ()
method which is a mandatory part of every java program.
Its method (Function) named main with string array as argument.
public : Access Modifier
static: static is reserved keyword which means that a method is accessible and usable even
though no objects of the class exist.
void: This keyword declares nothing would be returned from method. Method can return any
primitive or object.
Method content inside curly braces. { }
System.out.println("Welcome to JAVA") : This statement is used to print any information
System: It is name of Java utility class.
out: It is an object which belongs to System class.
println: It is utility method name which is used to send any String to console.
Write a Java program to print stmt as – “My target to get job is 2 months”
Method: A method is a program module that contains a series of statements that carry out a
task.Any class can contain an unlimited number of methods, and each method can be called
an unlimited number of times. The syntax to declare method is given below.
public void methodname(){
//statements to print;
}
Eg: public void m1(){
System.out.println(“Method 1 executed”);
}
Data Types :
Data type defines the values that a variable can take, for example if a variable has int data
type, it can only take integer values. In java we have two categories of data types
1.Primitive Data Types
2.Reference/Object Data Types
Primitive Data Types –Byte ,Short ,int,long,float,double,boolean,char
Reference Data Types:
Reference variables are created using defined constructors of the classes. They are
used to access objects. These variables are declared to be of a specific type that cannot
be changed. For example, Employee, Puppy etc.
Class objects and various types of array variables come under reference data type.
Default value of any reference variable is null.
A reference variable can be used to refer to any object of the declared type or any
compatible type.
Example : Animal animal = new Animal("giraffe");
Java language supports few special escape sequences for String and char literals as
well.
Variables : A variable is a name which is associated with a value that can be changed. For
example when I write int i=10; here variable name is i which is associated with value 10, int
is a data type that represents that this variable can hold integer values.
Mr. Suresh Page 28 of 139
Selenium Training by Suresh
There are three kinds of variables in Java:
In Java, all variables must be declared before they can be used
Local variables – Defined with in the method and able to access with in that method only
Instance variables – Defined outside the method and with in the class
Static/class variables –Need to use the keyword as Static
Variables are nothing but reserved memory locations to store values. This means that
when you create a variable you reserve some space in memory.
Based on the data type of a variable, the operating system allocates memory and decides what
can be stored in the reserved memory. Therefore, by assigning different data types to
variables, you can store integers, decimals, or characters in these variables.
Java Access Modifiers : The Java language has a wide variety of modifiers, including the
following:
Java Access Modifiers & Non Access Modifiers
Java provides a number of access modifiers to set access levels for classes, variables,
Mr. Suresh Page 29 of 139
Selenium Training by Suresh
methods and constructors. The four access levels are:
1. Visible to the package. The default. No modifiers are needed.
2. Visible to the class only (private).
3. Visible to the world (public).
4. Visible to the package and all subclasses (protected).
Java provides a number of non-access modifiers to achieve many other functionality.
The static modifier for creating class methods and variables
The final modifier for finalizing the implementations of classes, methods, and
variables.
The abstract modifier for creating abstract classes and methods.
The synchronized and volatile modifiers, which are used for threads.
Operators :Java provides a rich set of operators to manipulate variables. We can divide all
the Java operators into the following groups:
•Arithmetic Operators(- + * / % ++ --)
•Relational Operators (> < >= <= == !=)
•Bitwise Operators(& | ^ >> >>>)
•Logical Operators (&& || & |! ^)
•Assignment Operators( = , +=)
•Misc Operators (? :)
The if Statement:
If statement consists a condition, followed by statement or a set of statements as shown
below:
if(condition){
Statement(s);
}
The statement gets executed only when the given condition is true. If the condition is false
then the statements inside if statement body are completely ignored.
Example1:
public class Test {
public static void main(String args[]){
int x = 10;
Mr. Suresh Page 30 of 139
Selenium Training by Suresh
if( x < 20 ){
System.out.print("This is if statement");
}
}
}
This would produce following result:
This is if statement
Example2:Write a program to print Student result status : studentmarks=80
else if Statement:
if-else-if statement is used when we need to check multiple conditions. In this statement we
have only one “if” and one “else”, however we can have multiple “else if”. It is also known
as if else if ladder. This is how it looks:
if(condition_1) {
//if condition_1 is true execute this
statement(s);
}
else if(condition_2) {
Mr. Suresh Page 32 of 139
Selenium Training by Suresh
//execute this if condition_1 is not met and condition_2 is met
statement(s);
}
else if(condition_3) {
// execute this if condition_1 & condition_2 are not met and condition_3 is met
statement(s);
}
else {
// if none of the condition is true then these statements gets executed
statement(s);
}
Note: The most important point to note here is that in if-else-if statement, as soon as the
condition is met, the corresponding set of statements get executed, rest gets ignored. If none
of the condition is met then the statements inside “else” gets executed.
Example:
public class Test {
public static void main(String args[]){
int x = 30;
if( x = = 10 ){
System.out.print("Value of X is 10");
}else if( x = = 20 ){
System.out.print("Value of X is 20");
}else if( x = = 30 ){
System.out.print("Value of X is 30");
}else{
System.out.print("This is else statement");
}
}
}
Example: Write a program to print Grade details based on student marks: stdmarks=92
Example: Write a program to print status based on age details: age =10;
if(condition_1) {
Statement1(s);
if(condition_2) {
Statement2(s);
}
}
Statement1 would execute if the condition_1 is true. Statement2 would only execute if both
the conditions( condition_1 and condition_2) are true.
Example:
public class Test {
public static void main(String args[]){
int x = 30; int y = 10;
if( x = = 30 ){
if( y = = 10 ){
System.out.print("X = 30 and Y = 10");
}
}
}
This would produce following result: X = 30 and Y = 10
Example: int age=27; int salary=50000;
Loops:
Loops are used to execute a set of statements repeatedly until a particular condition is
satisfied. In Java we have three types of basic loops:
•while Loop
•do...while Loop
•for Loop
As of java 5 the enhanced foreach loop was introduced. This is mainly used for Arrays.
Note: The important point to note when using while loop is that we need to use increment or
decrement statement inside while loop so that the loop variable gets changed on each
iteration, and at some point condition returns false. This way we can end the execution of
while loop otherwise the loop would execute indefinitely.
The syntax of a while loop is:
while(condition)
{
//Statements
//increment or decrement
}
Example:
public class Test {
public static void main(String args[]){
int x= 10;
while( x < 15 ){
System.out.println("value of x : " + x );
x++;
}
}
}
This would produce following result:
value of x : 10
value of x : 11
value of x : 12
Mr. Suresh Page 35 of 139
Selenium Training by Suresh
value of x : 13
value of x : 14
Example: write a program to print stmt for 10 times : “Java is very easy”
Arrays in Java
Arrays: - Group of similar elements
Java provides a data structure, the array, which stores a fixed-size sequential collection of
elements of the same type. An array is used to store a collection of data, but it is often more
useful to think of an array as a collection of variables of the same type.
Instead of declaring individual variables, such as number0, number1, ..., and number99, you
declare one array variable such as numbers and use numbers[0], numbers[1], and ...,
numbers[99] to represent individual variables.
Syntax : datatype array name = array values
Int myList[] = {5,6,4,5,3---11}
Example: Following statement declares an array variable, myList, creates an array of 10
elements of double type, and assigns its reference to myList.
double[] myList = new double[10];
Following picture represents array myList. Here myList holds ten double values and the
indices are from 0 to 9.
Processing Arrays: When processing array elements, we often use either for loop or foreach
loop because all of the elements in an array are of the same type and the size of the array is
known.
Note: The array elements can be accessed with the help of the index,Accessing the array with
an index greater than or equal to the size of the array leads to NullPointer Exception.
The foreach Loops: For-each is another array traversing technique like for loop, while loop,
do-while loop introduced in Java5. It starts with the keyword for like a normal for-
loop.Instead of declaring and initializing a loop counter variable, you declare a variable that
is the same type as the base type of the array, followed by a colon, which is then followed by
the array name.In the loop body, you can use the loop variable you created rather than using
an indexed array element.It’s commonly used to iterate over an array or a Collections class
(eg, ArrayList)
Syntax: for (type var : array) {
statements using var;
}
Sample Program for Arrays & For Each Loop
public class Foreach1 {
public static void main(String[] args) {
Mr. Suresh Page 39 of 139
Selenium Training by Suresh
int myList[] = {10, 20, 30, 40 ,50,60};
// Print all the array elements
for (int element: myList) {
System.out.println(element);
}
}
}
Example : write a program to print all the elements from below array.
// String data[] ={"selenium","training",”by”,"suresh”};
ArrayList in Java
ArrayList is a part of collection framework and is present in java.util package.ArrayList is
initialized by a size; however the size can increase if collection grows or shrunk if objects are
removed from the collection.
Example:
import java.util.ArrayList;
public class ArrayListExp {
public static void main(String args[]) {
ArrayList<String> subjects = new ArrayList<String>();
subjects.add("Mat");
subjects.add("sci");
subjects.add("eng");
subjects.add("tel");
System.out.println(subjects);
subjects.add(2,"hin");
System.out.println(subjects);
}
}
Example: Create an arrayList with Selenium components details and print the same.
Write a java program to perform substract two numbers by accepting the values from
keyboard
Inheritance
The process by which one class acquires the properties (data members) and functionalities
(methods) of another class is called inheritance. The aim of inheritance is to provide the
reusability of code so that a class has to write only the unique features and rest of the
common properties and functionalities can be extended from the another class.
Child Class: The class that extends the features of another class is known as child class, sub
class or derived class.
Parent Class: The class whose properties and functionalities are used(inherited) by another
class is known as parent class, super class or Base class.
Note: The biggest advantage of Inheritance is that the code that is already present in base
class need not be rewritten in the child class.This means that the data members(instance
variables) and methods of the parent class can be used in the child class as.
Mr. Suresh Page 43 of 139
Selenium Training by Suresh
Syntax: Inheritance in Java
To inherit a class we use extends keyword. Here class B is child class and class A is parent
class. The class B is inheriting the properties and methods of A class.
class B extends A
{
Single Inheritance
When a class extends another one class only then we call it a single inheritance. The below
flow diagram shows that class B extends only one class which is A. Here A is a parent class
of B and B would be a child class of A.
Example:
class A {
public void test () {
System.out.println ("Hai...");
System.out.println("parent class");
}
}
public class B extends A {
public static void main (String [] args){
B s= new B ();
s.test ();
}
}
Multilevel Inheritance : Multilevel inheritance refers - where one can inherit from a derived
class, thereby making this derived class the base class for the new class. As you can see in
below flow diagram C is subclass or child class of B and B is a child class of A, Multilevel
inheritance can go up to any number of levels.
class A {
int a=10;
int b=20;
public void selIDE(){
System.out.println("IDE");
}
}
class B extends A{
int x=30;
int y=40;
public void selWD(){
System.out.println("WD");
System.out.println(a+b); //accessing from class A
}
}
public class C extends B{
public void selRC(){
System.out.println("RC");
System.out.println(x+y); //accessing from class B
System.out.println(a+b); //accessing from class A
}
public static void main(String args[]){
C obj = new C();
obj.selIDE(); //accessing methods of class A without creating object for class A
obj.selWD(); //accessing methods of class A without creating object for class B
obj.selRC();
}
}
Polymorphism in JAVA :
Polymorphism: It means one name with many forms.
These are 2 types:
Method Over loading
Method Over riding
Method Overloading
Writing two or more methods in the same class in such way that each method has
same name but with different method signatures
Mr. Suresh Page 45 of 139
Selenium Training by Suresh
Method Overriding
Writing two or more methods in super and sub classes such that the methods have
same name and same signature
Method Overloading (Writing two or more methods in the same class in such way that each
method has same name but with different method signatures)
As we know that a method has its own signature which is known by method's name and the
parameter types. Java has a powerful feature which is known as method overloading. With
the help of this feature we can define two methods of same name with different parameters. It
allows the facility to define that how we perform the same action on different type of
parameter.
Example: public class OverLoad {
public void add(int a,int b){
System.out.println(a+b);
}
public void add(int a,int b ,int c){
System.out.println(a+b+c);
}
public static void main(String args[]){
OverLoad obj = new OverLoad();
obj.add(10, 20);
obj.add(10, 20, 30);
}
}
Overriding (Writing two or more methods in super and sub classes such that the methods
have same name and same signature)
Method overriding in java means a subclass method overriding a super class method. Super
class method should be non-static. Subclass uses extends keyword to extend the super class.
In overriding methods of both subclass and super class possess same signatures. Overriding is
used in modifying the methods of the super class.
Example:
public class OverRide {
public void add(int a,int b){
System.out.println(a+b);
}
}
//Create new class as OverRide1
public class OverRide1 extends OverRide{
public void add(int a,int b){
System.out.println(a-b);
}
public static void main(String args[]){
OverRide1 obj1 = new OverRide1();
obj1.add(10, 20);
OverRide obj = new OverRide();
obj.add(10, 20);
}
}
Mr. Suresh Page 46 of 139
Selenium Training by Suresh
Encapsulation & Abstraction in JAVA
Encapsulation – Data Bind
Encapsulation is a process of binding or wrapping the data and the codes that operates on the
data into a single entity. Eg: class
Example: class Person{
//variable - data
private String name = "Suresh";
private int age = 26;
//method
public void talk() {
System.out.println("Hello ,Iam"+name);
System.out.println("My age is"+age);
} public static void main(String args[]){
Person p = new Person();
p.talk();
}
}
Abstraction: Data Hide
A class that is declared using “abstract” keyword is known as abstract class. It can have
abstract methods (methods without body) as well as concrete methods (regular methods with
body). A normal class (non-abstract class) cannot have abstract methods.
“Data abstraction is a mechanism of retrieving the essential details without dealing with
background details”.
•To use use abstraction we need use abstract keyword in the class
•For abstracts method implementation will be available in other class
•We can’t create any object for abstract class.To get the access for abstract methods will use
inherit those abstract classes.
Example
abstract class Bank {
abstract void credit();
abstract void debit();
}
class HDFC extends Bank{
void credit() {
System.out.println("Amount credit from HDFC");
}
void debit() {
System.out.println("Amount debited from HDFC");
}
}
class ICICI extends Bank{
void credit() {
System.out.println("Amount credit from ICICI");
}
void debit() {
System.out.println("Amount debited from ICICI");
Mr. Suresh Page 47 of 139
Selenium Training by Suresh
}
}
public class TestBank{
public static void main(String args[]) {
HDFC h = new HDFC();
h.credit();
h.debit();
ICICI i = new ICICI();
i.credit();
i.debit();
}
}
Interface in JAVA
Interface : Interface looks like a class but it is not a class. An interface can have methods and
variables just like the class but the methods declared in interface are by default abstract (only
method signature, no body) the variables declared in an interface are public, static & final by
default.
An interface in java is a blueprint of a class. It has static constants and abstract
methods only. The interface in java is a mechanism to achieve fully abstraction. There
can be only abstract methods in the java interface not method body. It is used to
achieve fully abstraction and multiple inheritance in Java.
Interface definition begins with a keyword interface.
An interface like that of an abstract class cannot be instantiated.
Example :
interface WebDriver{
public void get();
public void close();
}
class FirefoxDriver implements WebDriver{
public void get() {
System.out.println("TO open Application in firefox browser");
}
public void close() {
System.out.println("TO open Application in firefox browser");
}
}
public class ChromeDriver implements WebDriver {
public void get() {
System.out.println("TO open Application in chrome browser");
}
public void close() {
System.out.println("To close Application in chrome browser");
}
public static void main(String args[]) {
//Creating object for ChromeDriver class directly
ChromeDriver driver = new ChromeDriver();
Mr. Suresh Page 48 of 139
Selenium Training by Suresh
driver.get();
driver.close();
//Creating object for WebDriver(interface) indirectly - with the reference of ChromeDriver
class
WebDriver driver2 = new ChromeDriver();
driver2.get();
driver2.close();
//Creating object for FirefoxDriver class directly
FirefoxDriver ff = new FirefoxDriver();
ff.get();
ff.close();
//Creating object for WebDriver(interface) indirectly - with the reference of FirefoxDriver
class
WebDriver f = new FirefoxDriver();
f.get();
f.close();
}
}
} }
The throws/throw Keywords: If a method does not handle a checked exception, the method
must declare it using the throws keyword. The throws keyword appears at the end of a
method's signature.
You can throw an exception, either a newly instantiated one or an exception that you just
caught, by using the throw keyword. Try to understand the different in throws and throw
keywords.
Mr. Suresh Page 52 of 139
Selenium Training by Suresh
The following method declares that it throws a Remote Exception:
import java.io.*;
public class className{
public void deposit(double amount) throws RemoteException {
// Method implementation
throw new RemoteException();
}
//Remainder of class definition
}
A method can declare that it throws more than one exception, in which case the exceptions
are declared in a list separated by commas. For example, the following method declares that
it throws a Remote Exception and an InsufficientFundsException:
Import java.io.*;
public class className{
public void withdraw(double amount) throws RemoteException,
InsufficientFundsException {
// Method implementation
}
//Remainder of class definition
}
The finally Keyword The finally keyword is used to create a block of code that follows a try
block. A finally block of code always executes, whether or not an exception has occurred.
Using a finally block allows you to run any cleanup-type statements that you want to execute,
no matter what happens in the protected code.
A finally block appears at the end of the catch blocks and has the following syntax:
try{
//Protected code
}catch(ExceptionType1 e1) {
//Catch block
}catch(ExceptionType2 e2) {
//Catch block
}catch(ExceptionType3 e3) {
//Catch block
}finally {
//The finally block always executes.
}
Example: public class Final{
public static void main(String args[]){
int a[] = new int[2];
try{
System.out.println("Access element three :" + a[3]);
}catch(ArrayIndexOutOfBoundsException e){
System.out.println("Exception thrown :" + e);
}
finally{
a[0] = 6;
System.out.println("First element value: " +a[0]);
Mr. Suresh Page 53 of 139
Selenium Training by Suresh
System.out.println("The finally statement is executed");
}
}
}
This would produce following result:
Exception thrown :java.lang.ArrayIndexOutOfBoundsException: 3
First element value: 6
The finally statement is executed
Note the followings:
•A catch clause cannot exist without a try statement.
•It is not compulsory to have finally clauses whenever a try/catch block is present.
•The try block cannot be present without either catch clause or finally clause.
•Any code cannot be present in between the try, catch, finally blocks.
JAVA Assignment
Write a sample java program to Print the statement as – “ *** I have not failed. I've just
found 10,000 ways that won't work *** ”
Create One Class, three static Methods and print below stmt.
Method1 – Daily I will practice selenium for 2 hours.
Method2 – Daily I will sleep only for 6 hours.
Method3 – Daily I will wake up at 6 clock
Write a program to print the each element from the below array using for each loop
int arr[]={12,13,14,44};
String s1[]={“Suresh”,”selenium”,”project”,”training”}
Write a program to add list of element to array list and print the same- Selenium
,Training ,By ,Suresh.
Note: Before writing webdriver program makes sure that you added webdriver jar files to
project.
Steps to add Jar files to project
1. Create new java project
2. Right click on created project
3. Select Build path option and click on Configure build path option
4. Click on libraries Tab
Mr. Suresh Page 60 of 139
Selenium Training by Suresh
5. Click on Add external jar file button
6. Browse Webdriver jar files
7. Click on Open button
8. Click on Apply and close button
Example to Verify the application title and calling test data by using variables
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.By;
public class TC_Verify {
public static String un = "admin";
public static String pw = "admin";
public static void main(String args[]) throws Exception{
System.setProperty(“webdriver.gecko.driver”,”E:\\geckodriver.exe”);
WebDriver driver = new FirefoxDriver();
//Test Case steps
driver.navigate().to("http://127.0.0.1/orangehrm-2.6/login.php");
if(driver.getTitle().equals("OrangeHRM - New Level of HR Management")) {
System.out.println("Title matched");
}
else {
System.out.println("Title not matched and expected title is "+driver.getTitle());
}
driver.findElement(By.xpath("//input[@name='txtUserName']")).sendKeys(un);
driver.findElement(By.xpath("//input[@name='txtPassword']")).sendKeys(pw);
driver.findElement(By.name("Submit")).click();
Thread.sleep(3000);
Mr. Suresh Page 62 of 139
Selenium Training by Suresh
System.out.println("Login completed");
driver.findElement(By.linkText("Logout")).click();
System.out.println("logout completed");
driver.quit();
}
}
What is Iframe?
A web page which is embedded in another web page or an HTML document embedded
inside another HTML document is known as a frame.
The IFrame is often used to insert content from another source, such as an advertisement, into
a Web page. The <iframe> tag specifies an inline frame.
How to identify the frame ?
Perform inspect Element and Search with the ‘frame’/ 'iframe', if you can find any tag name
with the ‘frame’/ 'iframe' then it is meaning to say the page consisting an frame/ iframe.
Methods to handle frames
To Enter – driver.switchTo().frame(“framename/frameid/index”)
To Exit - driver.switchTo().defaultContent()
//Example for Frames & VerifyText & Reading the data from Textbox
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import static org.testng.Assert.assertTrue;
public class AddEmp {
public static void main(String[] args) throws InterruptedException {
System.setProperty(“webdriver.gecko.driver”,”E:\\geckodriver.exe”);
WebDriver driver=new FirefoxDriver();
driver.navigate().to("http://127.0.0.1/orangehrm-2.6/login.php");
driver.findElement(By.xpath("//input[@type='text']")).sendKeys("suresh");
driver.findElement(By.xpath("//input[@type='password']")).sendKeys("suresh123");
Alerts in WebDriver
What is Alert?
Alert is a small message box which displays on-screen notification to give the user some kind
of information or ask for permission to perform certain kind of operation. It may be also used
for warning purpose.
Here are few alert scenarios
1)Simple Alert --This simple alert displays some information or warning on the screen.
2) Prompt Alert--This Prompt Alert asks some input from the user and selenium webdriver
can enter the text using sendkeys(" text to enter").
Syntax :
import org.openqa.selenium.Alert;
Alert alert = driver.switchTo().alert();
Alert is an interface. below are the methods that are used to handle the alerts
To Click on OK button. - alert.accept();
To click on Cancel button - alert.dismiss()
To get the text which is present on the Alert. - alert.getText();
To pass the text to the prompt popup - alert.sendkeys();
Example for alerts
import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class PopUp {
public static void main(String args[])throws Exception {
System.setProperty(“webdriver.gecko.driver”,”E:\\geckodriver.exe”);
WebDriver driver =new FirefoxDriver ();
driver.get ("http://127.0.0.1/orangehrm-2.6/login.php");
System.out.println (driver.getTitle ());
Mr. Suresh Page 66 of 139
Selenium Training by Suresh
driver.findElement (By.name ("txtUserName")).sendKeys ("suresh");
driver.findElement (By.name ("Submit")).click ();
Thread.sleep (2000L);
Alert a= driver.switchTo ().alert ();
System.out.println (a.getText ());
a.accept ();
driver.findElement (By.name ("txtPassword")).sendKeys ("suresh123");
driver.findElement (By.name ("Submit")).click ();
Thread.sleep (2000);
System.out.println ("Login completed");
driver.findElement (By.linkText ("Logout")).click ();
driver.quit ();
}
}
r.keyPress(KeyEvent.VK_ENTER);
r.keyRelease(KeyEvent.VK_ENTER);
Thread.sleep(3000L);
System.out.println("Login completed");
driver.findElement(By.linkText("Logout")).click();
System.out.println("Logout completed");
driver.quit();
}
}
JavaScript Executer
What are JavaScript Executors?
JavascriptExecutor interface is a part of org.openqa.selenium and implements
java.lang.Object class. JavascriptExecutor presents the capabilities to execute JavaScript
directly within the web-browser. To be able to execute the JavaScript, certain mechanisms in
the form of methods along with a specific set of parameters are provided in its
implementation.
JavaScript Executors
While automating a test scenario, there are certain actions those become an inherent part of
test scripts.
These actions may be:
•Clicking a button, hyperlink etc.
•Typing in a text box
•Scrolling Vertically or Horizontally until the desired object is brought into view
•And many more
Windows Handelers :
Get Window Handles. The Get Window Handles command of the WebDriver API returns a
list of all WebWindow s. Each tab or window, depending on whether you are using a tabbed
browser, is associated by a window handle that is used as a reference when switching to the
window
import java.util.ArrayList;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class WindowHandels {
public static void main(String args[]) throws Exception{
System.setProperty("webdriver.gecko.driver",
"D:\\Suresh_Selenium\\Drivers\\geckodriver.exe");
WebDriver driver = new FirefoxDriver();
driver.get("file:///D:/Suresh_Selenium/HtmlFiles/multiplewindows.html");
driver.findElement(By.id("btn1")).click();
Thread.sleep(3000);
driver.findElement(By.id("btn2")).click();
ArrayList<String> wind=new ArrayList<String>(driver.getWindowHandles());
driver.switchTo().window(wind.get(0));
Thread.sleep(3000);
driver.quit(); }
}
Now in above html table need to retrieve the row and coloumn count after that retrieve
the data from particular cell and whole webtable
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class Table {
public static void main(String[] args)throws Exception {
System.setProperty(“webdriver.gecko.driver”,”E:\\geckodriver.exe”);
WebDriver driver=new FirefoxDriver ();
driver.get("url");
//Count Details
int row =driver.findElements(By.xpath("//table[@id='idCourse']/tbody/tr")).size();
int col =driver.findElements(By.xpath("//table[@id='idCourse']/tbody/tr[1]/td")).size();
int rowcol =driver.findElements(By.xpath("//table[@id='idCourse']/tbody/tr/td")).size();
System.out.println(row);
System.out.println(col);
System.out.println(rowcol);
//To get Data from particular Cell
String data1 = driver.findElement(By.xpath("//table [@id='idCourse']/tbody/tr
[2]/td[2]")).getText();
System.out.println (data1);
//To get Data from all rows
for (int i=1;i<=row;i++) {
//for (int j=1;j<=col;j++) {
String data = driver.findElement(By.xpath("//table [@id='idCourse']/tbody/tr
["+i+"]")).getText ();
System.out.println(data);
}
}
driver.close();
}
}
import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.Statement;
import java.sql.ResultSet;
class Database{
public static void main(String args[]) {
try {
Connection con=DriverManager.getConnection ("jdbc: odbc: dsn1");
Statement st=con.createStatement ();
Thread.sleep (3000);
ResultSet rs=st.executeQuery ("select * from emptable");
while (rs.next()) {
System.out.println (rs.getString (2) +"\t"+rs.getString (3) +rs.getString (4) +"\t"+rs.getString
(5));
}
rs.close ();
st.close ();
con.close ();
}
catch (Exception e) {
System.out.println ("Error:"+e);
}
}
}
Mr. Suresh Page 79 of 139
Selenium Training by Suresh
12. How to Perfrom Click action with out using Click method
14. What are the Technical challenges you faced while working with Selenium
Automation
15. List the common errors you faced while working with Selenium
17. Write a code to Select single value & Multipul values from dropdown
19. Write a code to get Row count & Coloum count from WebTable & Write a code TO
retrive data from particular cell
Automation Frameworks
What an Automation Framework is?
A test automation framework is a set of assumptions, concepts and tools that provide support
for automated software testing. The main advantage of such a framework is the low cost for
maintenance. If there is change to any test case then only the test case file needs to be
updated and the Driver Script and Startup script will remain the same. Ideally, there is no
need to update the scripts in case of changes to the application.
Utility of Test Automation Framework
Provides an Outline of overall Test Structure
Ensures Consistency of Testing
Minimizes the Amount of Code for Development - thereby Less Maintenance
Maximizes Reusability
Reduces Exposure of Non-Technical Testers to Code
Enables Test Automation using Data
How Many Types of Automation Frameworks are there?
Generally there are 4 Types:
Data Driven Automation Framework
Keyword Driven Automation Framework
Modular Automation Framework
Hybrid Automation Framework
Modular Framework
Modular Framework is the approach where all the test cases are first analyzed to find out the
reusable flows. Then while scripting, all these reusable flows are created as functions and
stored in external files and called in the test scripts wherever required.
Enables creation of Small, Independent Scripts representing
Modules & Functions of the Application under Test (AUT)
Test Library Architecture Framework:
Enables creation of Library Files representing Modules & Functions of the
Project Suresh_Modular_Framework
Package com.hrms.LIB
general.java Maintains all the reusable fundtions related
to your project.
Eg:
openBrowser()
closeBrowser()
login()
logout()
addemp()
delemp()
etc….
global.java Maintains all the varibles & objects related
your project
Eg:
WebDriver driver,
application url,
UserName,
Password,
etc …
==========Objects==========
txt_UserName = "txtUserName"
btn_Login = "Submit"
link_logout = "Logout"
etc…
Package com.hrms.testscripts All the actual test cases need to written in
this package only
TC_HRMS_101
TC_HRMS_102
TC_HRMS_103
=========create com.hrms.LIB package and in that create global.java file=========
package com.hrms.lib;
import org.openqa.selenium.WebDriver;
public class Global {
//===================Varibles info======================
public WebDriver driver;
public String url = "http://127.0.0.1/orangehrm-2.6/login.php";
public String un = "admin";
public String pw = "admin";
//=======================Objects=====================
public String txt_loginname = "txtUserName";
public String txt_password = "txtPassword";
public String btn_login = "Submit";
public String link_logout = "Logout";
Mr. Suresh Page 85 of 139
Selenium Training by Suresh
}
===========create general.java file in same package=========
package com.hrms.lib;
import org.openqa.selenium.By;
import org.openqa.selenium.firefox.FirefoxDriver;
public class general extends Global {
public void openapplication(){
System.setProperty(“webdriver.gecko.driver”,”E:\\geckodriver.exe”);
driver = new FirefoxDriver();
driver.navigate().to(url); }
public void closebrowser(){
driver.quit();
}
public void login() throws Exception{
driver.findElement(By.name(txt_loginname)).sendKeys(un);
driver.findElement(By.name(txt_password)).sendKeys(pw);
driver.findElement(By.name(btn_login)).click();
Thread.sleep(3000);
}
public void logout(){
driver.findElement(By.linkText(link_logout)).click(); }
public void addemp(){
System.out.println("adding new emp"); }
public void delmp(){
System.out.println("delete emp"); }
}
=======create all automation test scripts under the package of –
com.hrms.testscripts=======
package com.hrms.testscripts;
import com.hrms.lib.*;
public class TC_hrms_101 {
public static void main(String args[]) throws Exception{
general g = new general();
//test case steps
g.openapplication();
g.login();
g.addemp();
g.delmp();
g.logout();
g.closebrowser();
}
}
Crate a testsuite (By using xml) to execute end to end flow and then run above 3 test test
cases.
1.TC_101_VerifyLogin
2.TC_102_AddNewEmp
3.TC_103_DelEmp
Note: Create automation scripts for below scenarios.(Company Location Test cases)
1.TC_101_VerifyLogin
2.TC_102_Add New Company Location
3.TC_103_Search For newly Added company Location
4.TC_104_Delete company Location
Note: Create automation scripts for below scenarios.(Company Property Test cases)
1.TC_101_VerifyLogin
2.TC_102_Add New Company property
3.TC_103_Delete company property
Step 2
In the Install dialog box, click the Add button
Step 3
1.In "Name", type TestNG.
2.In "Location", type http://beust.com/eclipse.
3.Click OK
Step 4
Notice that "TestNG - http://beust.com/eclipse" was populated onto the "Work with:"
textbox.
Check the "TestNG" check box as shown below, then click Next.
Note: In the latest Eclipse (Kepler) you don't have a checkbox for TestNG, instead you
click on question mark (help) icon which will open up the form, and you can select all
and installation will continue as for the remaining instructions. Thanks Jana for the tip!
Step 5
Click next again on the succeeding dialog box until you reach the License Agreement
dialog.
Click "I accept the terms of the license agreement" then click Finish.
Step 6
Wait for the installation to finish
Step 7
When Eclipse prompts you for a restart, just click Yes.
Step 8
After the restart, verify if TestNG was indeed successfully installed. Click Window >
Preferences and see if TestNG is included on the Preferences list.
OR
Installation:
Select help menu option in eclipse
Select eclipse market place option
Search for TestNG plugin
Click on install btutton
Click on Next
Accept license
Click on finish btn
Restart eclipse
Step 2: download and Add Testng .Jar file to project
Go to TestNG.org site
Click on downloads
Click on “You can download the current release version of TestNG here”.
Add the .jar files to the project
Example:.
import org.testng.annotations.Test;
public class TC_TestNG {
@Test
public void login(){
System.out.println("login completed");
}
@Test(dependsOnmethods="login")
public void logout(){
System.out.println("Logout completed");
}
}
Note: in above example logout method will get executed only in case of login method got
passed other it will skip the logout method
login completed
delete emp
logout completed
login completed
Adding new emp
logout completed
}
Before Executing the program
Parallel Execution : Running the testcases with multipul browsers using WebDriver
with TestNG
This program will open the two browsers - one is Chrome and another is Firefox and it will
execute the test scrips parallel.
============= TC_101 =============
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.testng.Reporter;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Parameters;
import org.testng.annotations.Test;
public class TC_101 {
WebDriver driver;
@Test
public void openFF() throws Exception {
Hybrid Framework
Note: While working with Selenium we had an option to implement Log4j also .In below
will discuss in detail to implement Log4j with our Framework.
Log4j-Logger
Selenium with Logs (Log4j)
Sometimes logging is considered to be an overhead upon the existing script creation
mechanism but experts considers it to be one of the best practices if used in the accurate
proportion because of the following advantages:
Advantages of Logging in Selenium Scripts:
Grants a complete understanding of test suites execution
Log messages can be stored in external files for post execution scrutiny
Logs are an exceptional assistant in debugging the program execution issues and
failures
Logs can also be reviewed to ascertain the application’s health by the stakeholders
Log4j – A Java based Logging API
Moving on to the technical details about logging, let us discuss the origin of the API that we
would be using throughout the log4j to generate logs. Log4j was a result of collaborative
efforts of people at Secure Electronic Marketplace for Europe to develop a utility that would
help us generating logs and hence the log4j came into limelight in the year 1996. Log4j is an
open source tool and licensed under IBM Public License.
There are three main components that constitute the implementation of log4j. These
Mr. Suresh Page 104 of 139
Selenium Training by Suresh
components represent the details about the log level, formats of the log message in which
they would be rendered and their saving mechanisms.
Constituents of Log4j
1. Loggers
2. Appenders
3. Layouts
#1) Loggers
The following steps need to done in order to implement loggers in the project.
Step 1: Creating an instance of Logger class
Step 2: Defining the log level
Logger Class – It is a java based utility that has got all the generic methods already
implemented so that we are enabled to use log4j.
Log levels – Log levels are popularly known as printing methods. These are used for printing
the log messages. There are primarily five kinds of log levels.
error()
warn()
info()
debug()
log()
Thus, to be able to generate logs, all we need to do is to call any of the printing method over
the logger instance. We will have a broader look into it during the implementation phase.
#2) Appenders
Now that we know how to generate these logs, the next thing that should pop up into our
minds is that where do I get to view the logs? The answer to this question lies in the
definition of “Appenders”.
Appenders are consistently used to specify the data source/medium where the logs should be
generated. The scope of data sources stretches from various external mediums like console,
GUI, text files etc.
#3) Layouts
At times, user wishes certain information to be pre – pended or appended with each log
statement. For example I wish to a print a timestamp along with my log statement. Thus, such
requirements can be accomplished by “Layouts”.
Layouts are a utility that allows the user to opt for a desired format in which the logs would
be rendered. Appenders and Layout have a tight coupling between them. Thus, we are
required to map each of the appender with a specific layout.
Take a note that user is leveraged to define multiple appenders, each mapped with a distinct
layout
Jenkins
Jenkins - History
2005 - Hudson was first release by Kohsuke Kawaguchi of Sun Microsystems
2010 – Oracle bought Sun Microsystems
o Due to a naming dispute, Hudson was renamed to Jenkins
Oracle continued development of Hudson (as a branch of the original)
About Jenkins
Jenkins is an open source tool written in Java.
Jenkins is CI (Continuous Integration) tool which will help you to run test in easy
manner.
Jenkins is a self-contained, open source automation server which can be used to
automate all sorts of tasks related to building, testing, and delivering or deploying
software.
Steps to configure Jenkins with Selenium
1.Generate batch file
2.Download Jenkins .exe file and Install the same
3.Configure pre-defined settings(JDK path and Email Configuration)
4.Create a job Schedule
Steps to Generate bacth file
Create lib folder in project root directory
Copy all the required jar file to run the project in to created lib folder
Save the file as run.bat ,by then batch file will be created
Perform double click on run.bat , by that you should be able to see that scripts are running.
Once scripts are running then we can confirm batch file created successfully.
Download to your local system and just u can double click on .exe file it will automatically
get installed
Once installation is completed open any browser and type http://localhost:8080/ then u will
be able to see Jenkins home page as below .By this you can confirm that Jenkins had installed
successfully
Provide JDK Name as JAVA_HOME and JAVA_HOME (JDK path installed in your system)
,make sure you Uncheck the install automatically check box
Click on use custom workspace checkbox and give your Selenium script project workspace
path – (provide path including java project name)
Then go to Build and Select – Execute Windows batch command option from the drop-down
box.
Provide the batch file name which you created in project workspace
To run build automatically provide schedule details by clicking on Build periodically check
box opion[This setting is optional]
To execute the script from Jenkins(manually) now click on created job and select BuildNow
option by that it will execute the program will provide the results
Now you will be able to see build is executing and status shown as below
Click on build which u excuted to see the execution log information and then click on
Console output option, then it will shows the execution log information
Git HUB(https://github.com/)
Github is a repository on web, which support all the feature of revision control and source
code management
Steps to Integreate GitHub with Selenium Project in Eclipse:
Create an account in github with your valid email and other information.
Login to github account and create new repository
Specify the name of the repository, description and click on create repository.
Now open Eclipse and Select project which we want to upload on github.
Perform right click on project and Go to team section and Select share project.
Select the required files to upload from Unstaged Changes box and click on + symbol, by
Mr. Suresh Page 116 of 139
Selenium Training by Suresh
that those files will be moved to Staged Chnages box.
Provide commit message ,author and committer details and click on commit button
Once we are getting this window we completed to push the code to git reposity.
Mr. Suresh Page 118 of 139
Selenium Training by Suresh
To confirm we can goto git repository and check either code is moved to repository or not
Note: if required we can download this code into another team member system and then we
can make required modifications.
POM - PageObjectModel
Why POM --- The main advantage of Page Object Model is that if the UI changes for any
page, it don’t require us to change any tests, we just need to change only the code within the
page objects (Only at one place). Many other tools which are using selenium are following
the page object model.
What is POM?
Page Object Model is a design pattern to create Object Repository for web UI
elements.
Under this model, for each web page in the application there should be corresponding
page class.
This Page class will find the WebElements of that web page and also contains Page
methods which perform operations on those WebElements.
Name of these methods should be given as per the task they are performing
Advantages of POM :
1. Page Object Patten says operations and flows in the UI should be separated from
verification. This concept makes our code cleaner and easy to understand.
2. Second benefit is the object repository is independent of testcases, so we can use the
same object repository for a different purpose with different tools. For example, we
can integrate POM with TestNG/JUnit for functional testing and at the same time with
JBehave/Cucumber for acceptance testing.
3. Code becomes less and optimized because of the reusable page methods in the POM
classes.
4. Methods get more realistic names which can be easily mapped with the operation
happening in UI.
Mr. Suresh Page 119 of 139
Selenium Training by Suresh
Try with POM framework as below structure –
Apache-MAVEN
MAVEN INTRODUCTION
Apache Maven, an open source build framework that can be used to build projects and it
provides developers a complete build life-cycle framework.
Originally Maven was designed to simplify building processes in Jakarta Turbine project.
The Main Objectives of Maven are:
•It follows the best practices and standards which helps new developers coming into a project
•It provides quality information of the project like test reports, dependency list etc.
•It provides a uniform build system with its project object Model.
Maven is a project management tool, provides concept of a project object model (POM) file
to manage project’s build, dependency and documentation. The most powerful feature is
able to download the project dependency libraries automatically
Let see how to configure eclipse with maven for selenium: (assuming eclipse is already there
or you can go to http://www.eclipse.org/downloads/packages/release/juno/sr2)
Launch the Eclipse IDE.
Create a new project by selecting File |New | Other from Eclipse Main Menu.
On the New dialog, select Maven |Maven Project as shown in the following
screenshot:
Next, the New Maven Project dialog will be displayed. Select the Create a
simple project (skip archetype selection) check-box and set everything to default and
click on the Next button as shown in the following screenshot:
On the New Maven Project dialog box, enter base package name (like
com.myproject.app) in Group Id and project name (like myproject) in Artifact Id
textboxes. You can also add a name and description. Set everything to default and
click on the Finish button as shown in the following screenshot:
Right-click on JRE System Library [J2SE-1.5] and select the Properties option
from the menu.
On the Properties for JRE System Library [J2SE-1.5] dialog box, make sure
Workspace default JRE (jre7) is selected. If this option is not selected by default,
select this option.
Note: The JRE version might change based on the Java version installed on your machine.
Click on the OK button to save the change as shown in the following screenshot:
Select pom.xml from Package Explorer. This will open the pom.xml file in the
editor area with the Overview tab open. Select the pom.xml tab instead.
Add the WebDriver and testng dependencies highlighted in the following code
snippet, to pom.xml in the <project> node:
------------------------------------------------------------------------
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.myproject.app</groupId>
<artifactId>myproject</artifactId>
<version>0.0.1-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>3.12.0</version>
</dependency>
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>6.8.0</version>
Mr. Suresh Page 122 of 139
Selenium Training by Suresh
<scope>test</scope>
</dependency>
</dependencies>
</project>
Cucumber
What are the benefits?
1. It is helpful to involve business stakeholders who can't easily read code
2. Cucumber focuses on end-user experience
3. Style of writing tests allow for easier reuse of code in the tests
4. Quick and easy set up and execution
5. Efficient tool for testing
Introduction
Cucumber introduces the notion of “features” which describe the behavior you wish to test.
The Feature is then broken down into a number of different “scenarios” which comprise the
test you wish to execute which will subsequently validate the feature. Each scenario is further
broken down into a number of “steps” which describe the execution path of each scenario.
Typically, these follow a strict “given-when-then” format which aids consistency and
provides a clear Template for writing acceptance tests.
Testing with Cucumber
Cucumber is a testing framework that helps to bridge the gap between software developers
and business managers. Tests are written in plain language based on the behavior-driven
development (BDD) style of Given, When, Then, which any layperson can understand. Test
cases are then placed into feature files that cover one or more test scenarios. Cucumber
interprets the tests into the specified programming language and uses Selenium to drive the
test cases in a browser. Our tests are translated into Java code.
The Given, When, Then syntax is designed to be intuitive. Consider the syntax elements:
Given provides context for the test scenario about to be executed, such as the point in
your application that the test occurs as well as any prerequisite data.
When specifies the set of actions that triggers the test, such as user or subsystem actions.
Then specifies the expected result of the test.
}
6. Now you can exeute the program by using two option one is feature file and another one is
TestRun
Executing by Feature File - Rightclick on hrms.feature file and Select Run as Cucumbe
feature. Results log need to shown as below
Executing by TestRun File - Rightclick on TestRun file and Select Run as JUnitTest.
Results shown in the path(C:\Training1\Cumber_HRMS\target\cucumber-html-report) as
below.
Sikuli-script.jar will be added to your project build path. You’re done. Now you can start
writing Sikuli scripts inside this project.
Example for - TC_adding new emp –Clicking on browse button and selecting an file to
upload an image using WebDriver with Sikuli
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.sikuli.script.Pattern;
import org.sikuli.script.Screen;
public class WinPopup {
public static void main(String[] args) throws InterruptedException {
System.setProperty(“webdriver.gecko.driver”,”E:\\geckodriver.exe”);
WebDriver driver=new FirefoxDriver();
driver.navigate().to("http://127.0.0.1/orangehrm-2.6/login.php");
driver.findElement(By.xpath("//input[@type='text']")).sendKeys("admin");
driver.findElement(By.xpath("//input[@type='password']")).sendKeys("admin");
driver.findElement(By.xpath("//input[@type='Submit']")).click();
Thread.sleep(5000L);
//Selecting the frame
driver.switchTo().frame("rightMenu");
For Chrome:
java -jar selenium-server-standalone-2.41.0.jar -role webdriver -hub
http://localhost:4444/grid/register -port 5556 -browser browserName=chrome
There are few scenarios where you may need browser from each type i.e.: IE, Chrome and
Firefox.
For instance you may need to use 1 IE and 1 Firefox and 1 Chrome browser
java -jar selenium-server-standalone-2.41.0.jar -role webdriver -hub
http://localhost:4444/grid/register -port 5556 -browser browserName=iexplore
-browser browserName=firefox -browser browserName=chrome
HTTP methods
Commonly used in REST based architecture.
GET − Provides a read only access to a resource.
POST − Used to create a new resource.
DELETE − Used to remove a resource.
PUT − Used to update existing resource or create a new resource.
Sample program to run api :
Note: Download and add rest assured jars to the respective project.
package Test;
import io.restassured.RestAssured;
import io.restassured.response.Response;