Selenium Notes
Selenium Notes
b) JAVA OOPS
1- Inheritance
2- Polymorphism
3- Abstraction
4- Encapsulation
JAVA Notes
1)-Byte (8 bits)
Example: byte a =10;
Characters
Conditional
8) - Boolean
Example: Boolean a = true
Variable – for variable you can change the value in the code
Constant – for constant you cannot change the values and it is final,
once declared. E.g., final int a = 10; (final is a keyword and needs to declare
before variable)
Wrapper class:
In order to use primitive data types as Objects, we have to use Wrapper Classes which help us in
converting the primitive data types into objects.
Java Variables:
What is variable – a named memory location to store the temporary data
within a program
- Variable names should not match with java keywords or reserved words
and must be unique in the scope of declaration meaning no duplications of
variable and not must exceed 255 characters e.g.
int a; -- correct
int new; --- incorrect
Types of variable in JAVA are:
Advantage of instance variable over local variable is you can access the
variable outside the block or inside any block
Java opertors
Logical Or operator ||
Example 2:
- If Statement
- Switch Statement
Nested Condition e.g. if (a>b) {if (a>c) {if (a>d)…n number of conditions
but it will check one by one condition and then go forward
For Loop
Syantax:
Example:
String languages [ ] = {“C”.”Cobol”,”Java”,VBScript”}
For (String Lang: Languages) {
System.out.println(lang);
}
Example 2:
Int a=10,b=20;
Int math = new int [3];
Math[0] = a+b;
Math[1] = a-b;
Math[2] = a*b;
For(int ma : math){
System.out.println(ma);
}
Numbers :
Operations on String:
- String + String - Concatenation by ‘+ ‘operator
- String + int Concatenation by – concat method
- Int + int addition
Example:
String str1=”Selenium”;
String str2=”UFT”;
System.out.println(str1+str2); // Selenium UFT
System.out.println(str1.concat(str2));concat is a method //Selenium UFT
System.out.println(“Selenium”+1+1); //Selenium11
System.out.println(1+1+”Selenium”); //2Selenium
String Comparison
Example:
JAVA Arrays
A Java array is an object that holds fixed numbers of values of single data
types (Only constant array in java)
- The length of array is established when array is created.
- Array length is fixed and index starts from 0 (zero)
Declaration of arrays:
Syntax:
Note : You can use the same datatype in java meaning you can use the fixed
datatype.
Two types of array:
1- Single Dimensional array
2- Multi dimensional array
- Using array we can optimize the code, data code be retrieve easily
- we can get required data index position
Two concepts:
Transfer statements are used to transfer the flow of execution from one block of code to a different
block of code.
break;
o The purpose of the break; statement is to come out of the statements based on some condition.
o Demonstrate the usage of break; statements inside any loop statement (Demonstrate here)
continue;
o The purpose of the continue statement is to skip the current iteration of a loop based on some
condition and continue with the next iteration.
o Demonstrate on how to use continue; statements inside any loop statement (Demonstrate here)
return
o Will be explained later, as it is used with methods.
try, catch, finally
o Will be explained later, as it is used in Exception Handling
Example:
Scanner scan = new scanner (system.in);
System.out.println(“Read Two numbers”);
String s1 = scan.nextline();
String s2 = scan.nextline();
Int a = Integer.parseInt(s1); // if you do not covert from string to int then it
will concatinating
Int b = Integer.parseInt(s2);
System.out.println(a+b)
Data Conversion :
Whenever we read any type of data from files or application objects then
computer program considers the data as string type data, in order to
perform mathematical operators then we need to convert the data (convert
only numeric values only and not alphabets)
Syntax:
Try
{
Statements
------------
-----------
}
Catch (exception name) {
Syso(Exception handling code)
}
Example:
Int a =10;
Int b=0;
Try
{
Int result = a/b;
System.out.println(result);
}
Catch(ArithmaticException e){
System.out.println(“dived by zero error”);
}
System.out.println(“Hello”);
System.out.println(“Selenium”);
Using file class we can create any data type of file and treat them as text
files only e.g. word ,excel etc. You can create excel or word file too but you
cannot enter the data in to the file
Example:
// Delete a Folder
File fileObject = new File (“c: /Users/Lenovo/Desktop/ABC”);
fileObject.delete();
systemout.println(“folder deleted”);
Constructors:--
the purpose of the constructor to simplify the process of initialization of the
variables.
class Car {
String carModel;
public Car(){
this keyword
The purpose of this keyword is to differentiate the instance variable
with the parameterized variables of methods/constructors.
1-String methods
2-Array methods
3-Number methods
4-character methods
Note:
Calling External methods- Creating in other class and calling in other class
Calling internal methods – Calling methods in same class is called internal
methods
Examples:
1- Writing methods (with returning value)
//Write Methods (Before main methods)
//Call Methods (After main methods)
Syntax:1(a)
accessModifier returnType methodName(parameters-optional and use
comma and pass n numbers of parameters);{
--------
--------
--------
}
//Calling Methods
Syntax:
ClassName ObjectName = new ClassName();
//Call methods by invoking object
ObjectName.MethodName(Values of parameter if any);
Example:
Public class JavaMethods{
//User defined methods
Public int multiply (int a, int b, int c) {
Int result = a*b*c;
Return result;
}
Public static void main (String [] args) {
// Create Object
1(b)- Method with returning value and calling the method without
object
Writing methods
accessModifier nonaccessModifier returnTypeName (Parameters){
Statements
-------------
------------
}
Example:
Class2
Public class class2 {
Public static void main (String [] args){
Class1 xyz = new class1();
xyz.studentRank(700);
}}
Class1
Public static void studentRank(int marks){
If(marks>=600){
System.out.println(‘Rank A”);
}
Elseif(marks>s=500){
System.out.println(“Rank b”);
}
Else{
System.out.println(“Rank C”);
}}
Public static void main (string[] args){
//Call Methods
Javamethods.studentRank(700);
}}
Class2
Public class class2 {
Public static void main (String [] args) {
Class1.studentRank (700);
}}
1- String methods
2- Number methods
3- Character methods
4 -Array methods
1-String Methods:
Example:
String str1 =”Selenium”;
String str2 =”SELENIUM”;
String str3 =”Seleniuma”;
String str4 =”Selenium”;
System.out.println(str1.compareTo(str2)); // positive value meaning >0
System.out.println(str1.compareTo(str3)); // Negative value
System.out.println(str1.compareTo(str4)); // both are equal value meaning
=0
Example:
String str1 =” Se lenium”;
String str2 =”SEL ENIUM ”;
2) Number Methods
3) abs() absolute value mean returns positive value but no rounding off
the value
Example
Double a =-10.234;
Double b =-10.784;
System.out.println(Math.abs(a)); // 10.234
System.out.println(Math.abs(b)); // 10.784
Example
Double a =-10.234;
Double b =-10.784;
System.out.println(Math.round(a)); // 10
System.out.println(Math.round(b)); // -11
Int a =5;
Int b=8;
Double c =-10.234;
Double d =-10.784;
System.out.println(Math.max(a,b)); // 8
System.out.println(Math.max(c,d)); // 10.784
System.out.println(Math.max(10,14);//14 direct values without declaring
the variable.
3) Character Methods
// the character class wraps a value of primitive data type char in an object.
2) isAlphabetic()
Example:
Char a =’z’; // single quote for char and double quote for string
Char b = ‘1’;
System.out.println(character.isAlphabetic(a));//true
System.out.println(character. isAlphabetic (b));//false
System.out.println(character. isAlphabetic (‘d’));
2-toString() – Prints an array ( without this method you can print via for
loop)
Example:
String array1 [] = {“selenium”,”UFT”,”RFT”,”Silktest”};
String str = Arrays.toString(array1); //Arrays is class and toString() is a
method
System.out.println(str);
1-Inheritance
2-Polymorphism
3-Abstraction
4-Encapsulation
Inheritance : It is a process of inheriting(reusing) the class
members(variables and methods(user defined methods but build in methods
you can use it anywhere) from one class to another class.
Example:
Int y = obj.add2()
System.out.println(y); // 70
Obj.multiply2(); //1200
}
}
1- Single inheritance
Example:
ClassB extends ClassA (ClassA is a super class)
Class 2
Class 1:
Class 2
Class 3
Note: In multilevel inheritance local class members will have the preference
to execute first if class members are same in all classes and after local then
parent class will have preference and then grandparents class will have
preference
Class 1:
Class 2
Class 1:
Class2
Another example if you want to access the variable and methods of class1
(package1) in Class2 (Package2) by making a class2 object but accessing
the variable and methods of class1(package1)
Class 1:
Class2
Polymorphism
Existence of object behavior in many ways (forms) is known as
polymorphism
Derived from Greek word:
Poly – many
Morph – ways
If two or more methods with same name in the same class but they differ in
following ways:
- Number of arguments or parameters
- Type of arguments
Example:
System.out.println(a+b+c);
}
Public void add (double a , double b){ // type is different but class name is
same
System.out.println(a+b);
}
Public static void main (String[] args){
Class1 obj = new class1 ();
obj.add(10,20,30); // object access methods based on their parameters
value and this is accessed by second method
obj.add(10,20); // Access by first method
obj.add(1.23,2.34) // Access by third method
If two or more methods are available in the super class and sub class
Example:
Public class Class1 {
Public void myMethod(){
System.out.println(“Selenium for test automation”);
}
Public static void main (String[] args){
Class1 obj1=new Class1 ();
Obj1.myMethod();
Output will be: UFT/QTP for test automation (Due to home or local method
is present that is why first it will access the home method and if there is no
home method then it will access the parent method)
OR,
Syntax:
Public void add () {
Statements
-----------
}
2- Abstract methods – the methods which are not having body (If we
know the method name but not known the method functionality).
Syntax:
Public abstract void add (); abstract is a keyword
Example1:
Class 1 (having 10 methods)
10 methods are concrete methods then it is called java class
Example2:
Class2 (having 10 methods)
5 methods are concrete methods and 5 methods are abstract methods and it
is known as abstract class
Example1:
Class 3 (having 10 methods)
All 10 methods are abstract methods then it will call as abstract class
Public abstract void engine (); //Eclipse will show error and give you a
option to change to abstract class.
Package javaexamples;
Public class HeroHonda extends Bikes{
Public void engine(){
System.out.println(“Bikes have engine”);
}
}}
Note:
Interfaces
- Selenium IDE has integrated development environment
- Selenium WebDriver has programming Interface but no IDE
- UFT/QTP has both IDE and programming Interface.
Java Interfaces
Class Vs Interface
Abstract Vs Interface
Note:
- All interface methods are by default public and abstract
- Static and final modifiers are not allowed in interface methods (Only static
and not non-static)
- In interfaces variables have to initialize at the time of declaration only
For Example: int a; a=100; (incorrect); int a=100; (Correct)
- In interfaces variables are public and final by default
- Interfaces are going to be used using “implements” keyword.
}
//Reuse methods from interface to Class
Package javaExamples;
Public class ClassNew implements Interface1 {
// it will show the error on ClassNew to implement the unimplemented
methods
//after clicking then all the interfaces will come on the sub class
//give a body to all methods
Public void engine () {
System.out.println(“Bikes have engine”)
}
Public void wheels () {
System.out.println(“Bikes have wheels”)
}
Public void seat () {
System.out.println(“Bikes have seat”)
}
Public void handle () {
System.out.println(“Bikes have handle”)
}
Public static void main (String [] args){
ClassNew obj=new ClassNew();
Obj.seat();
Obj.engine();
Obj.handle();
Note:
1- From class (Concreate class or Abstract class) to class we use extends
keyword
2- From interface to class we use implements keyword to re-use the
methods
3- Interface to interface we cannot access the methods from interface to
interface
Encapsulation
Advantage:
- It provides control over the data
- By providing setter and getter method, we can make a class read only or
write only
Example:
Package JavaExamples;
Public class Class1{
Private string name =”test Automation”;
Public string getName(){
Return name;
} public void setName(){
Name = newName;
}
Public static void main(String[] args){
Class1 obj = new Class1();
System.out.println(obj.getname);
}
// create another class and this class will be read only due to getter method
Packages javaExamples;
Public static void main(String[] args){
Class2 abc=new Class2();
abc.setName(“Selenium testing”); // for writing the value
System.out.println(abc.getName()); // for reading the value (can be used
read or write)
}}
Modifiers :
- Test Automation
Advantages:
a) Business Classification
- Vendor Tools e.g. HP tools, test complete etc.
- Open source tools e.g. Selenium, Jmeter, Bugzilla etc.
- In house tools
b) Technical Classification:
- Functional and regression test tools – UFT, RFT, Silk test, Selenium
etc.
- Performance test tools – Loadrunner, Jmeter , RPT , Silk Performer
- Test management tools – ALM/QC, JIRA etc.
- Defect management tools – Bugzilla, PR- tracker etc.
a) Decision to automation
d) Test Execution:
- Single test run
- Batch testing (executing series of batch)
- generating test reports
1-Test Planning
2-Test Design
3-Test Execution
4-Test Closure
1- Planning
2- Generating Basic tests
3- Enhancing Tests
4- Running and debugging Tests
5- Analyzing Test Results
6- Reporting Defects
Selenium Test Process
Phase I – Test Planning (Tasks)
In UFT:
- Object Repository based test design (Recording, Keyword Driven
methodology)
- Descriptive Programing (Static, dynamic Programing)
In Selenium:
- Using recording feature in selenium IDE / Type test scripts using UI
element identifiers and selenium commands
- Write test scripts using UI elements locators in Selenium RC (Out dated)
- Write test scripts using UI elements locators in WebDriver interface
Note: Selenium does not provide detailed test reports (summary only) and
using either Junit or Test Ng we can get detailed test reports
Note: Selenium does not integrate directly with any other tool for test
management or defect management tool (Double check)
What is Selenium?
Advantages of Selenium:
Disadvantage of Selenium:
- Application environment
- Web Browsers
- IE, Mozilla fire fox, Chrome, opera, Safari
Feature:
Limitations:
Selenium UFT
Open Source, No License Vendor , HP , Cost
Support Web based applications only Supports Desktop and Web
Applications
Using elements Locators Based on Add ins only it supports
Supports Java, C# ,PHP ,Ruby, VB script only
Python ,Perl to create and enhance
tests
Supports windows , UNIX , Mac etc. Only windows operating system
operating environments
Supports web browser e.g. IE, It supports only IE for designing and
Chrome ,Opera , Firefox ,Safari for execution Firefox , chrome
Limited support for image testing Rich support for image testing
Difficult to use Easy to use
No reliable technical Support HP provides support
New features may not work properly New features will work properly
No Object repository , No centralized Centralized maintenance of Objects
maintenance of objects e.g. shared object repository
No authorized Certification HP conducts certification
No other tools integration ALM/QC can be integrated for test
management tool
Frameworks:
- Junit
It is framework for unit testing and it can be used for Selenium functional
testing
Junit is used to execute test batches and generating reports
Frameworks are generally created if you have to execute the test case which
are in 100’s or 1000’ in number and all those test cases are created by the
team members and if all the team members are adopting their own strategy
then there will be a different approaches altogether and that could lead to
duplication of work or no work. In order to avoid all those things, we need to
lay down the framework that who will do what things e.g. first writing the
test cases and after that layout those test cases in a automation framework
by creating methods and calling those methods etc.
2nd method – When you want to use the functionality back, forward and
refresh then you need to use the navigate.to
Driver.navigate().to(http://www.google.com);
Driver.navigate().back();
Driver.navigate().forward();
Driver.navigate().refresh();
Simple Example:
Package WebDriversample;
Import org.openqa.selenium.by;
Import org.openqa.selenium.webdriver;
Import org.openqa.selenium.firefox.Firefoxdriver;
Selenium UFT
Element Object
locator Property
Locators
Introduction to Locators
We can use these locators in our test automation code to locate the UI elements on the Web
pages.
Demonstrate the usage of Locators in locating the UI Elements on the Web Pages using
Selenium IDE
The below are the different types of locators which can be used for locating the UI elements on the
Web Pages:
HTML Basics for Locators
Locators Priority
The below is the priority order in which we need to select and use
the locators :
- Launch Browser
- Navigate to specified URL
- Close focused browser
- Close all opened browser
- Navigate from one URL to another
- Navigate to back page
- Navigate to forward
- Refresh the browser
- Minimize the browser
- Maximize the browser
a) General Image
- Check the existence
- Check enabled or disabled status
b) Image button:
- Image button (submits)
c) Image Link
- Click, Redirects to another URL
6) Check Box – Operations on check box
- Check If the check box is displayed or not
- Check If the check box is enabled or not
- Check If the check box is select or not
- Check If the check box is un-select or not
Two ways of finding an element:
1)-Absolute xpath it will show from the starting of the document meaning
from the very beginning (hierarchical structure)
2) - Relative xpath it is not hierarchical and find the exact element
1-Xpath
2-ID
3-ClassName
4- Name
5- LinkText
6-CSS Selector
7- Partial Link
Writing customized xpaths:
Tagname = input
Attribute = ID
Value = email
Attributes Value
Id email
Class input text
Type text
Tabindex 1
Value “ “ – blank
Name email
Syntax: //tagname[@attribut=’value’]
//input[@name=’email’]
OR – If you are not sure about tag name then go for below syntax
Note: but make a habit of writing a tag name as values can be added so in
that case it can identify another value but if you have given tagname then it
will be unique.
Note: all the letters are case sensitive so make sure copy the exact words
and copy in xpath
Dynamic xpath are used for where the elements properties are continuous
changes e.g. when you search in the google and same thing searched in the
google there xpath will change.
Driver.findelement(by.xpath(”//* Starts-with(………)”);
Driver.findelement(by.xpath(”//* Contains(………)”);
and after that we need to see that how many elements are present in the
web page and in order to do that we need to do the following:
. (Dot) is by default
/ -- is for the first element in the page
// -- meaning it can be present anywhere in the page
For xpath where there is no unique id and traversing by some other element
id to that main element:
Commands are:
- Preceding – sibling ::
- Following –sibling ::
Customize xpath:
.//Div[@class=’’]
-- Shortest way to write the CSS locator path is for above login example is
#login1
-- In CSS instead of ‘/’ we need to give the space
-- In CSS instead of class we can use dot (.) and if there is any space
between values then use dot (.)
--In CSS starts with is written as ^ sign (carrot sign) instead of an whole
word like in xpath e.g. input[id^=’logi’
-- In CSS contains written as * instead of writing whole word contains like in
xpath e.g. input[id*=’ogin’]
Driver.Quit(); --- Closes all the browser opened by driver and destroys the
driver object.
What is the difference between implicit wait and explicit wait?
Explicit Wait explicit wait time is generally used and it is a best practice
e.g. when you pass the arguments as 5 seconds that means if Webdriver
gets the element in 2 seconds then it will not wait for another 3 seconds.it
will move on to the next line of code to execute but it will wait for 5 seconds
only and if the element does not appear then it will throw the error.
(Maximum and minimum time will vary on the condition and
element)
Radio Button:
WebDriver driver = new FirefoxDriver();
driver.get("http://www.echoecho.com/htmlforms10.htm");
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
// Make a list of all the radio buttons and put it into list (object)
List<WebElement> list =
driver.findElements(By.xpath("//input[@name='group1']"));
//Print the size of the list
System.out.println(list.size());
//loop to identify the value
for(WebElement e: list)
{
//get attribute meaning getting the names of all the values of radio button
System.out.println(e.getAttribute("value"));
// get to know that which button is selected and it will give the value in
boolean
System.out.println(e.isSelected());
// if condition for cheese meaning if you find cheese text then click on that
text
if(e.getAttribute("value").equals("Cheese"))
{
e.click();
}
}
// condition to see which value is checked or unchecked
System.out.println("-----------------------------------");
for(WebElement e: list){
System.out.println(e.getAttribute("value"));
System.out.println(e.isSelected());
}
}
We will look in detail for each of the webdriver methods that we have. The
first that we use is 'driver.get(url)' after starting the browser.
When we get the driver object, the below are the methods that we can
perform operation on a driver. In IDE like eclipse, when we enter driver. and
click on space bar, it will show all the below methods.
get()
getCurrentUrl();
getTitle()
findElements()
findElement()
getPageSource()
close()
quit()
Method Name :- get()
Syntax: get(url)
Example: driver.get();
Purpose: It will load a new web page in the current browser window. This is
done using an http get operation, and the method will block until the load is
complete.
Parameters: URL - The URL to load and it should be a fully qualified URL
Method Name: getCurrentUrl()
Syntax: getCurrentUrl()
Example: driver.getCurrentUrl();
Purpose: Gets a string representing the current URL that the browser is
opened.
Returns: The URL of the page currently loaded in the browser
Method Name: getTitle()
Syntax: getTitle()
Example: driver.getTitle();
Purpose: Gets the title of the current web page.
Returns: The title of the current page, with leading and trailing white space
stripped, or null if one is not already set
Method Name: findElements()
Syntax: findElements(By by)
Example: driver.findElements(By.xpath("//");
Purpose: Find all elements within the current page using the given
mechanism.
Parameters: By - The locating mechanism to use
Returns: A list of all WebElements, or an empty list if nothing matches
Method Name: findElement()
Syntax: WebElement findElement(By by)
Example: driver.findElements(By.xpath("//");
Purpose: Find the first WebElement using the given method.
Parameters: By - The locating mechanism
Returns: The first matching element on the current page
Throws: NoSuchElementException - it will return exception if no matching
elements are found
Method Name: getPageSource()
Syntax: getPageSource()
Example: driver.getPageSource();
Purpose: Get the source of the currently loaded page. If the page has been
modified after loading (for example, by Javascript) there is no guarantee
that the returned text is that of the modified page.
Returns: The source of the current page
Method Name: close()
Syntax: void close()
Example: driver.close();
Purpose: Close the current window, if there are multiple windows, it will
close the current window which is active and quits the browser if it's the last
window opened currently.
Method Name: quit()
Syntax: void quit()
Example: driver.quit();
Purpose: Quits this driver instance, closing every associated window which is
opened.
Method Name: getWindowHandles()
Syntax: Set getWindowHandles()
Example: driver.getWindowHandles();
Purpose: Return a set of window handles which can be used to iterate over
all the open windows of this Webdriver instance by passing them to
switchTo().WebDriver.Options.window()
Returns: A set of window handles which can be used to iterate over all the
open windows.
Method Name: getWindowHandle()
Syntax: String getWindowHandle()
Example: driver.getWindowHandle();
Parameter: Return an opaque handle to this window that uniquely identifies
it within this driver instance. This can be used to switch to this window at a
later date
switchTo
WebDriver.TargetLocator switchTo()
The next future commands will be performed to a different frame or window.
Returns: A Target Locator which can be used to switch or select a frame or
window
Method Name: navigate()
Syntax: WebDriver.Navigation navigate()
Example: driver.navigate.to("");
Purpose: An abstraction allowing the driver to access the browser's history
and to navigate to a given URL.
Returns: A WebDriver.Navigation that allows the selection of what to do next
Method Name: manage()
Syntax: WebDriver.Options manage()
Purpose: Gets the Option interface
Returns: An option interface