SlideShare a Scribd company logo
About Author:
Rajesh Kumar
Bachelor of Technology graduate in Computer Science from Uttar Pradesh Technology
University in 2004. He has started his career as an automation engineer in 2004 and has
14+ years of experience in automation domain. He has worked with top
notch organization in e-Commerce, e-Learning, Travel and Banking Domain.
Currently he is working as an automation architect with a multinational company. He is
very passionate about exploring different automation tools for functional and non-
functional automation. He is a subject matter expert for functional automation tools i.e.
Win Runner, QTP (Quick Test Professional), RFT (Rational Functional Tester), Silk Test,
Selenium, Test Complete, Appium and SeeTest. He has extensive experience in
automation team building, Automation tools training, automation framework development
and automation project supports as SME.
Table of Contents
Chapter-1| ‘Hello World’ Program.............................................................................................. 3
Chapter-2 | Java Basic Concept- Part-1....................................................................................... 5
Chapter-3 | Java Basic Concept- Part-2....................................................................................... 8
Chapter-4 | A Closer Look at the "Hello World!" ...................................................................... 12
Chapter-5 | A Closer Look at Function...................................................................................... 14
Chapter-6 | Control Flow Statements....................................................................................... 17
Chapter-7 | File Input Output Operations................................................................................. 20
Chapter-8 | First Selenium Program ......................................................................................... 23
Chapter-9 | A Closer Look at First Selenium Program............................................................... 27
Chapter-10 | Identifying Objects Uniquely ............................................................................... 29
Chapter-11 | Advance Technique to Compose CSS and XPATH locator..................................... 32
Chapter-1| ‘Hello World’ Program
Step-1 | Choosing Automation Tool and Language
The first step to start learning automation is to finalize on the tool/API and the language.
This is the most problematic step to decide on the tool and the language. Your search for
the latest market trend, consult your friends from the automation background and even
your senior. Everyone will have a different opinion. Even my opinion changes with time
and with the person I am talking to so, the best way are to go with the Public Poll.
Choose the tool and language with the highest community support and is open source.
Nowadays Selenium with Java is the best suite for you to learn automation. I know
JavaScript is gaining more popularity. Also, Mobile automation is gaining more popularity
then desktop automation as mobile users and mobile apps are increasing exponentially.
But, just don't forget we are talking about the first step.
Step-2 | Installing Eclipse and Java
This is the most difficult step for the person who wants to start with automation. Even I
have given up for many tools before I have started. Installation and configuration are the
most tricky and irritating job. The reason is we do not know which version is required what
all software's are required. What setting need to be done blah blah….
To make it easy for you guys/gals, we will take step by step.
1. Check if java is installed on your machine if not install it using following steps
2. Use java –version command on command prompt to check java version on your
machine. In case it is not installed on your machine you will get error message. In
case you have a java version which is older than 1.6 then upgrade it
3. Download latest version of Java SE Development Kit from following
location: http://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-
2133151.html
4. Install latest version of Java (64 bit or 32 bit) corresponding to your machine operating
system
5. Download Eclipse (64 bit or 32 bit) corresponding to your machine operating
system: https://eclipse.org/downloads/
6. Create a new folder “AutomationWorkspace” in your D drive or any other drive of
your machine
7. Unzip eclipse folder and navigate to the folder where you will see eclipse.exe
8. Double click on eclipse.exe to open Eclipse and provide the path of
the “AutomationWorkspace” when pop-up appears for ‘select a workspace’ and
click on ‘OK’ button.
9. Click on File -- New – Others
10.Select ‘Java Project’ from the ‘Select a wizard’ model window and click on
‘Next’ button
11.Enter Project name as ‘HelloWorld’ in ‘Create a Java Project’ model window and
click on ‘Finish’
12.Click on + (expansion sign) in ‘Package Explorer’ pane to expend the project folder
13.Add a package to your project folder using following steps:
ü Mouse Right click on ‘src’ folder
ü Select New -- Package
ü Enter Package Name as ‘mypackage’
14.Add a class to your package created in above step using following steps:
ü Mouse Right click on ‘mypackage’folder
ü Select New -- Class
ü Enter Class Name as ‘MyClass’
15.Write your first Hello World Program
package mypackage;
public class MyClass {
public static void main (String args[]){
System.out.println("Hello World !!");
}
}
16.Click on Run button and Enjoy
Challenges You Might Face:
1. You might face some issue when you are installing Java for the first time on your
machine
2. Java Home need to be set in Environment variable (you will get many article and
videos)
3. Java version should be compatible with your Eclipse version that you have
downloaded else eclipse will throw error while launching. You can check it online
which version of eclipse is compatible with which java version.
Note: You can always post your question in case facing any issue. I will be happy to help
you all, but don’t give up.
“The more you know, the more you know you don't know.” - Aristotle
Chapter-2 | Java Basic Concept- Part-1
Bad habits die hard; it’s very true as we all have the tendency to achieve most with least
effort. So, I will try to cover least required to come to a platform from where you can start
working on automation. But, before we start working on automation we should at least
learn few concepts which will help you in understanding what you are doing.
Variables:
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.
Data Type:
There are two data types available in Java:
Primitive Data Types:
There are eight primitive data types supported by Java. Primitive data types are
predefined by the language and named by a keyword:
§ byte e.g. byte a = 100
§ short e.g. short s = 10000
§ int e.g. int a = 100000
§ float e.g. float f1 = 234.5
§ double e.g. double d1 = 123.44
§ boolean e.g. boolean one = true
§ char e.g. char letterA ='A'
Reference/Object Data Types:
Reference variables are created using defined constructors of the classes. They are used
to access objects.
Arithmetic Operators:
+ Additive operator (also used for String concatenation)
- Subtraction operator
* Multiplication operator
/ Division operator
% Remainder operator
Equality and Relational Operators:
== Equal to
!= Not equal to
> Greater than
>= Greater than or equal to
< Less than
<= Less than or equal to
Conditional Operators:
&& Conditional-AND
|| Conditional-OR
Make your hands dirty by practicing above concepts through code:
Sample 1:
Create another class ‘Test1’ in you ‘mypackage’ as done in previous session. Copy and
paste below code and run to see the output
package mypackage;
public class Test1 {
public static void main (String args[]){
int a;
int b;
int c;
a = 5.45;
b=10.55;
c = a + b;
System.out.println("Sum of a and b is :: " + c);
}
}
Sample 2:
Create another class ‘Test2’ in you ‘mypackage’ as done in previous session. Copy and
paste below code and run to see the output
package mypackage;
public class Test2 {
public static void main (String args[]){
int a;
int b;
int c;
a = 5;
b=10;
c = a + b;
System.out.println("Sum of a and b is :: " + c);
}
}
Sample 3:
Create another class ‘Test3’ in you ‘mypackage’ as done in previous session. Copy and
paste below code and run to see the output
package mypackage;
public class Test3 {
public static void main (String args[]){
int a;
int b;
int c;
a = Testing;
b= qauser;
c = a + b;
System.out.println("Sum of a and b is :: " + c);
}
}
"We learn from failure, not from success" - Bram Stoker
Chapter-3 | Java Basic Concept- Part-2
Strings, which are widely used in Java programming, are a sequence of characters. In
the Java programming language, strings are objects.
The Java platform provides the String class to create and manipulate strings.
String Length:
Using this method, you can find number of characters contained in the string object
package mypackage;
public class StringLength {
public static void main(String args[]) {
String TestString = "I am learning Selenium with Java";
int len = TestString.length();
System.out.println("String Length is : " + len);
}
}
Concatenating Strings:
This returns a new string that is string1 with string2 added to it at the end.
package mypackage;
public class StringConcat {
public static void main(String args[]) {
String String1 = "Selenium with ";
String String2 = "Java";
String String3 = String1 + String2;
System.out.println("Final string after concatination method-1 is :: " + String3);
// Another way of doing what we have done above
String String4 = String1.concat(String2);
System.out.println("Final string after concatination method-2 is :: " + String4);
}
}
IndexOf:
Returns the index within this string of the first occurrence of the specified substring.
package mypackage;
public class StringIndex {
public static void main(String args[]) {
String TestString = " Learning Selenium from Selenium Community";
int Index = TestString.indexOf("Selenium");
System.out.println("Index of Selenium in above string : " + Index);
}
}
LastIndexOf:
Returns the index within this string of the last occurrence of the specified substring.
package mypackage;
public class StringLastIndex {
public static void main(String args[]) {
String TestString = "Learning Selenium from Selenium Community";
int FirstIndex = TestString.indexOf("Selenium");
System.out.println("First Index of Selenium in above string : " + FirstIndex);
int LastIndex = TestString.lastIndexOf("Selenium");
System.out.println("Last Index of Selenium in above string : " + LastIndex);
}
}
Split:
Splits this string around matches of the given regular expression.
package mypackage;
public class StringSpliting {
public static void main(String args[]) {
String TestString = "Your Booking Reference Number is 234567891";
String[] StringParts = TestString.split(" ");
System.out.println("Reference Number in above string : " + StringParts[5]);
}
}
SubString:
Returns a string that is a substring of this string. The substring begins with the character
at the specified index and extends to the end of this string.
package mypackage;
public class SubString {
public static void main(String args[]) {
String TestString = "Your Booking Reference Number is 234567891";
int FirstIndex = TestString.indexOf("is");
String StringParts = TestString.substring(FirstIndex + 3);
System.out.println("Sub string i.e. Reference Number in above string :
" + StringParts);
}
}
Replace:
Replaces each substring of this string that matches the literal target sequence with the
specified literal replacement sequence.
package mypackage;
public class StringReplace {
public static void main(String args[]) {
String TestString = "Your Booking Reference Number is 234567891";
String ReplacedString = TestString.replace("Your", "Customer");
System.out.println("Initial String:: " + TestString);
System.out.println("Replaced String:: " + ReplacedString);
}
}
Lower/UpperCase:
Converts all of the characters in this String to Lower / Upper case
package mypackage;
public class StringUpperLowerCase {
public static void main(String args[]) {
String TestString = "Your Booking Reference Number is 234567891";
String StringLowerCase = TestString.toLowerCase();
System.out.println("Lower Case String:: " + StringLowerCase);
String StringUpperCase = TestString.toUpperCase();
System.out.println("Upper Case String:: " + StringUpperCase);
}
}
Compare:
Compare two string either considering case sensitivity or ignoring case sensitivity.
package mypackage;
public class StringComparision {
public static void main(String args[]) {
String ExpectedString = "Your Booking Reference Number is 234567891";
String ActualString = "Your booking reference number is 234567891";
System.out.println("Result considering case senstivity::
" + ActualString.equals(ExpectedString));
System.out.println("Result ignoring case senstivity::
" + ActualString.equalsIgnoreCase(ExpectedString));
}
}
Trim:
Returns a string whose value is this string, with any leading and trailing whitespace
removed.
package mypackage;
public class StringTrim {
public static void main(String args[]) {
String TestString = " Your Booking Reference Number is
234567891 ";
String TrimmedString = TestString.trim();
System.out.println("Actual String:: " + TestString);
System.out.println("String after trim:: " + TrimmedString);
}
}
“Tell me and I forget, teach me and I may remember, involve me and I
learn” - Benjamin Franklin
Chapter-4 | A Closer Look at the "Hello World!"
In our first session we have created a program for “Hello World”. After that we have
learned few more programs related to integer and string. Now, let’s have a close look of
the very first program that has been created to test the Java, Eclipse set-up and
configuration.
package mypackage;
public class MyClass {
public static void main (String args[]){
System.out.println("Hello World !!");
}
}
When you will have a closure look of the above program. You will find following:
§ Package
§ Class
§ Main Method
§ Source Code
Package:
Our program is starting with a package statement [package mypackage;]. Package can
be defined as a grouping of related types (classes, interfaces, enumerations and
annotations) providing access protection and name space management. When you
create a Class file system automatically create a default package. But it is always
suggested not to use the default package and create a package of your own.
Class:
Every package has Class in it e.g. [public class MyClass]. Every class has a class body
(the area between the braces) contains all the code that provides for the life cycle of the
objects created from the class.
Class can be defined as a template/blue print that describes the behaviors/states that
object of its type support. In general, class declarations can include these components,
in order:
1. Modifiers such as public, private, and a number of others that you will encounter
later.
2. The class name, with the initial letter capitalized by convention.
3. The class body, surrounded by braces, {}.
Main Method:
In the Java programming language, every application must contain a main method whose
signature is:
public static void main(String[] args)
§ The main method accepts a single argument: an array of elements of type String
i.e. String[] args
§ This array is the mechanism through which the runtime system passes information
to your application
Source Code:
System.out.println("Hello World !!");
Let's look at the components of this line:
§ System tells the system to do something.
§ out tells the system that we are going to do some output stuff.
§ println stands for "print line," so we are telling the system to print a line in the
output.
§ The parentheses around ("Hello World.") means that the method
System.out.println() takes in a parameter, which, in this case, is the String "Hello
World."
Note that there are some rules in Java that we have to adhere to:
§ You must always add a semicolon at the end of every line.
§ Java is case sensitive, so you must write method names, variable names, and
class names in the correct case or you will get an error.
§ Blocks of code specific to a certain method or loop are encased between curly
brackets.
Access Level Modifier:
Access level modifiers determine whether other classes can use a particular field or
invoke a particular method. There are two levels of access control:
At the top level—public, or package-private (no explicit modifier).
At the member level—public, private, protected, or package-private (no explicit modifier).
A class may be declared with the modifier public, in which case that class is visible to all
classes everywhere. Also, class always has access to its own members.
“Teaching is only demonstrating that it is possible. Learning is making it possible
for yourself” - Paulo Coelho
Chapter-5 | A Closer Look at Function
In Java, all function definitions must be inside classes. We also call functions methods.
Let's look at an example method:
package mypackage;
public class Functions {
public static void FunctionWithoutParam(){
String String1 = "How to Learn Selenium?";
System.out.println("Ques: ".concat(String1));
}
public static void FunctionWithParam(String sQuestion){
System.out.println("Ques: ".concat(sQuestion));
}
public static void main (String args[]){
FunctionWithoutParam();
FunctionWithParam("How to Learn Java?");
}
}
• Static means this method belongs to the class Functions and not to a specific instance
of Functions
• void means this method doesn't return a value. Methods can return a single value in Java
and it has to be defined in the method declaration. However, you can use return by itself
to exit the method.
• First method doesn't get any arguments, but of course Java methods can get arguments
as we'll which is shown in second method.
• Non static methods in Java are used more than static methods. Those methods can only
be run on objects and not on the whole class.
Calling one function in another function within same class:
package mypackage;
public class FunctionCalling {
public static void CalledFunctionWithoutParam(){
System.out.println("Calledfunction will be called by calling function");
}
public static void CalledFunctionWithParam(String sArgument){
System.out.println(sArgument);
}
public static void CallingFunction(){
CalledFunctionWithoutParam();
CalledFunctionWithParam("Argument to be passed in the called function");
}
public static void main (String args[]){
CallingFunction();
}
}
Let’s have a close look of the above example. In above example we have
a class FunctionCalling which contains 3 simple methods/function and 1 main
method/function. Since java program should have at least 1 main method which is the
execution point.
Wehave 2 methods/functioni.e. CalledFunctionWithoutParam and CalledFunctionWi
thParam. First one will not accept any argument while second function will accept an
argument. Both these functions/method are called function which mean they will be called
by the 3 function i.e. CallingFunction.
Calling one function in another function within another class:
We are going to create 2 classes
CalledClass:
This class will have 2 functions/methods
i.e. CalledFunctionWithoutParam & CalledFunctionWithParam
package mypackage;
public class CalledClass {
public void CalledFunctionWithoutParam(){
System.out.println("Function from another class to be called");
}
public void CalledFunctionWithParam(String sArgument){
System.out.println(sArgument);
}
}
CallingClass:
This class will have a calling function/method i.e. CallingFunction and Main method.
package mypackage;
public class CallingClass {
static CalledClass CalledFunctionClass = new CalledClass();
public static void CallingFunction(){
CalledFunctionClass.CalledFunctionWithoutParam();
CalledFunctionClass.CalledFunctionWithParam("Argument to be passed in the
called function form another class");
}
public static void main (String args[]){
CallingFunction();
}
}
Observation:
• We cannot call the function just by providing the name of the calling function in called
function as we were doing while calling a function within same class
• When you are calling a function from another class then you will have to create an
instance of the class from where you are calling the function.
• This is done using the
statement static CalledClass CalledFunctionClass = new CalledClass();
• Now using the object instance i.e. CalledFunctionClass we can call the function with that
class
i.e. CalledFunctionClass.CalledFunctionWithoutParam(); CalledFunctionClass.Cal
ledFunctionWithParam("Argument to be passed in the called function form another
class");
• CallingFunction method is a static method so when we are creating an instance
of called class, we are declaring it asstatic else you won’t be able to call as calling
method is a static method.
“The beautiful thing about learning is nobody can take it away from you” - B.B.
King
Chapter-6 | Control Flow Statements
The if-then Statement:
The if-then statement is the most basic of all the control flow statements. It tells your
program to execute a certain section of code only if a particular test evaluates to true e.g.
package mypackage;
public class IfThenStatement {
public static void main(String args[]){
String AutomationTool = "QTP";
if (AutomationTool.equalsIgnoreCase("QTP")){
System.out.println("Automation tool has it's own Object Repository");
}
if(AutomationTool.equalsIgnoreCase("RFT")){
System.out.println("This is not going to be printed on console");
}
}
}
The if-then-else Statement:
The if-then-else statement provides a secondary path of execution when an "if" clause
evaluates to false.
package mypackage;
public class IfThenStatement {
public static void main(String args[]){
String AutomationTool = "QTP";
if (AutomationTool.equalsIgnoreCase("RFT")){
System.out.println("This is not going to be printed on console");
}
else{
System.out.println("Automation tool has it's own Object Repository");
}
}
}
The for Statement:
The for statement provides a compact way to iterate over a range of values. Programmers
often refer to it as the "for loop" because of the way in which it repeatedly loops until a
particular condition is satisfied. The general form of the for statement can be expressed
as follows:
for (initialization; termination;
increment) {
statement(s)
}
When using this version of the for statement, keep in mind that:
• The initialization expression initializes the loop; it's executed once, as the loop begins.
• When the termination expression evaluates to false, the loop terminates.
• The increment expression is invoked after each iteration through the loop; it is perfectly
acceptable for this expression to increment or decrement a value.
The following program, ForLoop, uses the general form of the for statement to print the
numbers 1 through 10 to standard output:
package mypackage;
public class ForLoop {
public static void main(String[] args){
for(int i=1; i<11; i++){
System.out.println("Count is: " + i);
}
}
}
The switch Statement:
Unlike if-then and if-then-else statements, the switch statement can have a number of
possible execution paths. A switch works with the byte, short, char, and int primitive data
types. It also works with enumerated types (discussed in Enum Types), the String class,
and a few special classes that wrap certain primitive types: Character, Byte, Short,
and Integer (discussed in Numbers and Strings).
The following code example, SwitchDemo, declares an int named month whose value
represents a month. The code displays the name of the month, based on the value
of month, using the switch statement.
package mypackage;
public class SwitchDemo {
public static void main(String[] args) {
int month = 8;
String monthString;
switch (month) {
case 1: monthString = "January";
break;
case 2: monthString = "February";
break;
case 3: monthString = "March";
break;
case 4: monthString = "April";
break;
case 5: monthString = "May";
break;
case 6: monthString = "June";
break;
case 7: monthString = "July";
break;
case 8: monthString = "August";
break;
case 9: monthString = "September";
break;
case 10: monthString = "October";
break;
case 11: monthString = "November";
break;
case 12: monthString = "December";
break;
default: monthString = "Invalid month";
break;
}
System.out.println(monthString);
}
}
"Any fool can know. The point is to understand" - Albert Einstein
Chapter-7 | File Input Output Operations
Create a file in Java:
The File.createNewFile() method is used to create a file in Java, and return
a boolean value : true if the file is created successful; false if the file is already exists or
the operation failed.
package mypackage;
import java.io.File;
public class CreateFile {
public static void main(String[] args) {
try {
File file = new File("src/newfile.txt");
if (file.createNewFile()) {
System.out.println("File is created!");
} else {
System.out.println("File already exists.");
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
Note: You can use the same function to create a .json and .properties file. These file
types are mostly used for the automation to accept input or write output.
Write to file using BufferedWriter:
In Java, BufferedWriter is a character streams class to handle the character data. Unlike
bytes stream (convert data into bytes), you can just write the strings, arrays or characters
data directly to file e.g.
package mypackage;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
public class WriteFileBufferedStream {
public static void main(String[] args) {
try {
String content = "This is the content to write into file";
File file = new File("src/newfile.txt");
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(content);
bw.close();
System.out.println("Done");
} catch (Exception e) {
e.printStackTrace();
}
}
}
Append to file using BufferedWriter:
package mypackage;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.PrintWriter;
public class AppendFileBufferedStream {
public static void main(String[] args) {
try(FileWriter fw = new FileWriter("src/newfile.txt", true);
BufferedWriter bw = new BufferedWriter(fw);
PrintWriter out = new PrintWriter(bw))
{
out.println("the text");
//more code
out.println("more text");
//more code
} catch (Exception e) {
System.out.println(e);
}
}
}
How to READ file in Java – BufferedReader
In Java, there are many ways to read a file, here we show you how to use the simplest
and most common-used method –BufferedReader.
package mypackage;
import java.io.BufferedReader;
import java.io.FileReader;
public class ReadFileBufferedReader {
public static void main(String[] args) {
BufferedReader br = null;
try {
String sCurrentLine;
br = new BufferedReader(new FileReader("src/newfile.txt"));
while ((sCurrentLine = br.readLine()) != null) {
System.out.println(sCurrentLine);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
"In learning you will teach, and in teaching you will learn" - Phil Collins
Chapter-8 | First Selenium Program
We have learnt and practiced good enough concepts that are required for creating
automated test script using Selenium. In our first selenium script we are not going to use
all the concepts but as we advance further those concepts will be required very frequently.
To create our first automated script using selenium we further need to download and
configure selenium-server jar. Follow the steps below for set-up and configuration:
Step-1:
Create a ‘jars’ folder inside your project folder i.e.’HelloWorld’
Step-2:
Download selenium standalone server from following location:
http://www.seleniumhq.org/download/
Step-3:
Copy downloaded Selenium Standalone Server into your ‘jars’ folder created in step-1
Step-4:
Mouse Right click on your project folder ‘HelloWorld’ in Eclipse and click
on ‘Refresh’ option
Step-5:
You will see ‘jars’ folder and selenium standalone server inside it in ‘Package
Explorer’ pane of Eclipse
Step-6:
Mouse Right click on your project folder ‘HelloWorld’ in Eclipse again and perform
following steps:
§ Click on Build Path à Configure Build Path
§ Click on ‘Add External Jars’ button on ‘Properties for HelloWorld’ model
opened
§ Navigate to ‘jars’ folder and select ‘Selenium Standalone Server’ jar
§ Click on ‘Open’ button
§ Click on ‘Apply’ button
Step-7:
Download ‘geckodriver.exe’ from following location and copy it into your ‘jars’ folder
https://github.com/mozilla/geckodriver/releases
Step-8:
Make sure that you have the latest version of Firefox browser i.e. 49.0 or above
Step-9:
Create one class ‘FirstSeleniumProgram’ in ‘mypackage’
Step-10:
Copy and paste the following code for execution on Firefox browser:
package mypackage;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
public class FirstSeleniumProgram {
public static void main(String args[]) throws InterruptedException{
System.setProperty("webdriver.gecko.driver","jars/geckodriver.exe");
DesiredCapabilities capabilities=DesiredCapabilities.firefox();
capabilities.setCapability("marionette", true);
WebDriver driver;
try{
driver = new FirefoxDriver(capabilities);
driver.get("https://accounts.google.com/SignUp?");
driver.findElement(By.id("FirstName")).sendKeys("test");
driver.findElement(By.id("LastName")).sendKeys("user");
driver.close();
}
catch(Exception e){
System.out.println(e);
}
}
}
Step-11:
Click on ‘Run’ icon from eclipse to run your first selenium program
Execution:
This program will launch the Firefox browser, open the Gmail sign-up page and enter text
as ‘test’ in First name text field and ‘user’ in Last name text field.
Change Required for Execution on Chrome:
Step-1:
Create one class ‘SecondSeleniumProgram’ in ‘mypackage’
Step-2:
Download ‘chromedriver.exe’ from the following location and copy it your ‘jars’ folder
http://chromedriver.storage.googleapis.com/index.html?path=2.24/
Step-3:
Copy and paste the following code for execution on Chrome browser:
package mypackage;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
public class SecondSeleniumProgram {
public static void main(String args[]) throws InterruptedException{
System.setProperty("webdriver.chrome.driver", "jars/chromedriver.exe");
DesiredCapabilities capabilities=DesiredCapabilities.chrome();
WebDriver driver;
try{
driver = new ChromeDriver(capabilities);
driver.get("https://accounts.google.com/SignUp?");
driver.findElement(By.id("FirstName")).sendKeys("test");
driver.findElement(By.id("LastName")).sendKeys("user");
driver.close();
}
catch(Exception e){
System.out.println(e);
}
}
}
Step-4:
Click on ‘Run’ icon from eclipse to run your first selenium program
Change Required for Execution on Internet Explorer:
Step-1:
Create one class ‘ThirdSeleniumProgram’ in ‘mypackage’
Step-2:
Download ‘IEDriverServer.exe’ from the following location and copy it your ‘jars’ folder
http://www.seleniumhq.org/download/
Step-3:
Copy and paste the following code for execution on IE browser:
package mypackage;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
public class ThirdSeleniumProgram {
public static void main(String args[]) throws InterruptedException{
System.setProperty("webdriver.ie.driver", "jars/IEDriverServer.exe");
DesiredCapabilities capabilities=DesiredCapabilities.internetExplorer();
WebDriver driver;
try{
driver = new InternetExplorerDriver(capabilities);
driver.get("https://accounts.google.com/SignUp?");
driver.findElement(By.id("FirstName")).sendKeys("test");
driver.findElement(By.id("LastName")).sendKeys("user");
driver.close();
}
catch(Exception e){
System.out.println(e);
}
}
}
Step-4:
Check that Protected Mode settings for each zone to be the same value using following
step
Settings Internet Options Security Internet/Local Intranet/Trusted
sites/Restricted sites
Check or Uncheck ‘Enable Protected Mode’ checkbox for all the zones
Step-5:
Set Zoom level to 100%
Step-6:
Click on ‘Run’ icon from eclipse to run your first selenium program
Note: For execution on IE-11 please refer settings mentioned on selenium website
“Logic will get you from A to B. Imagination will take you everywhere” - Albert
Einstein
Chapter-9 | A Closer Look at First Selenium Program
In this session we are going to discuss more about what we have written in our first
Selenium Program using java to understand it in a better.
public class FirstSeleniumProgram {
public static void main(String args[]) throws InterruptedException{
System.setProperty("webdriver.gecko.driver","jars/geckodriver.exe");
DesiredCapabilities capabilities=DesiredCapabilities.firefox();
capabilities.setCapability("marionette", true);
WebDriver driver;
WebElement element;
try{
driver = new FirefoxDriver(capabilities);
driver.get("https://accounts.google.com/SignUp?");
element = driver.findElement(By.id("FirstName"));
element.sendKeys("test");
element = driver.findElement(By.id("LastName"));
element.sendKeys("user");
driver.close();
}
catch(Exception e){
System.out.println(e);
}
}
}
System.setProperty("webdriver.gecko.driver","jars/geckodriver.exe");
We need geckodriver.exe for Firefox, IEDriverServer.exe for Internet Explorer and
chromeDriver.exe for chrome browser. This .exe contains implementation of WebDriver
wire protocol which is used for communication with Selenium Server to interpret and
perform action accordingly.
Every browser has its own rendering engine and mechanism so; we need separate .exe
or implementation for each browser. In above statement we are providing the path of
these exe that will be help Selenium Server/ WebDriver to identify the object on browser
and perform operation as per WebDriver wire protocol.
DesiredCapabilities capabilities=DesiredCapabilities.firefox();
Desired capabilities are used by WebDriver to set/configure the browsers to be used. It
is always define in Key/Value pair (JSON format) e.g. browserName, version, platform
etc.
WebDriver driver;
In the above statement we are creating an object instance of WebDriver which will act as
a handle for the browser.
WebElement element;
In the above statement we are creating an object instance of WebElement which will hold
the value of the web page object like text field, button, text etc.
driver = new FirefoxDriver(capabilities);
In the above statement we are initializing the driver with Firefox driver and given
capabilities (given properties). This will work as a handle to the browser and will be user
further to perform any action/operation on the opened browser.
driver.get("https://accounts.google.com/SignUp?");
In the above statement we are using the function ‘get’ of class driver to open the
application URL.
element = driver.findElement(By.id("FirstName"));
In the above statement we are identifying the element using findElement function
providing the Object properties i.e. id in this case and its value i.e. FirstName. Also
assigning this to an element class element which will be used later to perform action.
element.sendKeys("test");
In the above statement we providing text as “test” in the text field that has been identified
in the above step using the locator (Object Properties and its value i.e. id=FirstName).
driver.close();
In the above statement we are closing the browser handle that has been initiated in the
statement driver = new FirefoxDriver(capabilities);
Note:
element = driver.findElement(By.id("FirstName"));
element.sendKeys("test");
element = driver.findElement(By.id("LastName"));
element.sendKeys("user");
We keep assigning the element with the page objects properties to identify the
element/object uniquely to perform action on it. In the above statements we have first
assigned the element with First Name properties to identify the text field for First name
and then performed enter operation on it. After that we have reassigned the element with
Last Name properties to identify the text field for Last name and then performed enter
operation on it. We will keep doing that for various element on which we will have to
perform any kind of operation/action.
“Live as if you were to die tomorrow. Learn as if you were to live forever”- Mahatma
Gandhi
Chapter-10 | Identifying Objects Uniquely
In Introduction we have discussed that all the functional automation tools are object
based. Every automation tool/api provide some or the other kind of mechanism to identify
the elements/objects on the webpage uniquely. WebDriver also provide many ways to
identify the elements/objects using its properties defined in the html code. These
properties and its value are called as “Locators” in selenium/WebDriver.
Following are the most commonly used locators in WebDriver:
§ ID
§ CSS
§ XPATH
§ Link Text
Note:
WebDriver provided more then dozens of locators to identify the elements/object on any
web page but in real world above three are most commonly used.
How to look for the object properties defined in html code of your browser?
Step-1:
Open https://accounts.google.com/SignUp? in your browser i.e. Firefox/chrome/IE
Step-2:
Right mouse click on the First name text field and click on “Inspect element” option
Step-3
Developer’s tool will be opened at the bottom having html code highlighted for the First
name text field which will look like below screenshot:
Step-4:
Html code highlighted in BLUE color contains the properties defined for the first name
text field. Now we will have to use these properties only to identify the text field for first
name uniquely.
Let’s have a closure look of the locators and how to compose it.
ID:
ID or Identifier is the most reliable locator for any object on a web page. It is always unique
for every element/object but, sometime developers do not provide ID for all the
elements/objects so, we will have to use other locator type. Also, ID is categories into
following 2 categories:
Static ID:
Static ID as shown in the above screenshot does not change with the session. It will
remain same every time you open the page. These are most suitable to be used as it is.
Dynamic ID:
Dynamic ID is created at the runtime and contains some numbers mostly. It always
changes with the session so, whenever you will open the page you will get a different ID
value. These ID are not suitable to be used for locating/identifying the element/objects.
Note:
Always use static ID only for identifying the element/object uniquely. Else, use CSS or
XPATH to for object identification.
CSS:
CSS stands for Cascading Style Sheets and it describes how HTML elements are to be
displayed on screen. To locate/identify the element/object using CSS you will have to use
the object properties to compose the CSS locator.
Following is the simplest way of creating a CSS locator for the First name text field for
which we have the html code in the screenshot:
CSS = TagName/Node[property=’property value’]
Here
§ Tag Name/Node = input
§ Property = id or name
§ Property value = FirstName or FirstName
So CSS locator that can be easily created using the properties of the First Name text
field are:
§ CSS = input [id=’FirstName’]
§ CSS = input [name = ‘FirstName’]
Note:
We will cover more about CSS selector locator in another chapter where we will learn few
advance technique that can be used to create CSS locator
XPATH:
XPATH is a query language that is used to traverse through the DOM (Document Object
Model). In a simple language you can say that XTAPH locator identify element by traverse
through the DOM structure/HTML code. XPATH can be categories into following 2
categories:
Absolute XPATH:
§ Absolute xpath locator start with ‘/’ (Single Slash)
§ It uses Complete path from the Root Element to the desire element
§ Absolute XPATH are generally very long
§ It provides the exact location of the element/object on the html page
§ It is more fragile than relative XPATH as minor change in the DOM structure will
break it
Relative XPATH:
§ Relative XPATH starts with ‘.//’ (dot followed by 2 slashes)
§ Relative XPATH starts from a parent node generally having id defined
§ Relative XPATH are shorter
§ It is less fragile as until the parent node is not changed it works perfectly
§ Relative XPATH is a bit slower than absolute XPATH
§ Relative XPATH is mostly used in Selenium for object identification
Signature of Relative XPATH is:
//TagName/Node[@property=’property value’]
e.g.
//input[@id=’FirstName’] or //input[@name=’FirstName’]
Absolute XPATH for FirstName is:
/html/body/div/div[2]/div/div/div/form/div/fieldset/label/input
Note:
We will cover more about XPATH locator in another chapter where we will learn few
advance techniques that can be used to create XPATH locator
Link Text:
Link Text is mainly used for the links only. It is the easiest way to identify the link by its
link label. In case you are not able to identify any link using Link Text or you have multiple
link with the same label then you can always switch for CSS or XPATH locator.
“If you can't explain it simply, you don't understand it well enough” - Albert
Einstein
Chapter-11 | Advance Technique to Compose CSS and
XPATH locator
In our previous session we have covered the simplest way of composing CSS and XPATH
to identify the element/object on the web page. In this session we are going to learn some
advance technique to compose CSS and XPATH. Also, this session will be more like a
practice session to make sure that we have good enough understanding of CSS and
XPATH to identify the element/object uniquely. Object identification is the building block
for the automation tool.
Selenium IDE a plugin for Firefox browser can be best used for validating that the CSS
Locator or XPATH locator that has been composed for any element/object is identifying
the element/object correctly or not. There are other plugins also available for Firefox,
chrome and IE but, I prefer to use selenium IDE as I have never faced any issue once I
have validated my locator with Selenium IDE.
Validating Locator using Selenium IDE:
Step-1: Open https://addons.mozilla.org/en-US/firefox/addon/selenium-ide/ in Firefox
browser
Step-2: Click on Add to firefox button and Selenium IDE is installed as a firefox plugin
Step-3: Open https://accounts.google.com/SignUp in firefox browser
Step-4: Open selenium IDE Tools Selenium IDE
Step-5: Click in the table area to that will highlight the ‘Command’,
‘Target’ and ‘Value’ field and enable ‘Select’ & ‘Find’button.
Step-6: In ‘Target’ field copy css=input[id='FirstName']
Step-7: Click on find button and you will see a green border appears around the
FirstName text field and it is filled with yellow color for fraction of second. It means that
the CSS locator is able to identify the element/object uniquely.
Next we are going to use other advance technique to compose CSS locator for
identification of few other element/object on this page. We will copy and paste it in
Selenium IDE to validate that the CSS locator created is working perfectly.
CSS
#id: Selects the element with id="FirstName"
• css=#FirstName
element1~element2: Selects every <input> element that are preceded by a <strong>
element
• css=strong ~ input
element+element: Selects all <input> elements that are placed immediately after
<strong> elements
• css=strong + input
[attribute=value]: Selects all elements with name="FirstName"
• css=[name="FirstName"]
element>element: Selects all <p> elements where the parent is a <div> element
• css=label[id="firstname-label"]>input
:nth-of-type(n): Selects every <p> element that is the second <p> element of its parent
• css=fieldset>label:nth-of-type(1)>input
:nth-last-of-type(n): Selects every <p> element that is the second <p> element of its
parent, counting from the last child
• css=fieldset>label:nth-last-of-type(2)>input
:nth-child(n): Selects every <p> element that is the second child of its parent
• css=label[id='firstname-label']>input:nth-child(2)
:only-of-type: Selects every <p> element that is the only <p> element of its parent
• css=label>input:only-of-type
XPATH:
Unique ID: Selects the element with unique ID FirstName
• xpath=//input[@id='FirstName']
child::input: Selects the first input child of the element with unique ID firstname-label
• xpath=//label[@id='firstname-label']/child::input[1]
descendant:: input: Selects the input element descendants of the context node
• xpath=//label[@id='firstname-label']/descendant::input
ancestor-or-self::input: Selects the input ancestors of the context node and, if the
context node is a input element, the context node as well
• xpath=//*[@id='FirstName']/ ancestor-or-self::input
ancestor::label: Selects all label ancestors of the context node
• xpath=//input[@id='FirstName']/ancestor::label
descendant-or-self::input: Selects the input element descendants of the context node
and, if the context node is a para element, the context node as well
• xpath=//*[@id='firstname-label']/descendant-or-self::input
self::input: Selects the context node if it is a input element, and otherwise selects
nothing
• xpath=//input[@id='FirstName']/self::input
descendant::input: Selects the input element descendants of the chapter element
children of the context node
• xpath=//fieldset/child::label/descendant::input
child::*/child::input: Selects all input grandchildren of the context node
• xpath=//fieldset/child::*/child::input
child::input[last()]: Selects the last input child of the context node
• xpath=//label[@id='firstname-label']/child::input[last()]
following-sibling::label[1]: Selects the next input sibling of the context node
• xpath=//label[@id='firstname-label']/following-sibling::label[1]/input
preceding-sibling::label[1]/: Selects the previous input sibling of the context node
• xpath=//label[@id='lastname-label']/preceding-sibling::label[1]/input
“A wise man can learn more from a foolish question than a fool can learn from a
wise answer” - Bruce Lee

More Related Content

What's hot

Realtime selenium interview questions
Realtime selenium interview questionsRealtime selenium interview questions
Realtime selenium interview questions
Kuldeep Pawar
 
Lulu.com.java.j2 ee.job.interview.companion.2nd.edition.apr.2007
Lulu.com.java.j2 ee.job.interview.companion.2nd.edition.apr.2007Lulu.com.java.j2 ee.job.interview.companion.2nd.edition.apr.2007
Lulu.com.java.j2 ee.job.interview.companion.2nd.edition.apr.2007
Arun Kumar
 
香港六合彩
香港六合彩香港六合彩
香港六合彩
baoyin
 
Workshop Android for Java Developers
Workshop Android for Java DevelopersWorkshop Android for Java Developers
Workshop Android for Java Developers
mhant
 
Packages and inbuilt classes of java
Packages and inbuilt classes of javaPackages and inbuilt classes of java
Packages and inbuilt classes of java
kamal kotecha
 
Class 1
Class 1Class 1
Class 1
Dario Pilozo
 
Java notes
Java notesJava notes
Java Lab
Java LabJava Lab
Java Lab
Leo Nguyen
 
The Seven Pillars Of Asp.Net
The Seven Pillars Of Asp.NetThe Seven Pillars Of Asp.Net
The Seven Pillars Of Asp.Net
Anand Kumar Rajana
 
Java scjp-part1
Java scjp-part1Java scjp-part1
Java scjp-part1
Raghavendra V Gayakwad
 
DevLabs Alliance Top 50 Selenium Interview Questions for SDET
DevLabs Alliance Top 50 Selenium Interview Questions for SDETDevLabs Alliance Top 50 Selenium Interview Questions for SDET
DevLabs Alliance Top 50 Selenium Interview Questions for SDET
DevLabs Alliance
 
Java for android developers
Java for android developersJava for android developers
Java for android developers
Aly Abdelkareem
 
Top 20 basic java interview questions for SDET
Top 20 basic java interview questions for SDETTop 20 basic java interview questions for SDET
Top 20 basic java interview questions for SDET
DevLabs Alliance
 
Event handling
Event handlingEvent handling
Event handling
Ravi_Kant_Sahu
 
Top 20 software testing interview questions for sdet
Top 20 software testing interview questions for sdetTop 20 software testing interview questions for sdet
Top 20 software testing interview questions for sdet
DevLabs Alliance
 
Core Java Tutorial
Core Java TutorialCore Java Tutorial
Core Java Tutorial
Java2Blog
 
Introduction to java
Introduction to javaIntroduction to java
Introduction to java
Sujit Majety
 
Living With Legacy Code
Living With Legacy CodeLiving With Legacy Code
Living With Legacy Code
Rowan Merewood
 
Selenium interview questions and answers
Selenium interview questions and answersSelenium interview questions and answers
Selenium interview questions and answers
kavinilavuG
 
java applets
java appletsjava applets
java applets
Waheed Warraich
 

What's hot (20)

Realtime selenium interview questions
Realtime selenium interview questionsRealtime selenium interview questions
Realtime selenium interview questions
 
Lulu.com.java.j2 ee.job.interview.companion.2nd.edition.apr.2007
Lulu.com.java.j2 ee.job.interview.companion.2nd.edition.apr.2007Lulu.com.java.j2 ee.job.interview.companion.2nd.edition.apr.2007
Lulu.com.java.j2 ee.job.interview.companion.2nd.edition.apr.2007
 
香港六合彩
香港六合彩香港六合彩
香港六合彩
 
Workshop Android for Java Developers
Workshop Android for Java DevelopersWorkshop Android for Java Developers
Workshop Android for Java Developers
 
Packages and inbuilt classes of java
Packages and inbuilt classes of javaPackages and inbuilt classes of java
Packages and inbuilt classes of java
 
Class 1
Class 1Class 1
Class 1
 
Java notes
Java notesJava notes
Java notes
 
Java Lab
Java LabJava Lab
Java Lab
 
The Seven Pillars Of Asp.Net
The Seven Pillars Of Asp.NetThe Seven Pillars Of Asp.Net
The Seven Pillars Of Asp.Net
 
Java scjp-part1
Java scjp-part1Java scjp-part1
Java scjp-part1
 
DevLabs Alliance Top 50 Selenium Interview Questions for SDET
DevLabs Alliance Top 50 Selenium Interview Questions for SDETDevLabs Alliance Top 50 Selenium Interview Questions for SDET
DevLabs Alliance Top 50 Selenium Interview Questions for SDET
 
Java for android developers
Java for android developersJava for android developers
Java for android developers
 
Top 20 basic java interview questions for SDET
Top 20 basic java interview questions for SDETTop 20 basic java interview questions for SDET
Top 20 basic java interview questions for SDET
 
Event handling
Event handlingEvent handling
Event handling
 
Top 20 software testing interview questions for sdet
Top 20 software testing interview questions for sdetTop 20 software testing interview questions for sdet
Top 20 software testing interview questions for sdet
 
Core Java Tutorial
Core Java TutorialCore Java Tutorial
Core Java Tutorial
 
Introduction to java
Introduction to javaIntroduction to java
Introduction to java
 
Living With Legacy Code
Living With Legacy CodeLiving With Legacy Code
Living With Legacy Code
 
Selenium interview questions and answers
Selenium interview questions and answersSelenium interview questions and answers
Selenium interview questions and answers
 
java applets
java appletsjava applets
java applets
 

Similar to Selenium web driver | java

Java Basics for selenium
Java Basics for seleniumJava Basics for selenium
Java Basics for selenium
apoorvams
 
JAVA INTRODUCTION
JAVA INTRODUCTIONJAVA INTRODUCTION
JAVA INTRODUCTION
Prof Ansari
 
JAVA INTRODUCTION
JAVA INTRODUCTIONJAVA INTRODUCTION
JAVA INTRODUCTION
Prof Ansari
 
Java For Automation
Java   For AutomationJava   For Automation
Java For Automation
Abhijeet Dubey
 
OBJECT ORIENTED PROGRAMMING LANGUAGE - SHORT NOTES
OBJECT ORIENTED PROGRAMMING LANGUAGE - SHORT NOTESOBJECT ORIENTED PROGRAMMING LANGUAGE - SHORT NOTES
OBJECT ORIENTED PROGRAMMING LANGUAGE - SHORT NOTES
suthi
 
Proyect of english
Proyect of englishProyect of english
Proyect of english
Carlos Alcivar
 
Introduction
IntroductionIntroduction
Introduction
richsoden
 
SMI - Introduction to Java
SMI - Introduction to JavaSMI - Introduction to Java
SMI - Introduction to Java
SMIJava
 
Java lab1 manual
Java lab1 manualJava lab1 manual
Java lab1 manual
nahalomar
 
Javascript
JavascriptJavascript
Javascript
Sheldon Abraham
 
Understanding Framework Architecture using Eclipse
Understanding Framework Architecture using EclipseUnderstanding Framework Architecture using Eclipse
Understanding Framework Architecture using Eclipse
anshunjain
 
Intro to programing with java-lecture 1
Intro to programing with java-lecture 1Intro to programing with java-lecture 1
Intro to programing with java-lecture 1
Mohamed Essam
 
MC0078 SMU 2013 Fall session
MC0078 SMU 2013 Fall sessionMC0078 SMU 2013 Fall session
MC0078 SMU 2013 Fall session
Narinder Kumar
 
Why test with flex unit
Why test with flex unitWhy test with flex unit
Why test with flex unit
michael.labriola
 
Intro Java Rev010
Intro Java Rev010Intro Java Rev010
Intro Java Rev010
Rich Helton
 
Java 3 rd sem. 2012 aug.ASSIGNMENT
Java 3 rd sem. 2012 aug.ASSIGNMENTJava 3 rd sem. 2012 aug.ASSIGNMENT
Java 3 rd sem. 2012 aug.ASSIGNMENT
mayank's it solution pvt.ltd
 
java traning report_Summer.docx
java traning report_Summer.docxjava traning report_Summer.docx
java traning report_Summer.docx
GauravSharma164138
 
Unit 1 of java part 2 basic introduction
Unit 1 of java part 2 basic introduction Unit 1 of java part 2 basic introduction
Unit 1 of java part 2 basic introduction
AKR Education
 
Compiling and understanding first program in java
Compiling and understanding first program in javaCompiling and understanding first program in java
Compiling and understanding first program in java
Jamsher bhanbhro
 
Presentation5
Presentation5Presentation5
Presentation5
Natasha Bains
 

Similar to Selenium web driver | java (20)

Java Basics for selenium
Java Basics for seleniumJava Basics for selenium
Java Basics for selenium
 
JAVA INTRODUCTION
JAVA INTRODUCTIONJAVA INTRODUCTION
JAVA INTRODUCTION
 
JAVA INTRODUCTION
JAVA INTRODUCTIONJAVA INTRODUCTION
JAVA INTRODUCTION
 
Java For Automation
Java   For AutomationJava   For Automation
Java For Automation
 
OBJECT ORIENTED PROGRAMMING LANGUAGE - SHORT NOTES
OBJECT ORIENTED PROGRAMMING LANGUAGE - SHORT NOTESOBJECT ORIENTED PROGRAMMING LANGUAGE - SHORT NOTES
OBJECT ORIENTED PROGRAMMING LANGUAGE - SHORT NOTES
 
Proyect of english
Proyect of englishProyect of english
Proyect of english
 
Introduction
IntroductionIntroduction
Introduction
 
SMI - Introduction to Java
SMI - Introduction to JavaSMI - Introduction to Java
SMI - Introduction to Java
 
Java lab1 manual
Java lab1 manualJava lab1 manual
Java lab1 manual
 
Javascript
JavascriptJavascript
Javascript
 
Understanding Framework Architecture using Eclipse
Understanding Framework Architecture using EclipseUnderstanding Framework Architecture using Eclipse
Understanding Framework Architecture using Eclipse
 
Intro to programing with java-lecture 1
Intro to programing with java-lecture 1Intro to programing with java-lecture 1
Intro to programing with java-lecture 1
 
MC0078 SMU 2013 Fall session
MC0078 SMU 2013 Fall sessionMC0078 SMU 2013 Fall session
MC0078 SMU 2013 Fall session
 
Why test with flex unit
Why test with flex unitWhy test with flex unit
Why test with flex unit
 
Intro Java Rev010
Intro Java Rev010Intro Java Rev010
Intro Java Rev010
 
Java 3 rd sem. 2012 aug.ASSIGNMENT
Java 3 rd sem. 2012 aug.ASSIGNMENTJava 3 rd sem. 2012 aug.ASSIGNMENT
Java 3 rd sem. 2012 aug.ASSIGNMENT
 
java traning report_Summer.docx
java traning report_Summer.docxjava traning report_Summer.docx
java traning report_Summer.docx
 
Unit 1 of java part 2 basic introduction
Unit 1 of java part 2 basic introduction Unit 1 of java part 2 basic introduction
Unit 1 of java part 2 basic introduction
 
Compiling and understanding first program in java
Compiling and understanding first program in javaCompiling and understanding first program in java
Compiling and understanding first program in java
 
Presentation5
Presentation5Presentation5
Presentation5
 

Recently uploaded

Fueling AI with Great Data with Airbyte Webinar
Fueling AI with Great Data with Airbyte WebinarFueling AI with Great Data with Airbyte Webinar
Fueling AI with Great Data with Airbyte Webinar
Zilliz
 
Serial Arm Control in Real Time Presentation
Serial Arm Control in Real Time PresentationSerial Arm Control in Real Time Presentation
Serial Arm Control in Real Time Presentation
tolgahangng
 
AWS Cloud Cost Optimization Presentation.pptx
AWS Cloud Cost Optimization Presentation.pptxAWS Cloud Cost Optimization Presentation.pptx
AWS Cloud Cost Optimization Presentation.pptx
HarisZaheer8
 
Azure API Management to expose backend services securely
Azure API Management to expose backend services securelyAzure API Management to expose backend services securely
Azure API Management to expose backend services securely
Dinusha Kumarasiri
 
Public CyberSecurity Awareness Presentation 2024.pptx
Public CyberSecurity Awareness Presentation 2024.pptxPublic CyberSecurity Awareness Presentation 2024.pptx
Public CyberSecurity Awareness Presentation 2024.pptx
marufrahmanstratejm
 
Dandelion Hashtable: beyond billion requests per second on a commodity server
Dandelion Hashtable: beyond billion requests per second on a commodity serverDandelion Hashtable: beyond billion requests per second on a commodity server
Dandelion Hashtable: beyond billion requests per second on a commodity server
Antonios Katsarakis
 
Presentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of GermanyPresentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of Germany
innovationoecd
 
Digital Marketing Trends in 2024 | Guide for Staying Ahead
Digital Marketing Trends in 2024 | Guide for Staying AheadDigital Marketing Trends in 2024 | Guide for Staying Ahead
Digital Marketing Trends in 2024 | Guide for Staying Ahead
Wask
 
Skybuffer AI: Advanced Conversational and Generative AI Solution on SAP Busin...
Skybuffer AI: Advanced Conversational and Generative AI Solution on SAP Busin...Skybuffer AI: Advanced Conversational and Generative AI Solution on SAP Busin...
Skybuffer AI: Advanced Conversational and Generative AI Solution on SAP Busin...
Tatiana Kojar
 
GNSS spoofing via SDR (Criptored Talks 2024)
GNSS spoofing via SDR (Criptored Talks 2024)GNSS spoofing via SDR (Criptored Talks 2024)
GNSS spoofing via SDR (Criptored Talks 2024)
Javier Junquera
 
“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...
“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...
“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...
Edge AI and Vision Alliance
 
Skybuffer SAM4U tool for SAP license adoption
Skybuffer SAM4U tool for SAP license adoptionSkybuffer SAM4U tool for SAP license adoption
Skybuffer SAM4U tool for SAP license adoption
Tatiana Kojar
 
Best 20 SEO Techniques To Improve Website Visibility In SERP
Best 20 SEO Techniques To Improve Website Visibility In SERPBest 20 SEO Techniques To Improve Website Visibility In SERP
Best 20 SEO Techniques To Improve Website Visibility In SERP
Pixlogix Infotech
 
Energy Efficient Video Encoding for Cloud and Edge Computing Instances
Energy Efficient Video Encoding for Cloud and Edge Computing InstancesEnergy Efficient Video Encoding for Cloud and Edge Computing Instances
Energy Efficient Video Encoding for Cloud and Edge Computing Instances
Alpen-Adria-Universität
 
Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...
Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...
Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...
saastr
 
HCL Notes and Domino License Cost Reduction in the World of DLAU
HCL Notes and Domino License Cost Reduction in the World of DLAUHCL Notes and Domino License Cost Reduction in the World of DLAU
HCL Notes and Domino License Cost Reduction in the World of DLAU
panagenda
 
Generating privacy-protected synthetic data using Secludy and Milvus
Generating privacy-protected synthetic data using Secludy and MilvusGenerating privacy-protected synthetic data using Secludy and Milvus
Generating privacy-protected synthetic data using Secludy and Milvus
Zilliz
 
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAUHCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
panagenda
 
GraphRAG for Life Science to increase LLM accuracy
GraphRAG for Life Science to increase LLM accuracyGraphRAG for Life Science to increase LLM accuracy
GraphRAG for Life Science to increase LLM accuracy
Tomaz Bratanic
 
A Comprehensive Guide to DeFi Development Services in 2024
A Comprehensive Guide to DeFi Development Services in 2024A Comprehensive Guide to DeFi Development Services in 2024
A Comprehensive Guide to DeFi Development Services in 2024
Intelisync
 

Recently uploaded (20)

Fueling AI with Great Data with Airbyte Webinar
Fueling AI with Great Data with Airbyte WebinarFueling AI with Great Data with Airbyte Webinar
Fueling AI with Great Data with Airbyte Webinar
 
Serial Arm Control in Real Time Presentation
Serial Arm Control in Real Time PresentationSerial Arm Control in Real Time Presentation
Serial Arm Control in Real Time Presentation
 
AWS Cloud Cost Optimization Presentation.pptx
AWS Cloud Cost Optimization Presentation.pptxAWS Cloud Cost Optimization Presentation.pptx
AWS Cloud Cost Optimization Presentation.pptx
 
Azure API Management to expose backend services securely
Azure API Management to expose backend services securelyAzure API Management to expose backend services securely
Azure API Management to expose backend services securely
 
Public CyberSecurity Awareness Presentation 2024.pptx
Public CyberSecurity Awareness Presentation 2024.pptxPublic CyberSecurity Awareness Presentation 2024.pptx
Public CyberSecurity Awareness Presentation 2024.pptx
 
Dandelion Hashtable: beyond billion requests per second on a commodity server
Dandelion Hashtable: beyond billion requests per second on a commodity serverDandelion Hashtable: beyond billion requests per second on a commodity server
Dandelion Hashtable: beyond billion requests per second on a commodity server
 
Presentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of GermanyPresentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of Germany
 
Digital Marketing Trends in 2024 | Guide for Staying Ahead
Digital Marketing Trends in 2024 | Guide for Staying AheadDigital Marketing Trends in 2024 | Guide for Staying Ahead
Digital Marketing Trends in 2024 | Guide for Staying Ahead
 
Skybuffer AI: Advanced Conversational and Generative AI Solution on SAP Busin...
Skybuffer AI: Advanced Conversational and Generative AI Solution on SAP Busin...Skybuffer AI: Advanced Conversational and Generative AI Solution on SAP Busin...
Skybuffer AI: Advanced Conversational and Generative AI Solution on SAP Busin...
 
GNSS spoofing via SDR (Criptored Talks 2024)
GNSS spoofing via SDR (Criptored Talks 2024)GNSS spoofing via SDR (Criptored Talks 2024)
GNSS spoofing via SDR (Criptored Talks 2024)
 
“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...
“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...
“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...
 
Skybuffer SAM4U tool for SAP license adoption
Skybuffer SAM4U tool for SAP license adoptionSkybuffer SAM4U tool for SAP license adoption
Skybuffer SAM4U tool for SAP license adoption
 
Best 20 SEO Techniques To Improve Website Visibility In SERP
Best 20 SEO Techniques To Improve Website Visibility In SERPBest 20 SEO Techniques To Improve Website Visibility In SERP
Best 20 SEO Techniques To Improve Website Visibility In SERP
 
Energy Efficient Video Encoding for Cloud and Edge Computing Instances
Energy Efficient Video Encoding for Cloud and Edge Computing InstancesEnergy Efficient Video Encoding for Cloud and Edge Computing Instances
Energy Efficient Video Encoding for Cloud and Edge Computing Instances
 
Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...
Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...
Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...
 
HCL Notes and Domino License Cost Reduction in the World of DLAU
HCL Notes and Domino License Cost Reduction in the World of DLAUHCL Notes and Domino License Cost Reduction in the World of DLAU
HCL Notes and Domino License Cost Reduction in the World of DLAU
 
Generating privacy-protected synthetic data using Secludy and Milvus
Generating privacy-protected synthetic data using Secludy and MilvusGenerating privacy-protected synthetic data using Secludy and Milvus
Generating privacy-protected synthetic data using Secludy and Milvus
 
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAUHCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
 
GraphRAG for Life Science to increase LLM accuracy
GraphRAG for Life Science to increase LLM accuracyGraphRAG for Life Science to increase LLM accuracy
GraphRAG for Life Science to increase LLM accuracy
 
A Comprehensive Guide to DeFi Development Services in 2024
A Comprehensive Guide to DeFi Development Services in 2024A Comprehensive Guide to DeFi Development Services in 2024
A Comprehensive Guide to DeFi Development Services in 2024
 

Selenium web driver | java

  • 1. About Author: Rajesh Kumar Bachelor of Technology graduate in Computer Science from Uttar Pradesh Technology University in 2004. He has started his career as an automation engineer in 2004 and has 14+ years of experience in automation domain. He has worked with top notch organization in e-Commerce, e-Learning, Travel and Banking Domain. Currently he is working as an automation architect with a multinational company. He is very passionate about exploring different automation tools for functional and non- functional automation. He is a subject matter expert for functional automation tools i.e. Win Runner, QTP (Quick Test Professional), RFT (Rational Functional Tester), Silk Test, Selenium, Test Complete, Appium and SeeTest. He has extensive experience in automation team building, Automation tools training, automation framework development and automation project supports as SME.
  • 2. Table of Contents Chapter-1| ‘Hello World’ Program.............................................................................................. 3 Chapter-2 | Java Basic Concept- Part-1....................................................................................... 5 Chapter-3 | Java Basic Concept- Part-2....................................................................................... 8 Chapter-4 | A Closer Look at the "Hello World!" ...................................................................... 12 Chapter-5 | A Closer Look at Function...................................................................................... 14 Chapter-6 | Control Flow Statements....................................................................................... 17 Chapter-7 | File Input Output Operations................................................................................. 20 Chapter-8 | First Selenium Program ......................................................................................... 23 Chapter-9 | A Closer Look at First Selenium Program............................................................... 27 Chapter-10 | Identifying Objects Uniquely ............................................................................... 29 Chapter-11 | Advance Technique to Compose CSS and XPATH locator..................................... 32
  • 3. Chapter-1| ‘Hello World’ Program Step-1 | Choosing Automation Tool and Language The first step to start learning automation is to finalize on the tool/API and the language. This is the most problematic step to decide on the tool and the language. Your search for the latest market trend, consult your friends from the automation background and even your senior. Everyone will have a different opinion. Even my opinion changes with time and with the person I am talking to so, the best way are to go with the Public Poll. Choose the tool and language with the highest community support and is open source. Nowadays Selenium with Java is the best suite for you to learn automation. I know JavaScript is gaining more popularity. Also, Mobile automation is gaining more popularity then desktop automation as mobile users and mobile apps are increasing exponentially. But, just don't forget we are talking about the first step. Step-2 | Installing Eclipse and Java This is the most difficult step for the person who wants to start with automation. Even I have given up for many tools before I have started. Installation and configuration are the most tricky and irritating job. The reason is we do not know which version is required what all software's are required. What setting need to be done blah blah…. To make it easy for you guys/gals, we will take step by step. 1. Check if java is installed on your machine if not install it using following steps 2. Use java –version command on command prompt to check java version on your machine. In case it is not installed on your machine you will get error message. In case you have a java version which is older than 1.6 then upgrade it 3. Download latest version of Java SE Development Kit from following location: http://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads- 2133151.html 4. Install latest version of Java (64 bit or 32 bit) corresponding to your machine operating system 5. Download Eclipse (64 bit or 32 bit) corresponding to your machine operating system: https://eclipse.org/downloads/ 6. Create a new folder “AutomationWorkspace” in your D drive or any other drive of your machine 7. Unzip eclipse folder and navigate to the folder where you will see eclipse.exe 8. Double click on eclipse.exe to open Eclipse and provide the path of the “AutomationWorkspace” when pop-up appears for ‘select a workspace’ and click on ‘OK’ button. 9. Click on File -- New – Others 10.Select ‘Java Project’ from the ‘Select a wizard’ model window and click on ‘Next’ button 11.Enter Project name as ‘HelloWorld’ in ‘Create a Java Project’ model window and click on ‘Finish’ 12.Click on + (expansion sign) in ‘Package Explorer’ pane to expend the project folder
  • 4. 13.Add a package to your project folder using following steps: ü Mouse Right click on ‘src’ folder ü Select New -- Package ü Enter Package Name as ‘mypackage’ 14.Add a class to your package created in above step using following steps: ü Mouse Right click on ‘mypackage’folder ü Select New -- Class ü Enter Class Name as ‘MyClass’ 15.Write your first Hello World Program package mypackage; public class MyClass { public static void main (String args[]){ System.out.println("Hello World !!"); } } 16.Click on Run button and Enjoy Challenges You Might Face: 1. You might face some issue when you are installing Java for the first time on your machine 2. Java Home need to be set in Environment variable (you will get many article and videos) 3. Java version should be compatible with your Eclipse version that you have downloaded else eclipse will throw error while launching. You can check it online which version of eclipse is compatible with which java version. Note: You can always post your question in case facing any issue. I will be happy to help you all, but don’t give up. “The more you know, the more you know you don't know.” - Aristotle
  • 5. Chapter-2 | Java Basic Concept- Part-1 Bad habits die hard; it’s very true as we all have the tendency to achieve most with least effort. So, I will try to cover least required to come to a platform from where you can start working on automation. But, before we start working on automation we should at least learn few concepts which will help you in understanding what you are doing. Variables: 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. Data Type: There are two data types available in Java: Primitive Data Types: There are eight primitive data types supported by Java. Primitive data types are predefined by the language and named by a keyword: § byte e.g. byte a = 100 § short e.g. short s = 10000 § int e.g. int a = 100000 § float e.g. float f1 = 234.5 § double e.g. double d1 = 123.44 § boolean e.g. boolean one = true § char e.g. char letterA ='A' Reference/Object Data Types: Reference variables are created using defined constructors of the classes. They are used to access objects. Arithmetic Operators: + Additive operator (also used for String concatenation) - Subtraction operator * Multiplication operator / Division operator % Remainder operator Equality and Relational Operators: == Equal to != Not equal to > Greater than >= Greater than or equal to < Less than <= Less than or equal to
  • 6. Conditional Operators: && Conditional-AND || Conditional-OR Make your hands dirty by practicing above concepts through code: Sample 1: Create another class ‘Test1’ in you ‘mypackage’ as done in previous session. Copy and paste below code and run to see the output package mypackage; public class Test1 { public static void main (String args[]){ int a; int b; int c; a = 5.45; b=10.55; c = a + b; System.out.println("Sum of a and b is :: " + c); } } Sample 2: Create another class ‘Test2’ in you ‘mypackage’ as done in previous session. Copy and paste below code and run to see the output package mypackage; public class Test2 { public static void main (String args[]){ int a; int b; int c; a = 5; b=10; c = a + b; System.out.println("Sum of a and b is :: " + c); } } Sample 3: Create another class ‘Test3’ in you ‘mypackage’ as done in previous session. Copy and paste below code and run to see the output package mypackage;
  • 7. public class Test3 { public static void main (String args[]){ int a; int b; int c; a = Testing; b= qauser; c = a + b; System.out.println("Sum of a and b is :: " + c); } } "We learn from failure, not from success" - Bram Stoker
  • 8. Chapter-3 | Java Basic Concept- Part-2 Strings, which are widely used in Java programming, are a sequence of characters. In the Java programming language, strings are objects. The Java platform provides the String class to create and manipulate strings. String Length: Using this method, you can find number of characters contained in the string object package mypackage; public class StringLength { public static void main(String args[]) { String TestString = "I am learning Selenium with Java"; int len = TestString.length(); System.out.println("String Length is : " + len); } } Concatenating Strings: This returns a new string that is string1 with string2 added to it at the end. package mypackage; public class StringConcat { public static void main(String args[]) { String String1 = "Selenium with "; String String2 = "Java"; String String3 = String1 + String2; System.out.println("Final string after concatination method-1 is :: " + String3); // Another way of doing what we have done above String String4 = String1.concat(String2); System.out.println("Final string after concatination method-2 is :: " + String4); } } IndexOf: Returns the index within this string of the first occurrence of the specified substring. package mypackage; public class StringIndex {
  • 9. public static void main(String args[]) { String TestString = " Learning Selenium from Selenium Community"; int Index = TestString.indexOf("Selenium"); System.out.println("Index of Selenium in above string : " + Index); } } LastIndexOf: Returns the index within this string of the last occurrence of the specified substring. package mypackage; public class StringLastIndex { public static void main(String args[]) { String TestString = "Learning Selenium from Selenium Community"; int FirstIndex = TestString.indexOf("Selenium"); System.out.println("First Index of Selenium in above string : " + FirstIndex); int LastIndex = TestString.lastIndexOf("Selenium"); System.out.println("Last Index of Selenium in above string : " + LastIndex); } } Split: Splits this string around matches of the given regular expression. package mypackage; public class StringSpliting { public static void main(String args[]) { String TestString = "Your Booking Reference Number is 234567891"; String[] StringParts = TestString.split(" "); System.out.println("Reference Number in above string : " + StringParts[5]); } } SubString: Returns a string that is a substring of this string. The substring begins with the character at the specified index and extends to the end of this string. package mypackage;
  • 10. public class SubString { public static void main(String args[]) { String TestString = "Your Booking Reference Number is 234567891"; int FirstIndex = TestString.indexOf("is"); String StringParts = TestString.substring(FirstIndex + 3); System.out.println("Sub string i.e. Reference Number in above string : " + StringParts); } } Replace: Replaces each substring of this string that matches the literal target sequence with the specified literal replacement sequence. package mypackage; public class StringReplace { public static void main(String args[]) { String TestString = "Your Booking Reference Number is 234567891"; String ReplacedString = TestString.replace("Your", "Customer"); System.out.println("Initial String:: " + TestString); System.out.println("Replaced String:: " + ReplacedString); } } Lower/UpperCase: Converts all of the characters in this String to Lower / Upper case package mypackage; public class StringUpperLowerCase { public static void main(String args[]) { String TestString = "Your Booking Reference Number is 234567891"; String StringLowerCase = TestString.toLowerCase(); System.out.println("Lower Case String:: " + StringLowerCase); String StringUpperCase = TestString.toUpperCase(); System.out.println("Upper Case String:: " + StringUpperCase); } } Compare: Compare two string either considering case sensitivity or ignoring case sensitivity.
  • 11. package mypackage; public class StringComparision { public static void main(String args[]) { String ExpectedString = "Your Booking Reference Number is 234567891"; String ActualString = "Your booking reference number is 234567891"; System.out.println("Result considering case senstivity:: " + ActualString.equals(ExpectedString)); System.out.println("Result ignoring case senstivity:: " + ActualString.equalsIgnoreCase(ExpectedString)); } } Trim: Returns a string whose value is this string, with any leading and trailing whitespace removed. package mypackage; public class StringTrim { public static void main(String args[]) { String TestString = " Your Booking Reference Number is 234567891 "; String TrimmedString = TestString.trim(); System.out.println("Actual String:: " + TestString); System.out.println("String after trim:: " + TrimmedString); } } “Tell me and I forget, teach me and I may remember, involve me and I learn” - Benjamin Franklin
  • 12. Chapter-4 | A Closer Look at the "Hello World!" In our first session we have created a program for “Hello World”. After that we have learned few more programs related to integer and string. Now, let’s have a close look of the very first program that has been created to test the Java, Eclipse set-up and configuration. package mypackage; public class MyClass { public static void main (String args[]){ System.out.println("Hello World !!"); } } When you will have a closure look of the above program. You will find following: § Package § Class § Main Method § Source Code Package: Our program is starting with a package statement [package mypackage;]. Package can be defined as a grouping of related types (classes, interfaces, enumerations and annotations) providing access protection and name space management. When you create a Class file system automatically create a default package. But it is always suggested not to use the default package and create a package of your own. Class: Every package has Class in it e.g. [public class MyClass]. Every class has a class body (the area between the braces) contains all the code that provides for the life cycle of the objects created from the class. Class can be defined as a template/blue print that describes the behaviors/states that object of its type support. In general, class declarations can include these components, in order: 1. Modifiers such as public, private, and a number of others that you will encounter later. 2. The class name, with the initial letter capitalized by convention. 3. The class body, surrounded by braces, {}. Main Method: In the Java programming language, every application must contain a main method whose signature is:
  • 13. public static void main(String[] args) § The main method accepts a single argument: an array of elements of type String i.e. String[] args § This array is the mechanism through which the runtime system passes information to your application Source Code: System.out.println("Hello World !!"); Let's look at the components of this line: § System tells the system to do something. § out tells the system that we are going to do some output stuff. § println stands for "print line," so we are telling the system to print a line in the output. § The parentheses around ("Hello World.") means that the method System.out.println() takes in a parameter, which, in this case, is the String "Hello World." Note that there are some rules in Java that we have to adhere to: § You must always add a semicolon at the end of every line. § Java is case sensitive, so you must write method names, variable names, and class names in the correct case or you will get an error. § Blocks of code specific to a certain method or loop are encased between curly brackets. Access Level Modifier: Access level modifiers determine whether other classes can use a particular field or invoke a particular method. There are two levels of access control: At the top level—public, or package-private (no explicit modifier). At the member level—public, private, protected, or package-private (no explicit modifier). A class may be declared with the modifier public, in which case that class is visible to all classes everywhere. Also, class always has access to its own members. “Teaching is only demonstrating that it is possible. Learning is making it possible for yourself” - Paulo Coelho
  • 14. Chapter-5 | A Closer Look at Function In Java, all function definitions must be inside classes. We also call functions methods. Let's look at an example method: package mypackage; public class Functions { public static void FunctionWithoutParam(){ String String1 = "How to Learn Selenium?"; System.out.println("Ques: ".concat(String1)); } public static void FunctionWithParam(String sQuestion){ System.out.println("Ques: ".concat(sQuestion)); } public static void main (String args[]){ FunctionWithoutParam(); FunctionWithParam("How to Learn Java?"); } } • Static means this method belongs to the class Functions and not to a specific instance of Functions • void means this method doesn't return a value. Methods can return a single value in Java and it has to be defined in the method declaration. However, you can use return by itself to exit the method. • First method doesn't get any arguments, but of course Java methods can get arguments as we'll which is shown in second method. • Non static methods in Java are used more than static methods. Those methods can only be run on objects and not on the whole class. Calling one function in another function within same class: package mypackage; public class FunctionCalling { public static void CalledFunctionWithoutParam(){ System.out.println("Calledfunction will be called by calling function"); }
  • 15. public static void CalledFunctionWithParam(String sArgument){ System.out.println(sArgument); } public static void CallingFunction(){ CalledFunctionWithoutParam(); CalledFunctionWithParam("Argument to be passed in the called function"); } public static void main (String args[]){ CallingFunction(); } } Let’s have a close look of the above example. In above example we have a class FunctionCalling which contains 3 simple methods/function and 1 main method/function. Since java program should have at least 1 main method which is the execution point. Wehave 2 methods/functioni.e. CalledFunctionWithoutParam and CalledFunctionWi thParam. First one will not accept any argument while second function will accept an argument. Both these functions/method are called function which mean they will be called by the 3 function i.e. CallingFunction. Calling one function in another function within another class: We are going to create 2 classes CalledClass: This class will have 2 functions/methods i.e. CalledFunctionWithoutParam & CalledFunctionWithParam package mypackage; public class CalledClass { public void CalledFunctionWithoutParam(){ System.out.println("Function from another class to be called"); } public void CalledFunctionWithParam(String sArgument){ System.out.println(sArgument); } }
  • 16. CallingClass: This class will have a calling function/method i.e. CallingFunction and Main method. package mypackage; public class CallingClass { static CalledClass CalledFunctionClass = new CalledClass(); public static void CallingFunction(){ CalledFunctionClass.CalledFunctionWithoutParam(); CalledFunctionClass.CalledFunctionWithParam("Argument to be passed in the called function form another class"); } public static void main (String args[]){ CallingFunction(); } } Observation: • We cannot call the function just by providing the name of the calling function in called function as we were doing while calling a function within same class • When you are calling a function from another class then you will have to create an instance of the class from where you are calling the function. • This is done using the statement static CalledClass CalledFunctionClass = new CalledClass(); • Now using the object instance i.e. CalledFunctionClass we can call the function with that class i.e. CalledFunctionClass.CalledFunctionWithoutParam(); CalledFunctionClass.Cal ledFunctionWithParam("Argument to be passed in the called function form another class"); • CallingFunction method is a static method so when we are creating an instance of called class, we are declaring it asstatic else you won’t be able to call as calling method is a static method. “The beautiful thing about learning is nobody can take it away from you” - B.B. King
  • 17. Chapter-6 | Control Flow Statements The if-then Statement: The if-then statement is the most basic of all the control flow statements. It tells your program to execute a certain section of code only if a particular test evaluates to true e.g. package mypackage; public class IfThenStatement { public static void main(String args[]){ String AutomationTool = "QTP"; if (AutomationTool.equalsIgnoreCase("QTP")){ System.out.println("Automation tool has it's own Object Repository"); } if(AutomationTool.equalsIgnoreCase("RFT")){ System.out.println("This is not going to be printed on console"); } } } The if-then-else Statement: The if-then-else statement provides a secondary path of execution when an "if" clause evaluates to false. package mypackage; public class IfThenStatement { public static void main(String args[]){ String AutomationTool = "QTP"; if (AutomationTool.equalsIgnoreCase("RFT")){ System.out.println("This is not going to be printed on console"); } else{ System.out.println("Automation tool has it's own Object Repository"); } } } The for Statement: The for statement provides a compact way to iterate over a range of values. Programmers often refer to it as the "for loop" because of the way in which it repeatedly loops until a particular condition is satisfied. The general form of the for statement can be expressed as follows: for (initialization; termination;
  • 18. increment) { statement(s) } When using this version of the for statement, keep in mind that: • The initialization expression initializes the loop; it's executed once, as the loop begins. • When the termination expression evaluates to false, the loop terminates. • The increment expression is invoked after each iteration through the loop; it is perfectly acceptable for this expression to increment or decrement a value. The following program, ForLoop, uses the general form of the for statement to print the numbers 1 through 10 to standard output: package mypackage; public class ForLoop { public static void main(String[] args){ for(int i=1; i<11; i++){ System.out.println("Count is: " + i); } } } The switch Statement: Unlike if-then and if-then-else statements, the switch statement can have a number of possible execution paths. A switch works with the byte, short, char, and int primitive data types. It also works with enumerated types (discussed in Enum Types), the String class, and a few special classes that wrap certain primitive types: Character, Byte, Short, and Integer (discussed in Numbers and Strings). The following code example, SwitchDemo, declares an int named month whose value represents a month. The code displays the name of the month, based on the value of month, using the switch statement. package mypackage; public class SwitchDemo { public static void main(String[] args) { int month = 8; String monthString; switch (month) { case 1: monthString = "January"; break; case 2: monthString = "February"; break;
  • 19. case 3: monthString = "March"; break; case 4: monthString = "April"; break; case 5: monthString = "May"; break; case 6: monthString = "June"; break; case 7: monthString = "July"; break; case 8: monthString = "August"; break; case 9: monthString = "September"; break; case 10: monthString = "October"; break; case 11: monthString = "November"; break; case 12: monthString = "December"; break; default: monthString = "Invalid month"; break; } System.out.println(monthString); } } "Any fool can know. The point is to understand" - Albert Einstein
  • 20. Chapter-7 | File Input Output Operations Create a file in Java: The File.createNewFile() method is used to create a file in Java, and return a boolean value : true if the file is created successful; false if the file is already exists or the operation failed. package mypackage; import java.io.File; public class CreateFile { public static void main(String[] args) { try { File file = new File("src/newfile.txt"); if (file.createNewFile()) { System.out.println("File is created!"); } else { System.out.println("File already exists."); } } catch (Exception e) { e.printStackTrace(); } } } Note: You can use the same function to create a .json and .properties file. These file types are mostly used for the automation to accept input or write output. Write to file using BufferedWriter: In Java, BufferedWriter is a character streams class to handle the character data. Unlike bytes stream (convert data into bytes), you can just write the strings, arrays or characters data directly to file e.g. package mypackage; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; public class WriteFileBufferedStream { public static void main(String[] args) { try { String content = "This is the content to write into file"; File file = new File("src/newfile.txt"); FileWriter fw = new FileWriter(file.getAbsoluteFile()); BufferedWriter bw = new BufferedWriter(fw); bw.write(content);
  • 21. bw.close(); System.out.println("Done"); } catch (Exception e) { e.printStackTrace(); } } } Append to file using BufferedWriter: package mypackage; import java.io.BufferedWriter; import java.io.FileWriter; import java.io.PrintWriter; public class AppendFileBufferedStream { public static void main(String[] args) { try(FileWriter fw = new FileWriter("src/newfile.txt", true); BufferedWriter bw = new BufferedWriter(fw); PrintWriter out = new PrintWriter(bw)) { out.println("the text"); //more code out.println("more text"); //more code } catch (Exception e) { System.out.println(e); } } } How to READ file in Java – BufferedReader In Java, there are many ways to read a file, here we show you how to use the simplest and most common-used method –BufferedReader. package mypackage; import java.io.BufferedReader; import java.io.FileReader; public class ReadFileBufferedReader { public static void main(String[] args) { BufferedReader br = null; try { String sCurrentLine; br = new BufferedReader(new FileReader("src/newfile.txt"));
  • 22. while ((sCurrentLine = br.readLine()) != null) { System.out.println(sCurrentLine); } } catch (Exception e) { e.printStackTrace(); } } } "In learning you will teach, and in teaching you will learn" - Phil Collins
  • 23. Chapter-8 | First Selenium Program We have learnt and practiced good enough concepts that are required for creating automated test script using Selenium. In our first selenium script we are not going to use all the concepts but as we advance further those concepts will be required very frequently. To create our first automated script using selenium we further need to download and configure selenium-server jar. Follow the steps below for set-up and configuration: Step-1: Create a ‘jars’ folder inside your project folder i.e.’HelloWorld’ Step-2: Download selenium standalone server from following location: http://www.seleniumhq.org/download/ Step-3: Copy downloaded Selenium Standalone Server into your ‘jars’ folder created in step-1 Step-4: Mouse Right click on your project folder ‘HelloWorld’ in Eclipse and click on ‘Refresh’ option Step-5: You will see ‘jars’ folder and selenium standalone server inside it in ‘Package Explorer’ pane of Eclipse Step-6: Mouse Right click on your project folder ‘HelloWorld’ in Eclipse again and perform following steps: § Click on Build Path à Configure Build Path § Click on ‘Add External Jars’ button on ‘Properties for HelloWorld’ model opened § Navigate to ‘jars’ folder and select ‘Selenium Standalone Server’ jar § Click on ‘Open’ button § Click on ‘Apply’ button Step-7: Download ‘geckodriver.exe’ from following location and copy it into your ‘jars’ folder https://github.com/mozilla/geckodriver/releases Step-8: Make sure that you have the latest version of Firefox browser i.e. 49.0 or above Step-9:
  • 24. Create one class ‘FirstSeleniumProgram’ in ‘mypackage’ Step-10: Copy and paste the following code for execution on Firefox browser: package mypackage; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.firefox.FirefoxDriver; import org.openqa.selenium.remote.DesiredCapabilities; public class FirstSeleniumProgram { public static void main(String args[]) throws InterruptedException{ System.setProperty("webdriver.gecko.driver","jars/geckodriver.exe"); DesiredCapabilities capabilities=DesiredCapabilities.firefox(); capabilities.setCapability("marionette", true); WebDriver driver; try{ driver = new FirefoxDriver(capabilities); driver.get("https://accounts.google.com/SignUp?"); driver.findElement(By.id("FirstName")).sendKeys("test"); driver.findElement(By.id("LastName")).sendKeys("user"); driver.close(); } catch(Exception e){ System.out.println(e); } } } Step-11: Click on ‘Run’ icon from eclipse to run your first selenium program Execution: This program will launch the Firefox browser, open the Gmail sign-up page and enter text as ‘test’ in First name text field and ‘user’ in Last name text field. Change Required for Execution on Chrome: Step-1: Create one class ‘SecondSeleniumProgram’ in ‘mypackage’ Step-2: Download ‘chromedriver.exe’ from the following location and copy it your ‘jars’ folder http://chromedriver.storage.googleapis.com/index.html?path=2.24/ Step-3: Copy and paste the following code for execution on Chrome browser:
  • 25. package mypackage; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.remote.DesiredCapabilities; public class SecondSeleniumProgram { public static void main(String args[]) throws InterruptedException{ System.setProperty("webdriver.chrome.driver", "jars/chromedriver.exe"); DesiredCapabilities capabilities=DesiredCapabilities.chrome(); WebDriver driver; try{ driver = new ChromeDriver(capabilities); driver.get("https://accounts.google.com/SignUp?"); driver.findElement(By.id("FirstName")).sendKeys("test"); driver.findElement(By.id("LastName")).sendKeys("user"); driver.close(); } catch(Exception e){ System.out.println(e); } } } Step-4: Click on ‘Run’ icon from eclipse to run your first selenium program Change Required for Execution on Internet Explorer: Step-1: Create one class ‘ThirdSeleniumProgram’ in ‘mypackage’ Step-2: Download ‘IEDriverServer.exe’ from the following location and copy it your ‘jars’ folder http://www.seleniumhq.org/download/ Step-3: Copy and paste the following code for execution on IE browser: package mypackage; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.ie.InternetExplorerDriver; import org.openqa.selenium.remote.DesiredCapabilities; public class ThirdSeleniumProgram { public static void main(String args[]) throws InterruptedException{ System.setProperty("webdriver.ie.driver", "jars/IEDriverServer.exe");
  • 26. DesiredCapabilities capabilities=DesiredCapabilities.internetExplorer(); WebDriver driver; try{ driver = new InternetExplorerDriver(capabilities); driver.get("https://accounts.google.com/SignUp?"); driver.findElement(By.id("FirstName")).sendKeys("test"); driver.findElement(By.id("LastName")).sendKeys("user"); driver.close(); } catch(Exception e){ System.out.println(e); } } } Step-4: Check that Protected Mode settings for each zone to be the same value using following step Settings Internet Options Security Internet/Local Intranet/Trusted sites/Restricted sites Check or Uncheck ‘Enable Protected Mode’ checkbox for all the zones Step-5: Set Zoom level to 100% Step-6: Click on ‘Run’ icon from eclipse to run your first selenium program Note: For execution on IE-11 please refer settings mentioned on selenium website “Logic will get you from A to B. Imagination will take you everywhere” - Albert Einstein
  • 27. Chapter-9 | A Closer Look at First Selenium Program In this session we are going to discuss more about what we have written in our first Selenium Program using java to understand it in a better. public class FirstSeleniumProgram { public static void main(String args[]) throws InterruptedException{ System.setProperty("webdriver.gecko.driver","jars/geckodriver.exe"); DesiredCapabilities capabilities=DesiredCapabilities.firefox(); capabilities.setCapability("marionette", true); WebDriver driver; WebElement element; try{ driver = new FirefoxDriver(capabilities); driver.get("https://accounts.google.com/SignUp?"); element = driver.findElement(By.id("FirstName")); element.sendKeys("test"); element = driver.findElement(By.id("LastName")); element.sendKeys("user"); driver.close(); } catch(Exception e){ System.out.println(e); } } } System.setProperty("webdriver.gecko.driver","jars/geckodriver.exe"); We need geckodriver.exe for Firefox, IEDriverServer.exe for Internet Explorer and chromeDriver.exe for chrome browser. This .exe contains implementation of WebDriver wire protocol which is used for communication with Selenium Server to interpret and perform action accordingly. Every browser has its own rendering engine and mechanism so; we need separate .exe or implementation for each browser. In above statement we are providing the path of these exe that will be help Selenium Server/ WebDriver to identify the object on browser and perform operation as per WebDriver wire protocol. DesiredCapabilities capabilities=DesiredCapabilities.firefox(); Desired capabilities are used by WebDriver to set/configure the browsers to be used. It is always define in Key/Value pair (JSON format) e.g. browserName, version, platform etc. WebDriver driver;
  • 28. In the above statement we are creating an object instance of WebDriver which will act as a handle for the browser. WebElement element; In the above statement we are creating an object instance of WebElement which will hold the value of the web page object like text field, button, text etc. driver = new FirefoxDriver(capabilities); In the above statement we are initializing the driver with Firefox driver and given capabilities (given properties). This will work as a handle to the browser and will be user further to perform any action/operation on the opened browser. driver.get("https://accounts.google.com/SignUp?"); In the above statement we are using the function ‘get’ of class driver to open the application URL. element = driver.findElement(By.id("FirstName")); In the above statement we are identifying the element using findElement function providing the Object properties i.e. id in this case and its value i.e. FirstName. Also assigning this to an element class element which will be used later to perform action. element.sendKeys("test"); In the above statement we providing text as “test” in the text field that has been identified in the above step using the locator (Object Properties and its value i.e. id=FirstName). driver.close(); In the above statement we are closing the browser handle that has been initiated in the statement driver = new FirefoxDriver(capabilities); Note: element = driver.findElement(By.id("FirstName")); element.sendKeys("test"); element = driver.findElement(By.id("LastName")); element.sendKeys("user"); We keep assigning the element with the page objects properties to identify the element/object uniquely to perform action on it. In the above statements we have first assigned the element with First Name properties to identify the text field for First name and then performed enter operation on it. After that we have reassigned the element with Last Name properties to identify the text field for Last name and then performed enter operation on it. We will keep doing that for various element on which we will have to perform any kind of operation/action. “Live as if you were to die tomorrow. Learn as if you were to live forever”- Mahatma Gandhi
  • 29. Chapter-10 | Identifying Objects Uniquely In Introduction we have discussed that all the functional automation tools are object based. Every automation tool/api provide some or the other kind of mechanism to identify the elements/objects on the webpage uniquely. WebDriver also provide many ways to identify the elements/objects using its properties defined in the html code. These properties and its value are called as “Locators” in selenium/WebDriver. Following are the most commonly used locators in WebDriver: § ID § CSS § XPATH § Link Text Note: WebDriver provided more then dozens of locators to identify the elements/object on any web page but in real world above three are most commonly used. How to look for the object properties defined in html code of your browser? Step-1: Open https://accounts.google.com/SignUp? in your browser i.e. Firefox/chrome/IE Step-2: Right mouse click on the First name text field and click on “Inspect element” option Step-3 Developer’s tool will be opened at the bottom having html code highlighted for the First name text field which will look like below screenshot: Step-4: Html code highlighted in BLUE color contains the properties defined for the first name text field. Now we will have to use these properties only to identify the text field for first name uniquely. Let’s have a closure look of the locators and how to compose it. ID: ID or Identifier is the most reliable locator for any object on a web page. It is always unique for every element/object but, sometime developers do not provide ID for all the elements/objects so, we will have to use other locator type. Also, ID is categories into following 2 categories:
  • 30. Static ID: Static ID as shown in the above screenshot does not change with the session. It will remain same every time you open the page. These are most suitable to be used as it is. Dynamic ID: Dynamic ID is created at the runtime and contains some numbers mostly. It always changes with the session so, whenever you will open the page you will get a different ID value. These ID are not suitable to be used for locating/identifying the element/objects. Note: Always use static ID only for identifying the element/object uniquely. Else, use CSS or XPATH to for object identification. CSS: CSS stands for Cascading Style Sheets and it describes how HTML elements are to be displayed on screen. To locate/identify the element/object using CSS you will have to use the object properties to compose the CSS locator. Following is the simplest way of creating a CSS locator for the First name text field for which we have the html code in the screenshot: CSS = TagName/Node[property=’property value’] Here § Tag Name/Node = input § Property = id or name § Property value = FirstName or FirstName So CSS locator that can be easily created using the properties of the First Name text field are: § CSS = input [id=’FirstName’] § CSS = input [name = ‘FirstName’] Note: We will cover more about CSS selector locator in another chapter where we will learn few advance technique that can be used to create CSS locator XPATH: XPATH is a query language that is used to traverse through the DOM (Document Object Model). In a simple language you can say that XTAPH locator identify element by traverse through the DOM structure/HTML code. XPATH can be categories into following 2 categories: Absolute XPATH: § Absolute xpath locator start with ‘/’ (Single Slash) § It uses Complete path from the Root Element to the desire element § Absolute XPATH are generally very long
  • 31. § It provides the exact location of the element/object on the html page § It is more fragile than relative XPATH as minor change in the DOM structure will break it Relative XPATH: § Relative XPATH starts with ‘.//’ (dot followed by 2 slashes) § Relative XPATH starts from a parent node generally having id defined § Relative XPATH are shorter § It is less fragile as until the parent node is not changed it works perfectly § Relative XPATH is a bit slower than absolute XPATH § Relative XPATH is mostly used in Selenium for object identification Signature of Relative XPATH is: //TagName/Node[@property=’property value’] e.g. //input[@id=’FirstName’] or //input[@name=’FirstName’] Absolute XPATH for FirstName is: /html/body/div/div[2]/div/div/div/form/div/fieldset/label/input Note: We will cover more about XPATH locator in another chapter where we will learn few advance techniques that can be used to create XPATH locator Link Text: Link Text is mainly used for the links only. It is the easiest way to identify the link by its link label. In case you are not able to identify any link using Link Text or you have multiple link with the same label then you can always switch for CSS or XPATH locator. “If you can't explain it simply, you don't understand it well enough” - Albert Einstein
  • 32. Chapter-11 | Advance Technique to Compose CSS and XPATH locator In our previous session we have covered the simplest way of composing CSS and XPATH to identify the element/object on the web page. In this session we are going to learn some advance technique to compose CSS and XPATH. Also, this session will be more like a practice session to make sure that we have good enough understanding of CSS and XPATH to identify the element/object uniquely. Object identification is the building block for the automation tool. Selenium IDE a plugin for Firefox browser can be best used for validating that the CSS Locator or XPATH locator that has been composed for any element/object is identifying the element/object correctly or not. There are other plugins also available for Firefox, chrome and IE but, I prefer to use selenium IDE as I have never faced any issue once I have validated my locator with Selenium IDE. Validating Locator using Selenium IDE: Step-1: Open https://addons.mozilla.org/en-US/firefox/addon/selenium-ide/ in Firefox browser Step-2: Click on Add to firefox button and Selenium IDE is installed as a firefox plugin Step-3: Open https://accounts.google.com/SignUp in firefox browser Step-4: Open selenium IDE Tools Selenium IDE Step-5: Click in the table area to that will highlight the ‘Command’, ‘Target’ and ‘Value’ field and enable ‘Select’ & ‘Find’button. Step-6: In ‘Target’ field copy css=input[id='FirstName'] Step-7: Click on find button and you will see a green border appears around the FirstName text field and it is filled with yellow color for fraction of second. It means that the CSS locator is able to identify the element/object uniquely. Next we are going to use other advance technique to compose CSS locator for identification of few other element/object on this page. We will copy and paste it in Selenium IDE to validate that the CSS locator created is working perfectly. CSS #id: Selects the element with id="FirstName" • css=#FirstName element1~element2: Selects every <input> element that are preceded by a <strong> element • css=strong ~ input
  • 33. element+element: Selects all <input> elements that are placed immediately after <strong> elements • css=strong + input [attribute=value]: Selects all elements with name="FirstName" • css=[name="FirstName"] element>element: Selects all <p> elements where the parent is a <div> element • css=label[id="firstname-label"]>input :nth-of-type(n): Selects every <p> element that is the second <p> element of its parent • css=fieldset>label:nth-of-type(1)>input :nth-last-of-type(n): Selects every <p> element that is the second <p> element of its parent, counting from the last child • css=fieldset>label:nth-last-of-type(2)>input :nth-child(n): Selects every <p> element that is the second child of its parent • css=label[id='firstname-label']>input:nth-child(2) :only-of-type: Selects every <p> element that is the only <p> element of its parent • css=label>input:only-of-type XPATH: Unique ID: Selects the element with unique ID FirstName • xpath=//input[@id='FirstName'] child::input: Selects the first input child of the element with unique ID firstname-label • xpath=//label[@id='firstname-label']/child::input[1] descendant:: input: Selects the input element descendants of the context node • xpath=//label[@id='firstname-label']/descendant::input ancestor-or-self::input: Selects the input ancestors of the context node and, if the context node is a input element, the context node as well
  • 34. • xpath=//*[@id='FirstName']/ ancestor-or-self::input ancestor::label: Selects all label ancestors of the context node • xpath=//input[@id='FirstName']/ancestor::label descendant-or-self::input: Selects the input element descendants of the context node and, if the context node is a para element, the context node as well • xpath=//*[@id='firstname-label']/descendant-or-self::input self::input: Selects the context node if it is a input element, and otherwise selects nothing • xpath=//input[@id='FirstName']/self::input descendant::input: Selects the input element descendants of the chapter element children of the context node • xpath=//fieldset/child::label/descendant::input child::*/child::input: Selects all input grandchildren of the context node • xpath=//fieldset/child::*/child::input child::input[last()]: Selects the last input child of the context node • xpath=//label[@id='firstname-label']/child::input[last()] following-sibling::label[1]: Selects the next input sibling of the context node • xpath=//label[@id='firstname-label']/following-sibling::label[1]/input preceding-sibling::label[1]/: Selects the previous input sibling of the context node • xpath=//label[@id='lastname-label']/preceding-sibling::label[1]/input “A wise man can learn more from a foolish question than a fool can learn from a wise answer” - Bruce Lee