0% found this document useful (0 votes)
22 views

Full Compilation

hi

Uploaded by

MEERA SUPERSTORE
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views

Full Compilation

hi

Uploaded by

MEERA SUPERSTORE
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 99

OOPS Concepts definitions:

=====================
1.CLASS:
Class is the collection of objects and methods.
In our project We are using lots of predefined classes like
1.ChromeDriver
2.FireFoxDriver
3.InternetExplorerDriver
4.Actions
5.Robot
6.Select
7.RemoteWebDriver

OBJECT:
Object is an instance of a class.
Using object,we can able to access the methods in a class.
It is a runtime memory allocation.

Object creation syntax:


-----------------------------
Classname objectname=new Classname();

METHODS:
Set of actions to be performed.
Reusable lines of code can be kept inside a method.
We can access the method using object whenever needed.
How to access class properities using object:
object.variable;
object.method();
for eg:-
-------
get(), getTitle(), getCurrentUrl(), getText(), getAttribute()
2.ENCAPSULATION:
-->Wrapping up of data and code acting on data together in a single unit.
-->Encapsulation, is to make sure that "sensitive" data is hidden from users.
-->To achieve this, you must: declare class variables/attributes as private

-->Provide public getters and setters methods to access and update the value
of a private variable.
I am using encapsulation in real time in POJO class where I create all my
locator variables as private. Because private variables cannot be accessed
outside the class. If we want to access private variables we have to use
getters.

3.POLYMORPHISM:
Performing single action in different ways.

Method Overloading/Static Binding/CompileTime Polymorphism:


--> In same class,there are multiple functions with same name but different
parameters then these functions are said to be overloaded.
--> Same method overloaded again and again using different arguments
type,count and order.
For example:In realtime I m overloading println,sendkeys and frame methods
System.out.println("Renu");
System.out.println(123);
System.out.println(12.2);

webelement.senkeys("Renu"); //Here Sendkeys accepts only one


argument

Actions a=new actions(driver);

a.sendkeys(webelement,"Renu"); //using actions class also we can use


sendkeys,here i am passing two arguments

driver.switchTo.frame(String id);
driver.switchTo.frame(String name);
driver.switchTo.frame(int index);
driver.switchTo.frame(Webelement ); //For same methods i m passing String
type,int type and Webelement type

Method overriding/Dynamic Binding/RunTime Polymorphism:


-->Method Overriding is when one of the methods in the super class is
redefined in the sub-class.
(or)When I am not satisfied with the business logic of my super class i am
overriding that method in my subclass.

In Realtime I m overriding many methods such as retry() method from


IRetryAnalyser, transform() method from IAnnotationTransformer and
getMessage() method from Exception.
Notes:
-->A constructor cannot be overridden.
-->Final - declared methods cannot be overridden
-->Any method that is static cannot be used to override.
Child class:
public class Child extends Parent{
public void print() {
System.out.println("Child class method");
}
public static void main(String[] args) {
Child c=new Child();
c.print();
}
}
Parent class:
public class Parent {
public void print() {
System.out.println("Parent class method"); //overrided method
}
}

4.INHERITANCE:
--------------
Using inheritance we can access one class properties in another class without
multiple object creation.so we can save memory.Also we can acheive code
reusability.

In real time, I m using inheritance concept in base class where i will


maintain all reusable methods.so,by extending base class i can call reusable
methods wherever i want.

4a)SINGLE INHERITANCE:
One child class extends one parent class.

4b)MULTILEVEL INHERITANCE:
One child class extends more than one parent class in tree level structure.
4c)MULTIPLE INHERITANCE:
More than one parent class parallely supporting into one child class.We
can't acheive multiple inheritance in java due to
1.Syntax error/compilation error(After extends keyword we cannot specify
more than one class)
2.Priority problem(When parent classes having same method name with same
arguments)
extending into same child class,

4d)HYBRID INHERITANCE:
It is the combination of single and multiple inheritance.

4e)HIERARCHIAL INHERITACE:
More than one child class inheriting the same parent class.

5. DATA ABSTRACTION:
====================
Hiding the implementation of the program.
(or)
Process of hiding certain details and showing only essential information to
the user.
Abstraction can be achieved with either abstract classes or interfaces.
The abstract keyword is a non-access modifier, used for classes and methods:
1.Abstract class:
Contains abstract as well as non-abstract methods.
We can't create objects for abstract class(to access the methods in abstract
class, it must be inherited in another class).
Abstract method: can only be used in an abstract class, and it does not have
a body(business logic). The body is provided by the subclass which extends
the abstract class.
Non-abstract method(Concrete method):normal method with business logic.
In real time, I m using 'By' in my project which is an abstract class.
public abstract class Sample {
public abstract void clientId(); //abstract method which has no logic
public void clientName() {
System.out.println("Client name is CTS");
//non-abstract method with business logic
}
}
Why And When To Use Abstract Classes and Methods?

To achieve security - hide certain details and only show the important
details of an object.

2.Java Interface:
Another way to achieve abstraction in Java, is with interfaces.
-->An interface can have only abstract methods.
-->To access the interface methods, the interface must be "implemented"
(kind of "inherited") by another class with the implements keyword (instead
of "extends").
-->The body of the interface method is provided in the class which implements
the Interface.

public interface Test{

void add(); //All the methods inside interface will have 'public abstract'
by default,so no need to mention.
}

I am using many interfaces in my project such as Webdriver, webelement,


Alert, Wait, Javascript executor, Takesscreenshot, List, Set, Map etc
Notes on Interfaces:
-->Like abstract classes, interfaces cannot be used to create objects

-->Interface methods do not have a body - the body is provided by the


"implement" class
-->On implementation of an interface, you must override all of its methods
-->Interface methods are by default abstract and public
-->Interface attributes(variables) are by default public, static and final
-->An interface cannot contain a constructor (as it cannot be used to create
objects)
Why And When To Use Interfaces?
1) To achieve security - hide certain details and only show the important
details of an object (interface).
2) Java does not support "multiple inheritance" (a class can only inherit
from one superclass). However, it can be achieved with interfaces, class
can implement multiple interfaces.
Advantages of Abstraction:
It reduces the complexity of viewing the things.
Avoids code duplication and increases reusability.
Achieving Multiple inheritance using interface:

1.we will not get syntax error because after "implements" keyword we can
specify any number of interfaces.
2.There will be no priority problem (Though all the interfaces have same
method, the definition for the particular method

will be present only in the class which implements all the interfaces--->so
there will be one method definition)

package org.cts.test;

public class Company implements Int1,Int2{

@Override

public void intId() {

System.out.println(123);

public void intName() {

System.out.println("Multiple Inheritance achieved through interface");

}
public static void main(String[] args) {

Company c=new Company();

c.intName();

c.intId();

}
Difference between Abstraction and Encapsulation:
Encapsulation is data hiding(information hiding) while Abstraction is detail
hiding(implementation hiding)
While encapsulation groups together data and methods that act upon the data,
data abstraction deals with exposing the interface to the user and hiding
the details of implementation.
STRING:
Strings are collection of characters enclosed within " " . In Java, String
is a Class,strings are treated as objects.
String Literal:
String str = “Java”;
Literal string shares the same memory incase of duplicates.
It is stored in String pool constants(String pool constants present inside
heap memory)

When String declared like this, intern() method on String is called. This
method references internal pool of string objects. If there already exists
a string value “Java”, then str will get reference of that string and no new
String object will be created.

String Object(Non-Literal String)


Non-literal string will not share the same memory even if it is a duplicate.
Since we use "new" operator everytime it creates new memory.
Non-literal strings stored in heap memory.
String str = new String(“Java”);

In this,JVM is forced to create a new string reference, even if “Java” is


in the reference pool.

Performance Comparison between String literal and String constant:

If we compare performance of string literal and string object, string object


will always take more time to execute than string literal because it will
construct a new string every time it is executed.
IMMUTABLE STRING:
Immutable string once string created,value can't be changed in reference.
Eg:String literals
MUTABLE STRING:
For mutable string,we can change the value in reference.
Eg:StringBuffer,StringBuilder
StringBuffer->Synchronised(One thread can only access StringBuffer class at
a time),Thread safe
StringBuilder---->Asynchronised(Multiple threads can access StringBuilder
class at a time),Not thread safe.
Program:

Note:
System-class
identityHashCode() -method to find the address of the variable.
TYPES OF VARIABLES:
LOCAL VARIABLE:
Local variable scope is only inside the method/block.
We cant use access specifiers for local variable.
We need to initialise local variable.

INSTANCE/GLOBAL VARIABLE:
Global variable declared inside class and outside methods.
We can use access specifiers for global variables.
Need not initialise value for global variable.It will have default value.

STATIC VARIABLE:
Static variable retains value between the objects(Since static variable is
shared by all the objects)

2 ways of accessing static variables:


classname.variablename
variablename

Static method:
If u specify a method as static, we need not create object for calling the
methods.

2 ways of accessing static methods:


classname.methodname();
methodname();
Program to show the difference between global variable and static variable:
--------------------------------------------------------------------------

public class Variable {


static int a=20;
int b=10;
public void print() {
System.out.println(a);
System.out.println(b);
a++;
b++;
}
public static void main(String[] args) {
Variable a=new Variable();
a.print();
Variable b=new Variable();
b.print();
Variable c=new Variable();
c.print();
}
}
OUTPUT:
------------
20
10
21 //static variable retains value between objects
10
FINAL VARIABLE:
1.If a variable declared as "final"---->we can't change the value assigned.
2.If a method as declared as "final"----->We can't override that method.
3.If a class as declared as "final"-------->We can't inherit that class.

Access Modifiers:

It is used to set the access level for classes, attributes, methods and
constructors.
We divide modifiers into two groups:
Access Modifiers - controls the access level
Non-Access Modifiers - do not control access level, but provides other
functionality
Access Modifiers:
private
default or no modifier
protected
public
A)Public(Project level access/Global level access)

In same package as well as different package,we can access the private


variables and methods of one class in another class using extends keyword
and creating separate object.
B)Protected(Global level access)
In same package,

Using extends keyword and by creating separate object also we can access the
properities of another class.
If it is in different package,

using extends keyword only we can access,We cannot create object and access
the protected attributes of a class.
C)Default(Package level access)
In same package only we can access(In different package we cannot access)
using extends keyword and by creating object.
D)Private(Class level access)
Outside class,we cannot access private variables.If we want to access private
variables outside the class we use getters
and setters.

Non Access Modifiers:


static
final
abstract

synchronised---->When Methods given with synchronised keyword,it can only


be accessed by one thread at a time

transient--->At the time of serialization, if we don’t want to save value


of a particular variable in a file, then we use transient keyword. When JVM
comes across transient keyword, it ignores original value of the variable
and save default value of that variable data type.

volatile--->volatile variable in Java is a special variable which is used


to signal threads, a compiler that this particular variables value are going
to be updated by multiple threads inside Java application. By making a
variable volatile using the volatile keyword in Java, application programmer
ensures that its value should always be read from main memory and thread
should not use cached value of that variable from their own stack.

strictfp-->Java strictfp keyword ensures that you will get the same result
on every platform if you perform operations in the floating-point variable.
STORAGE IN JAVA:
What is Stack Memory?

Stack in java is a section of memory which contains methods, local variables,


and reference variables. Stack memory is always referenced in Last-In-First-
Out order. Local variables are created in the stack.
Stack memory structure is mostly implemented for providing static memory
allocation.

What is Heap Memory?


Heap is a section of memory which contains Objects and may also contain
reference variables. Instance variables are created in the heap

Program Counter Register: Programs are a set of instructions.Program counter


register holds the address of the upcoming instructions to be executed.

CONSTRUCTOR:

Whenever you create object for a class,default costructor will automatically


invoked since class name and constructor name are same.

Purpose of constructor:
-->A constructor in Java is a special method that is used to initialize
objects.
-->The constructor is called when an object of a class is created.

-->All classes have constructors by default: if you do not create a class


constructor yourself, Java creates one

Rules:
-->constructor name must match the class name.
-->It cannot have a return type (like void)
Types:
Default constructor:(without arguments)
public class MyClass {
int x;
public MyClass() {
x = 5;
}
public static void main(String[] args)
{
MyClass myObj = new MyClass();
System.out.println(myObj.x);
}
}
// Outputs 5

Parameterized constructor:(With arguments)

public class MyClass {


int x;
public MyClass(int y) {
x = y;
}
public static void main(String[] args) {
MyClass myObj = new MyClass(5);
System.out.println(myObj.x);
}
}
// Outputs 5
Exception:
Exception results in abnormal termination of the program (or)Whenever
exception occurs, program terminates at the particular line itself.
We can avoid the abnormal termination of the program by handling the
exception.
Object
|
Throwable
|
Exception

Exception handling:
try block:
The code which is expected to throw exceptions is placed in the try block.
Catch block:

When an exception occurs, that exception occurred is handled by catch block


associated with it.

Every try block should be immediately followed either by a catch block or


finally block.
finally block:
The finally block follows a try block or a catch block.
A finally block of code will always be executed whether exception occurs or
not.

we can have,
Impossible combination:
-->Throwable class is the super class of all exception.

-->This will handle all the exceptions.so all the child catch blocks will
not be used/reached by any code.
-->so while writing the program itself,it will show error.

try
{
}
Catch(Throwable e){
}
Catch(Exception e){
}
Catch(ArithmeticException e){
}

possible combination:
-->we can specify multiple catch blocks

try
{
}
Catch(ArithmeticException e){
}
Catch(IndexOutOfBoundException e){
}
Catch(Throwable e){
}
throw:
It is used to explicitly throw an exception.

You cannot throw multiple exceptions.Only one exception can be thrown at a


time.
Throw is used within the method.
Checked exception cannot be handled using throw.
Throw is followed by an instance.

throws:
throws keyword is used to declare an exception at method level.
Can handle checked as well as unchecked exception.
Throws is used with the method signature.
You can handle multiple exceptions using throws.

Errors :
These are not exceptions at all, but problems that arise beyond the control
of the user or the programmer. Errors are typically ignored in your code
because we cannot handle the error.
For example, JVM crash, stack overflow, insufficient memory. They are also
ignored at the time of compilation.

Note:
-->A catch block cannot exist without a try statement.
-->It is not compulsory to have finally block whenever a try/catch block is
present.

-->The try block cannot be present without either catch block or finally
block.
-->No code can be present in between the try, catch, finally blocks.
-->We can have 'n' number of exception throwing statements in try block,
once an exception caught control will be moved to catch block, all the
remaining lines won’t be executed.
WHAT IS AUTOMATION TESTING?

Test Automation is a process that makes use of automation testing tools to execute
pre-scripted tests on applications, then compares the test results to the expected behaviour and
reports it to the testers.

Benefits:
1. It executes tasks automatically
2. Faster feedback
3. Increase effectiveness
4. Efficiency
5. Coverage of the software testing.

SELENIUM
Selenium is a test automation tool used to automate web-based application.
Selenium is an open-source automation testing tool which is used for automating tests
carried out on different web-browsers.
Advantages of Selenium
1. Language and Framework support
2. Opensource
3. Multi browser support
4. Support across various operating system.
5. Less hardware usage
Drawback:
We can’t automate desktop application using selenium.
Selenium Components:
1. Selenium IDE
2. Selenium RC (Remote control)
3. Selenium WebDriver
4. Grid
Selenium IDE: -

• Selenium IDE is a Firefox plugin which is used to create and execute test cases
• It records and plays back the interactions which the user had with the web browser
• Using IDE, you can export the programming code in different languages: Java, Ruby,
Python and so on

Selenium Grid: -

• Selenium Grid is used for parallel testing or distributed testing. It allows us to execute
test scripts parallelly on different machines
Selenium RC: -

• Selenium Remote Control (RC) is used to write test cases in different Programming
languages
• In Selenium IDE, we can run the recorded scripts only in Firefox browser, whereas, in
Selenium RC, we can run the recorded script in any browser like IE, Chrome, Safari,
Opera and so on

Selenium WebDriver: -

• Selenium WebDriver is a tool used to automate testing for web application


• It allows us to execute tests against different browsers like Firefox, Chrome, IE & Safari
• Selenium WebDriver eliminated the use of Selenium Server thus making it work faster
than RC

Latest version of selenium


selenium-server-standalone-3.141.59

Browser Driver Key Class

Chrome chrome driver webdriver.chrome.driver ChromeDriver

Firefox gecko driver webdriver.gecko.driver FirefoxDriver

Internet Explorer ie driver webdriver.ie.driver InternetExplorerDriver

To configure Driver:
Create new project → Right click → New → New folder {copy driver file}

Name the folder (driver will be best practicing)

Paste driver exe file


To configure browser:
System.setProperty( key , path of the driver );
System is a class.
setProperty() is a method in this we have to pass key and value.
It is used to set the key and path location of driver.
WebDriver
WebDriver is a interface.
WebDriver is a web automation framework that allows you to execute your tests against
different browser.
WebDriver also enables you to use a programming language in creating your test script.
It is mainly used for providing the connection between the browser and local system.
It acts as a bridge.

Instantiate for webdriver:


WebDriver refName = new DriverClassName();
WebDriver Methods:

Return
Method Description
Type
To launch given URL in the
driver.get(“url”);
configured browser
To get the title of the webpage
driver.gettitle(); String
launched
To get the URL of the current
driver.getCurrentUrl(); String
webpage
driver.quit(); To quit the browser

driver.manage().window().maximize() To maximize the browser tab

driver.switchTo().alert() Alert Switch to alert


Sample Program:
==============

package org.day.one;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

public class Sample {

public static void main(String[] args) {

//configure your browser


System.setProperty("webdriver.chrome.driver", "C:\\Users\\Azar. A.
R\\eclipse-workspace\\SCalss1\\Drivers\\chromedriver.exe");

//Instantiate for webdrivers


WebDriver d=new ChromeDriver();

//to maximize browser


driver.manage().window().maximize();

//to launch given url


d.get("https://www.facebook.com");

//to get the title of the webpage launched


String title = d.getTitle();
System.out.println(title);

//to get the url of the current page


String url = d.getCurrentUrl();
System.out.println(url);

//to quit the browser


driver.quit();

}
Locator:
When we need to perform any action in the browser, we have to find the locator.
Locators used to find and match the elements of your page that it needs to interact with.
In By class all the locator methods are available
By→ Abstract Class Package→ selenium.By
Static Methods of By

id xpath
name tagName
className linkText
partiallyLinkText
cssSelector
WebElement
WebElement → Interface Package →selenium.WebElement
Anything that is present on the web page is a WebElement such as text box, button, etc.
WebElement represents an HTML element. Selenium WebDriver encapsulates a simple form
element as an object of the WebElement. It basically represents a DOM element and all the
HTML documents are made up by these HTML elements.

Methods of WebElement:

txt.sendKeys(“sequence”) To pass any values in the textbox


btn.click() To perform click option for button
txt.getText() String To print the text in the WebElement

To print the attribute value in the web


txt.getAttribute(“AttribiuteName) String
element

To print the values we have passed in


txt.getAttribute(“value”) String
text box

1) By.id()
id value is “email”. and it’s a textbox, then we can find the locator by
WebElement txt = driver.findElement(By.id("email"));

2) By.name()
name value is “email”. and it’s a textbox, then we can find the locator by
WebElement txt = driver.findElement(By.name("email"));

3) By.className()
class value is “inputtext _55r1 _6luy”. and it’s a textbox, then we can find the locator by
WebElement txt = driver.findElement(By.className("inputtext _55r1 _6luy"));
package org.day.two;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;

public class One {

public static void main(String[] args) {

System.setProperty("webdriver.chrome.driver", "C:\\Users\\Azar. A.
R\\eclipse-workspace\\SDay2\\driver\\chromedriver.exe");

WebDriver driver=new ChromeDriver();

driver.get("https://www.facebook.com/");

//to find locator of the user name


WebElement txtUserName = driver.findElement(By.id("email"));
//to pass values in the text box
txtUserName.sendKeys("[email protected]");

//to find locator of the password field


WebElement txtPassword = driver.findElement(By.name("pass"));
txtPassword.sendKeys("123456789");

//to find locator of login button


WebElement btnLogin = driver.findElement(By.className("login"));
//to click button
btnLogin.click();
}
}

4) By.xpath()
Xpath is one of the locator available in webpage.
/ → absolute path (It find the WebElement from the top of the downstream.)
// → relative path (It find the WebElement from that particular tag.)
Reason for going to Xpath:
For validating the locator. (We can check this in webelements by ctrl+F)
When id,classname,name is not present.
General syntax:
//tagName [ @attributeName = ’ attributeValue ’ ]
If there is more than one attribute value is same for same attribute names in the web element
then we have to go for index(matching with more than one loctor)
General syntax:
( //tagName [ @attributeName = ’ attributeValue ’ ] ) [2]
When we try to find locator, if only text is present there then we go for text
text()
//tagName [ text( ) = ’ text name ’ ]
contains()
//tagName [ contains ( text( ) , ’partially text’ ) ]
contains() using attributes
//tagName [ contains ( @attributeName , ’attributeValue’ ) ]

Example Program
==========================================================================================
DEBUG
It is the step by step verification.
We can easily identify the step where the code getting exception.

Steps for debug:


1. Set a break point(double click at the line number.
2. R+click
3. Debug as
4. Java application
5. Switch
F6=> stepover
F8=>close debug
Types of Debug
Eclipse debugger.
Firefox JavaScript debugger.
Dynamic debugging technique
On line debugging tool.

For page loading time issue


Thread.sleep(milliseconds);
Thread => class
sleep()=>static method
It throws Interrupted Exception
1000 milli second = 1 second
ACTIONS
Actions → Class
Package → selenium.interactions
MouseOverAction
When we place a mouse on some option it will display a list of subOption.
For mouseOverAction we can use Actions class.

Declare Actions
Actions a = new Actions(WebDriver ref name);
Methods in Action

a.moveToElement(WebElement) To move mouse point or curser to webelement

a.dragAndDrop(source,target) For drag and drop option

a.sendKeys(source,sequence) To pass any values in the textbox

a.sendKeys(char sequence) To pass any values in the textbox

a.doubleClick(WebElement) To perform double click

a.contextClick(WebElement) To perform right click

The menu list disappears within the fractions of seconds before Selenium identify the next
submenu item and perform click action on it.

So, it is better to use .perform() method.

Whenever Actions methods takes place we use or end that method with perform() to perform
that method.
If we use one method to perform we use perform();
If we use more than one method in one line of code we use buid().perform();
Example Program

==========================================================================================
ROBOT
o Robot → class
o Package → java.awt
o Exception →AwtException(Abstract window toolkit)
Robot class is a class which is used to perform the keyboard action in java.
Declare Robot
Robot r=new Robot();
Mehods of Robot:
r.keyPress() To press any key
r.keyRelease() To release key(whenever keyPress() takes place
keyRelease() should also mentioned)
KeyEvent => Class(takes place inside the robot method where it consists of all keyboard
keys).

Example Program
ALERT
Alert → interface
Alert is a small message box displayed on the screen to give some information to the
user. Alert and webpage are different Alert has no locators. When alert appeared first we
need to switch into the alert to handle the alert, then only user can perform the next operation
in the webpage.
To switch into the alert
Alert a=WebDriver.switchTO().alert();
Types of Alert
1. Simple Alert → Contains only ok button
2. Confirm Alert → Contains both ok and cancel button
3. Prompt Alert → Contains text box with ok and cancel button
Methods in Alert
r.accept() Accept the alert
a.dismiss() Dismiss the alert
a.sendKey() To insert the values
a.getText To print the text in the alert

Simple Alert
Confirm Alert

----------------------------------------------------------------------------------------------------------------
Confirm Alert
JAVASCRIPT EXECUTOR

Java Script → Interface


Package → selenium.JavaScriptExecutor

JavaScriptExecutor is an Interface that helps to execute JavaScript through Selenium


Webdriver.
In Selenium Webdriver, locators like XPath, CSS, etc. are used to identify and
perform operations on a web page.
In case, these locators do not work you can use JavaScriptExecutor. You can use
JavaScriptExecutor to perform a desired operation on a web element.

To implement JavaScript

1. Type casting
JavaScriptExecutor js = ( JavaScriptExecutor ) WebdriverRef.Name
2. Use methods in JavaScript

Methods of JavaScript

js.executeScript ( “JavaSript code” ,WebElement reference );

JavaScript Codes

To pass any input text in text


arguments[0].setAttribute('value','input txt')
box

Retrieve the values of user


return arguments[0].getAttribute('value') String
entered text

arguments[0].click() For button click

arguments[0].scrollIntoView(false) Scroll down

arguments[0].scrollIntoView(true) Scroll up

When ever we want retrieve the user entered values the method returns Object. With
that object reference name we can do upcasting to get string values to be printed.
String s1=(String)object;
Example

---------------------------------------------------------------------------------------------------------------------------------------------------
TAKES SCREENSHOT
TakesScreenshot → Interface
TakesScreenshot ts=(TakesScreenshot)WebDriverRef.Name;
Methods
File src = ts.getScreenshotAs(OutputType.FILE);
File → Return type for getScreenshotAs( );
Steps:
1. Typecast
2. Store screenshot in default
3. Create a screenshot
The output format of the screenshot will be Base64, Bytes, Class, FILE.
In order to store the screenshot in our project folder
1. After taking the scerrnshot, create a file class
2. Create a folder in the package and give the path of the folder in the File class
3. In the path at last add the name of the screen shot.
4. Use FileUtils.copyFile(source, destination); to copy src file and past it in the desired
project folder. Source → ref name of getScreenshotAs( ).
5. copyFile() is a static method in the FileUtils class.

Example
VISIBLITY OF WEBELEMENT

To check visibility of the WebElements


isEnabled() - method to check whether the web element is enabled or not.
isDisplayed() - method to check whether the web element is displayed(present) or not
isSelected() -method to check whether the web element is selectable or not

It is widely used in radio button, dropdown, checkbox


FRAMES
html embedded inside another html
When any locator is placed inside the frame we cannot directly access the locator.
First we need to switch into the frame, then only we can access frame.

To switch into frame


First we have to check frame is available in DOM or not.
R + click → view frame source
Or
Inspect→cntrl + F →//iframe or //frameset etc.

Methods to switch into frame (method-overloading)


driver.switchTo().frame(string id);
driver.switchTo().frame(string name);
driver.switchTo().frame(web element);
driver.switchTo().frame(index);
Methods to switch out of frame
To switch from current frame to immediate parent frame (frame inside frame concept)
driver.switchTo().parentframe();
To switch the control from any frame to main.
driver.switchTo().defaultContent();
Example
WINDOWS HANDLING
Whenever we execute any program it can access current window webelement only.
When we have multiple windows to switch control between windows we go for
windows handling.
To switch into other window
driver.switchTo().window(String URL)
driver.switchTo().window(String title)
driver.switchTo().window(Window ID)

To find window ID
Parent id:
driver.getWindowHandle() → String
Child id:
driver.getWindowHandles() → Set<String>
WEBTABLE
To access the elements in the webtable we need to go for it.
Every table must be in the pattern of

table - tag name

tr - table row

th - table heading

td - table data

To find the web table


To print the first row of the table
DROPDOWN
Whenever dropdown takes place we need to go for Select class.
Select s=new Select(WebElement)
Dropdown Syntax Methods:

Example:
CSS VALUE

If the tag name changes dynamically we can use *.


Eg:
//button[@name=’login’] →here the button name changes dynamically
//*[@name=’login’] → use *
Highlighting text
NAVIGATION COMMANDS

driver.navigate().to(“url”) To navigate to given url


driver.navigate().forward() To move to the next page
driver.navigate().backward() To move to the current page
driver.navigate().refresh() To refresh the particular page

get() Will wait till the webpage loaded completely and it will not maintain
cookies(history)
navigate().to() Will not wait till the page load completely. But it will maintain browser history
so that we can move to the previous page and next page.
WAITS (synchronisation)
Types:
1. unconditional wait
2. conditional wait
1. Unconditional Wait
Thread.sleep() → For the given time script will pause its execution. Even the
webelement is found earlier the program will not resume until the given time completes.
Disadvantages
1. Application will get slow
2. Performance will be reduced.
2. Conditional Wait
For a given condition we can make our script to wait is known as conditional wait.
Types
1. Implicit Wait
2. Explicit Wait
2.1 Implicit Wait
Whenever we need to find webelement in webpage, if the webelement is not present,
before throwing the exception it will wait for the given time. When the webelement appeared
the program will resume and it wont wait for the time to complete
If it could not find the webelement it will throw TimeOutException.
It is applicable for all the locators.
Default polling time is 250 ms(milli seconds)[every 250ms it will go and check the
webelement found or not)
2.2 Explicit Wait
It is applicable for particular locator/ condition.
For the given condition to be satisfied or for finding the webelement till that we can
make our program to wait.
Types
1. WebDriverWait
2. FluentWait

Wait (Wait is the interface)


FluentWait implements Wait
WebDriverWait extends FluentWait
All the methods in fluent wait will also be in WebDriverWait
2.2.1 WebDriverWait
Whenever the time interval we give it will take only in SECONDS (so we cannot
overload).
It cannot handle TimeOutException.
Default polling time is 500 ms
WebDriverWait w = new WebDriverWait(driver, 10);
2.2.2 FluentWait
We can give the time interval in terms of MILLISECONDS, MACROSECONDS etc.
It can handle TimeOutException.(because here we have additional method)
We can set the polling time.
Methods

WebDriver d=new ChromeDriver();


WebDriver = d

d.get("url") To get into / launch webpage


d.getTitle() String To print the title of the webpage
d.getCurrentUrl String To print the current page url
d.manage().window().maximize() To maximize the window screen
d.findElement() WebElement Find the webelement in the webpage
d.findElements() List<WebElement> Find all the xpath with similar xpath name
d.quit() To quit the browser

ALERT
d.switchTo().alert() Alert To switch into alert when alert takes place

FRAMES
d.switchTo().frame() to switch into frame
d.switchTo().parantFrame() to switch from child frame to parent frame
d.switchTo().defaultContent() to switch from frame to main content

WebElement e=driver.findElement(By.id("email"))
WebElement=e

By.locator() to get the locator


e.sendKeys to pass the values in the text box
e.click to click button in web page
e.getText() String print existing text in the webpage
e.getAttribute("AttributeName") String to print the atribute value
e.getAttribute("value") String to print the user enterd value in the webpage
e.findElement() Find the webelement in the webpage
e.findElements() Find all the xpath with similar xpath name
Locator
By.Locator

By.id() id value
By.name() name value
By.className() class value

By.Xpath() attributes
//tagName[@attributeName='attributeValue']
text
//tagName[text()='textName']
partial text
//tagName[contains(text(),'partial text']
partial attribute
//tagName[contains(@atttributeName,'attributeValue')]

VISIBLITY OF WEBELEMENT
e.isSelected() Boolean to check whether the webelement is selected or not
e.isEnabled() Boolean to check whether the webelement is enabled or not
e.isDisplayed() Boolean to check whether the webelement is displayed or not

CSS VALES
e.getCssValue("details tag");

Actions a = new Actions(d)


a.moveToElement(e) To move curser/ mouse point
a.dragAndDrop(source e, target e) For drag and drop option
a.doubleClick(e) double click option
a.contextClick(e) right click option
a.sendKeys(source e, target words) pass values in text field
perform() mentioned at last of actions method

Robot r =new Robot()


r.keyPress() Key press operation
r.keyRelease() Key release operation
KeyEvent.VK_DOWN eg for downkey operation inside robot method
KeyEvent.VK_UP eg for upkey operation inside robot method
KeyEvent.VK_SHIFT eg for shiftkey operation inside robot method
Alert ar=d.switchTo().alert();

ar.accept() accept the alert


ar.dismiss() to dismiss the alert
ar.sendKeys() to insert the value in alert
ar.getText() String to print text in the alert

JavaScriptExecutor js = (JavaScriptExecutor)d

js.executeScript ( “JavaSript code” ,WebElement


reference ); to excecute JavaScript
JavaScript Codes
arguments[0].setAttribute('value','input txt') to pass any input text in the text box
return arguments[0].getAttribute('value') String to retrieve the user enterd values
arguments[0].click() to click any button
arguments[0].scrollIntoView(false) for scroll down operation
arguments[0].scrollIntoView(true) for scroll up operation
to heighlight the webelement in the
arguments[0].setAttribute('style','background:color') wepage

TakesScreenshot ts=(TakesScreenshot) d;

ts.getScreenshotAs(OutputType.FILE) File to take screen short and return file directiry stored

to copy from the default storage and paste it in the


FileUtils.copyFiles(source,destination) destination

d.switchTo().frame()

d.switchTo().frame(String id) To switch into frame


d.switchTo().frame(String name) To switch into frame
d.switchTo().frame(webelement) To switch into frame
d.switchTo().parantFrame(String id) to switch out of child frame
d.switchTo().defaultContent() to switch to main page of DOM
d.switchTo().window()

d.switchTo().window(string url) to switch into other window using url


d.switchTo().window(string title) to switch into other window using page title
d.switchTo().window(string id) to switch into other window using window id
to find id
d.getWindowHandle() String to get parent id
d.getWindowHandles() Set<String> to get all the windows id
d.switchTo().defaultContent() to switch to main parent window

Waits

Unconditional wait
Thread.sleep(milliseconds)
Conditional Wait
Implicit wait
d.manage().timeouts().implicitlyWait(10,TimeUnit.SECONDS)
d.manage().timeouts().implicitlyWait(10,TimeUnit.MINUTES)
d.manage().timeouts().implicitlyWait(10,TimeUnit.MILLISECONDS)
d.manage().timeouts().implicitlyWait(10,TimeUnit.MICROSECONDS)
d.manage().timeouts().implicitlyWait(10,TimeUnit.HOURS)
d.manage().timeouts().implicitlyWait(10,TimeUnit.DAYS)

Explicit Wait
WebDriverWait
WebDriverWait w = new WebDriverWait(d, 10);
w.until(ExpectedConditions.elementsToBeClickable(By.Name("login");
FluentWait<WebDriver> w = new FluentWait<>(driver).withTimeout(Duration.ofSeconds(20)).
pollingEvery(Duration.ofSeconds(1)).ignoring(Throwable.class);
w.until(ExpectedConditions.alertIsPresent());
7Navigation

d.navigate().to("url") to navigate to given url


d.navigate().forward() to move to the next page
d.navigate().backward() to move to previous page
d.navigate().refresh() to refresh the current page
MAVEN
DATA DRIVEN
POM FRAMEWORK
JUNIT
TESTNG
PRIORITY
IGNORE PARTICULAR TESTCASE

INVOCATION COUNT
HARD ASSERT
SOFT ASSERT
SUITE LEVEL EXECUTION
PARAMETERS
GROUPING:
Include:
Exclude:
DATAPROVIDER:
Data provider from other class

PARALLEL EXECUTION:
Using classes

Using methods
Using test
RERUN
MANUAL RERUN

AUTOMATIC RERUN when we know which test case is getting failed


AUTOMATIC RERUN when we don’t know which test case is getting failed
Execution flow
DEPENDENCY OF TEST CASE METHOD

DEPENDENCY ON METHOD
DEPENDENCY ON GROUP
alwaysRun=true

You might also like