Full Compilation
Full Compilation
=====================
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.
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.
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
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.
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.
void add(); //All the methods inside interface will have 'public abstract'
by default,so no need to mention.
}
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;
@Override
System.out.println(123);
}
public static void main(String[] args) {
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.
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)
Static method:
If u specify a method as static, we need not create object for calling the
methods.
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)
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.
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?
CONSTRUCTOR:
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.
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
Exception handling:
try block:
The code which is expected to throw exceptions is placed in the try block.
Catch block:
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.
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: -
To configure Driver:
Create new project → Right click → New → New folder {copy driver file}
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
package org.day.one;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
}
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:
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;
System.setProperty("webdriver.chrome.driver", "C:\\Users\\Azar. A.
R\\eclipse-workspace\\SDay2\\driver\\chromedriver.exe");
driver.get("https://www.facebook.com/");
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.
Declare Actions
Actions a = new Actions(WebDriver ref name);
Methods in Action
The menu list disappears within the fractions of seconds before Selenium identify the next
submenu item and perform click action on it.
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
To implement JavaScript
1. Type casting
JavaScriptExecutor js = ( JavaScriptExecutor ) WebdriverRef.Name
2. Use methods in JavaScript
Methods of JavaScript
JavaScript Codes
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 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
tr - table row
th - table heading
td - table data
Example:
CSS VALUE
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
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.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");
JavaScriptExecutor js = (JavaScriptExecutor)d
TakesScreenshot ts=(TakesScreenshot) d;
ts.getScreenshotAs(OutputType.FILE) File to take screen short and return file directiry stored
d.switchTo().frame()
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
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
DEPENDENCY ON METHOD
DEPENDENCY ON GROUP
alwaysRun=true