You are on page 1of 47

Control+click -> to get information

Constructor –

1. it is a special method which doesn’t have return type


2. its name should be exact same as class
3. its injected by jvm automatically
4. constructor can be overloaded

***what if we make private constructor?

->We can’t inherit class which has private constructor

-> With private constructor instance of class can be created inside declaring class(singleton pattern)

-> singleton class is one which limits the number of objects creation to one. Using private
constructor we can ensure that no more than one object can be created at a time. By providing
a private constructoryou prevent class instances from being created in any place other than this
very class.
->
Control+click -> to get information

Constructor –

1. it is a special method which doesn’t have return type


2. its name should be exact same as class
3. its injected by jvm automatically
4. constructor can be overloaded

***what if we make private constructor?

->We can’t inherit class which has private constructor

*The first of every constructor is 'super'.

We can call variable, method constructor using super and this keyword.

This keyword is use to call variable, method or constructor in same class.

Super keyword is use to call immediate parent constructor, method or variable

Diff between oops & java

Java won’t support oops concept 100%

1.Multiple inheritance not allowed.

2. Call by ref not present in java

Exception Handling
Exception are not compile time, its run time.
Control+click -> to get information

Constructor –

1. it is a special method which doesn’t have return type


2. its name should be exact same as class
3. its injected by jvm automatically
4. constructor can be overloaded

***what if we make private constructor?

->We can’t inherit class which has private constructor

*The first of every constructor is 'super'.

We can call variable, method constructor using super and this keyword.

This keyword is use to call variable, method or constructor in same class.

Super keyword is use to call immediate parent constructor, method or variable

Diff between oops & java

Java won’t support oops concept 100%

1.Multiple inheritance not allowed.

2. Call by ref not present in java

Exception Handling
Exception are not compile time, its run time.
Control+click -> to get information

Constructor –

1. it is a special method which doesn’t have return type


2. its name should be exact same as class
3. its injected by jvm automatically
4. constructor can be overloaded

***what if we make private constructor?

->We can’t inherit class which has private constructor

*The first of every constructor is 'super'.

We can call variable, method constructor using super and this keyword.

This keyword is use to call variable, method or constructor in same class.

Super keyword is use to call immediate parent constructor, method or variable

Diff between oops & java

Java won’t support oops concept 100%

1.Multiple inheritance not allowed.

2. Call by ref not present in java

Exception Handling
Exception are not compile time, its run time.
Control+click -> to get information

Constructor –

1. it is a special method which doesn’t have return type


2. its name should be exact same as class
3. its injected by jvm automatically
4. constructor can be overloaded

***what if we make private constructor?

->We can’t inherit class which has private constructor

*The first of every constructor is 'super'.

We can call variable, method constructor using super and this keyword.

This keyword is use to call variable, method or constructor in same class.

Super keyword is use to call immediate parent constructor, method or variable

Diff between oops & java

Java won’t support oops concept 100%

1.Multiple inheritance not allowed.

2. Call by ref not present in java

Exception Handling
Exception are not compile time, its run time.

*The first of every constructor is 'super'.

We can call variable, method constructor using super and this keyword.

This keyword is use to call variable, method or constructor in same class.

Super keyword is use to call immediate parent constructor, method or variable

Diff between oops & java

Java won’t support oops concept 100%


1.Multiple inheritance not allowed.

2. Call by ref not present in java

Exception Handling
Exception are not compile time, its run time.

What is exception in java - exception are usually are object thrown by jvm.

2 type of exception:

1. Checked exception – checked by compiler


2. Unchecked exception- Not checked by compiler.ex

Checked exception - checked by compiler


Ex.IoExcetion, noSuchmethod Exeption,sql exception
Unchecked Exception: Not Checked by compiler,arrayindexoutofbound ,arithmetic
Exception,NullPointer Exception.

Exception Handling -

1. Try-catch-finally block
2. throw keyword

Try-catch block:

try {
Code which may cause exception
}
catch (exception e){
Handling code
}

printStackTrace() - method trace the stack where it failed

try() -simply try won’t work

catch () -simply catch won’t work

Difference between catch & finally

1.Catch block execute when exception occurs

2.Finally block surely execute regardless of exception. Wrap up code will be written in finally

Structure -

Try {
//code may cause exception
} catch (exception e)
Handling code
} finally
//wrap up code
}

Try{
}catch{
Try{
}catch{
}
}

Allowed:

1.try{
}catch(){}
catch(){}
catch(){}

you can’t write try under other try block

if you write try under other try ,then only 1st try exception will work.

Throws Exception: Propagate exception: passing the exception to calling method.

Throws-send exception by method to other method and said that i am not able to handle see if you can
handle it

Throws then mention type of exception

public void m1 throws ArrayIndexOutofBondException(){

ex.

1.
public class Test1{
public void m1 throws ArrayIndexOutOfBoundException(){
int a={1,2,3,4,5};
System.out.println(a[5]);
}
}

2.
public class Test2{
public void m2 throws ArrayIndexOutOfBoundException(){
Test1 t = new Test1();
t.m1();
}
}

3.
public class Test3{
public static void main(String[] args){
test2 t2 = new test2();
try{
t2.m2();
}catch(Exception e){
Syso(exception handled);
}
}
}

Throw exception - for termination of method

Public class test1{

pubic void login(String user,String passwd){

if(user.equals("exist")&&passwd.equals("exist")){

Syso("login valid);

else{

throw new IllegalException();

}
Customised exception:

programmer designed/devloped exception

How to create exception

Create class with customized exception name

Extend your exception with exception class

ex.

public class illegalUserException extends Exception{

Collection
Array:

Homogenous in nature
Fixed in size
Array data structure
Collection framework:

Not fixed in size


Homogenius+Hetrogenius
Predefined support
Framework – collection of classes, abstract class, interface. Where operations are written in form of
methods

Collection interfaces:

 List
 Set
 Queue
 Map

List interface:
1. Duplicate allowed
2. Its variable in size
3. Insertion order preserve

Implementation classes of List interface:

ArrayList© -
 Backend stru is array.
 Duplicate allowed
 Heterogeneous
 Typecast happens automatically
 Random access possible
 Null insertion is also possible
 New capacity = initial capacity*3/2+1
Memory efficiency is more in arrayList than array
For performance wise array is better, because to add/delete element is easy in array while it take time
in arraylist.

Disadvantage:
Insertion & deletion operation are frequent then AL not preferred.
Frequent operation of reading data, AL is recommended
Constructor:
ArrayList()
ArrayList(int capacity):it will create arraylist with specific capacity
ArrayList(collection c):its will create arraylist of collection(collection of collection)

LinkList©:
Use double linklist structure
It’s recommended where frequent operations are insertion and deletion.
Not recommended where frequent operation are reading.

Constructors:
LinkedList() – creates empty linkedlist
LinkedList(collection c) – this will create a LinkedList of collection.

Vector©:V1.0 Legacy class (legacy means classes present from starting of java)
ArrayList & vector are same except1 feature that synchronized in nature.
Backend structure is array.
Variable in size.
Synchronized (Thread safe)
All methods are synchronized in vector.
Constructor:
Vector()
Vector(int)
Vector(collection)
Vector(int capacity,int incrementcapacity)

SET:
Doesn’t preserve insertion order.
Heterogeneous
Sort data in natural sorting order.
Datastrucutre is Hashtable

Set(I):
1.HashSet©
1.LinkedHashSet©
2.SortedSet(I)
1.NavigableSet(I)
2.TreeSet©

HashSet©:
It sorts data in natural sorting order.
It does not preserve insertion order.
It’s variable in size
Backed data structure is hash table (key & value pair).
Random access is not possible
Null insertion is possible,

LinkedHashSet©:
Insertion order preserve
Consistent performance
Backend data structure is hash table and doubly linked list.
Null insertion is possible
Doesn’t sort data even if data is of same type.

TreeSet©:
Sort data in natural order
Homogenous in nature (can’t add diff type of data)
Does not preserve insertion order.
Backend data structure is tree
If we tried to add heterogeneous data to tree set then will get class cast exception

Iterator:
Use cursors:
1. Iterator: iterator is used to iterate any element in collection. Its interface which has abstract
method.
Iterator itr = al.iterator();
|->interface |->method

While(itr.hasNext()){
|->return Boolean value true/false ,if its true then it will go on syso statement and
return object.if its false then it will finish while loop.
Syso(itr.next());
|->return object
}

Ex. Print collection and then add 2 in it and then print it

While(itr.hasNext()){
Int element= (int)itr.next();
Element = element+2;

Drawback:it iterate element only in forward direction.

To overcome this problem use ListIterator.

2. List Iterator(I):
Syso(“iterator for fwd direction”);
ListIterator itr = al.listIterator();
While(itr.hasNext()){
Syso(Itr.next());
}
For backward direction:
While(Itr.hasPrevious()){
Syso(itr.previous());
}

//for hashmap we need to take app keys into set and then print the value of keys
HashMap map = new HashMap();
Set allkeys = Hs.setKeys();
Iterator itr = allkeys.iterator();
While(itr.hasNext()){
Syso(map.get(Itr.next());

3. Numerator

SELENIUM
For webdriver testing: QTP, selenium webdriver, load runner
, selenium IDE

Regression testing – its part of testing, which test previous test cases to check whether new deployed
code impacted.

How to identify which test cast should be automate?


-We will automate regression testing
We will retest testing can automate
Sanity test cases
We can also automate smoke test case(find critical functionality work or not as per requirement)

Web application testing and Desktop Application testing:


QTP(quick test professions)not free,not open source
Selenium IDE:install as plugin inside Firefox browser – only for Firefox ,less programming freedom.
Selenium Webdriver(I):lots of scope of freedom,free,and open source,classes,abstract classes,Library
Selenium RC:

Selenium WebDriver:
3. Collection of interface, abstract class, classes which can be used to automate web application.
4. Selenium Automate only web application.
5. Support multiple languages like java,python,ruby,C# etc
6. It support multiple browsers
7. Third party library integration is easy and supported.
8. Platform independant

Selenium Webdriver(I) ->


FireFixDriver
InterExploredDriver
ChromeDriver
SafariDriver
iOSDriver
AndroidDriver
HtmlUnitDriver

HtmlUnitDriver:
Headless browser
Implimenettion of webdriver
Fastest & lightweight

Seleniumhq.com -for download jars

Open browser using seleniums 3.x and above


System.setproperty(webdriver.gecko.driver,” path”);
Geckodriver.exe version should be 0.18
Firefox version should be >49

For Selenium<2.49,firefox version<48


FirefoxDriver driver = new FirefoxDriver();

For Chrome - webdriver.chrome.driver


For internetExplorer – webdriver.ie.driver

Close() – close the current window

Quit() – close all windows


WebElement(I):

Methods of WebDriver(I):
<tagname attribute=”value1” attrib2=”vaalue2”>Text</name>
1. click() – click on particular webelement including button,link,radio button ,checkboxes
2. submit() – use to submit form
3. sendKeys(charSequence ..keys) –it can type in text boxes,text areas etc..
4. clear() – can be clear text area.
4. getTagName():get name of tag
5. getAttribute():use to get the attribute of specific tag mentioned as parameter
6. isSelected() : give Boolean value true or false if check boxes is present or not
7. gettext():This method can b use to get text of webelement including label,link etc
8. findElement() – return type webelement .
9. FindElements() – return type is list.

Locators in selenium:
By Claas
1. id
2. Name
3. xPath
4. css selector
5. class name
6. linkText
7. partialLinkText

Dynamic web table handling:


XPATH AXES:
xpath axes maintains Relationship between html tag
1. Parent
//<tagA>[@attrib=’value’]/parent::<tagB>[@attrib=’value] //tagB is parent of tagA
Ex./a[@target=’_balnk]/parent::li
Or
/li/a[@target=’_blank’]

2.Child :
//tagA>[@attrib=’value’]/child::<tagB>[@attrib=’value’]

Following-sibling
//ul[@class=’sub-menu collapse in’]/li[1]/following-sibling::li] //traverse all li which are present under ul
tag

For specific 2nd li –


//ul[@class=’sub-menu collapse in’]/li[1]/following-sibling::li[2]//traverse 2nd li which are present under
ul tag

Preceding-sibling:
//li[@data-target=’#security’]/preceding-sibling::li
//div[@class=’col-md-3 col-sm-4 left-menu’]/div[3]/preceding-sibling::div

Ancesester:
// div[@class=’col-md-3 col-sm-4 left-menu’]/ancestor::*

Descendant:
// div[@class=’col-md-3 col-sm-4 left-menu’]/descendant::*

Self:
//div[@class=’col-md-3 col-sm-4 left-menu’]/self::*

Ancestor-or-self:

Descendant-or-self

Waits in Selenium:Halt for sometime

(Timeout exception or NoSuchElement Exception)


1. Implicit Wait:
1. It will implicitly wait for each and every web element which is handled by webdriver instance.
2. Polling Time: its time till that time wait find element.
3. maximumOut : script will wait max time after crossed will get timeout exception
4. default polling time is 200miliseconds
5. driver.manage().timeout().implicitelywait(4,Timeout.SECONDS);
6. This operation is applicable every time when operation invoked driver instance.

2. Explicit Wait:
1. Wait only for particular element which takes little more time than other element
2. Highly customizable
3. We can ignore unwanted exception using explicit wait
4. We can wait for particular web element or its state or particular event on webpage.
5. We can specify polling time using explicit wait.
6. We can achieve explicit wait using 2 classes
WebDriverWait()
FluentWait()

WebDriverWait wait = new WebDriverWait (driver, 10, 1000);


Fluent wait have certain method, we have to call them using it we can customize it.
WebDriverWait have some constructor to call explicit wait

WINDOW HANDELING & FRAMES

Window has min max n close window.


Window is container of html DOM.
When we open browser with driver instance in its focus is on parent window.when we click on some
button or link on parent window and if a new build window is opening in this case focus will not set on
newly opened window automatically.

To set focus on newly window:


Every window which is opened by driver instance, have unique identifier and it called as window handle.
This handle is hexadecimal string

To handle windows:
 getWindowHandle() : Return type is string
-Return hexadecimal string handle of window to which web driver instance is currently pointing
 getWindowHandles() : Return type is set of strings
-Return set of window handles of windows which are open by driver instance only.

.equals method for object check hashcode


.equals method for string it check content

Frames:
Driver.switchTo.frame() //index,webelement,nameorid
Window popup – html dom,close,minimize,maximize
Pop-up – model popup div:not html dom container
Frames – inline frame

Alert –
1. Java script element or functions
2. Used to attract the focus of user towards some action
3. Its javascript function with which we can create alert – ie alert(),prompt(),confirm()
4. There is no chance of having multiple alert on same webpage at a time.

3 types of alert:
1. Simple Alert
2. Prompt alert
3. Confirmation alert
To handle alert we should use alert(I) – 2 methods for alert handling accept() & dismiss()

Simple Alert:
They have only 1 button and text
They r u se to notify about something to user
Alert alert = driver.switchTo.alert();
Alert.accept();

Prompt Alert: take input from user.


They have 2 button and 1 textbox and text
Confirmation Alert:
Will ask user to which action need to perform either ok or cancel.
Used to confirm the action which is performed by end user earlier

Accept() – Alert interface


Dismiss() – Alert interface
getText():Alert Interface
sendKeys():Alert interface
Handling mouse and keyboard events:
Press
Release
Press and hold
Press and hold multiple keys
Key combination

Mouse Event : Handle mouse and keys


Left click
Right click
Double Click
Mouse hover
Drag and drop

Robot class: its java class.Presnt in awt package


keyPress(int keyCode)
keyRelease(int keycode)
KeyEvent class which specify all the keys present on keyboard in form of static final int variable
MouseEvent class secify mouse actions in form of static final int variable
Robot rob = new Robot();
Rob.keyPress(KeyEvent VK_TAB)
Rob.keyRelease(KEyEvent VK_TAB)

Action class:keyboard n mouse event .we can mouse hover,right click ,left click
We can press only shift ,ALT,cntrl key through action class.if we try to press any other class then we wll
get illegalArgumentException

moveToELement() – mouse hover.


contextClick() – for right click
perform() – perform action that we want to execute.if u don’t fire perform() method then
mouse/keyboard events will not happen

Actions action = new Actions();


action.moveToElment()
ae.build()
ae.perform()
For colour change of login to netbanking button to green:

For scrolling window down:

For up –
Js.executeAsyncScript(“window.scrollby(0,-100)”)

Select class:

1.use to select option from dropdown.


2.Select boxes are designed by select tag using html.
3.Every option tag will have value attribute.
4.It is designed to handle dropdown

Methods:
SelectByIndex()
SelectByValue()
SelectByVisibleText()

To Deselect the element:this method we can use when it will allow multiple select option,it will not
work for single option.
1. DeselectbyIndex()
2. DeselectByValue()
3. DeselectByvisibleText()

getOptions() –
1.list of web element
2.this list contains all the options available in dropdown.

CSS Selector:

Cascade style sheet.


How to launch browser without using exe.

Required Jar files:


1.WebDriverManager library
2.slf4j
WebDriverManager.chromedriver.setup();
Webdriver driver = new ChromeDriver();

Taking Screenshot using selenium:

1.Using robot class:


2.Using TakeScreenShot interface:

TakeScreenShot scrShot = (TakeScreenShot)driver;


File src = scrShot.getScreenShotAs(OutputType.FILE);
FileUtils.copyFile (src, new File (“screenshot/test.jpg”));

Using AShot library:


Take screenshot of entire page
AShot as = new AShot();
ScreenShot sc = as.takesScreenShot(driver);
ImageIO.write(sc.getImage(),”png”,new File(“D:/naukri.png”);

For entire Page:


AShot as = new AShot();
ScreenShot sc = As.shootingStrategy(ShootingStrategies.viewportPasting(1000)).takeScreenShot(driver);
ImageIO.write(sc.getImage(),”JPG”,new File(“screenshot/fullpage.jpg”);

If want to exclude particular part or button use below code:


TESTNG :
Manage test cases,test,suites
Generate report
Choice of execution
Dont have main method
Single point of contact
It can create dependency between test method.

Annotation: In term of java, written on method level n class level.

@Test – method with this annotation is consider as test case.


If we applied @Test to class then all method inside class treated as test cases

ANNOTATION:
1.@Test:
Method with this annotation known as as test case.
Method level and class level.
2.@beforeTest:
Method with this annotation will be executed exactly before <test> tag of testing.xml
Method level annotation
3.@AfterTest
Executed after only <test> tag of testing.xml
Method level annotation.
4.BeforeSuite():
Method will execute just before suite tag of testing.xml
Method level annotaton.
5.AfterSuite:
Method execute just after suite tag of testing.xml
Method level annotation
6.@Beforemethod:
Execute just before each and every test method
Method level
7.@AfterMethod:
method with this annotation execute after test annotated tag

DataProvider():
For data driver testing
In 1 class,we can have multiple dataPrivder()
Its method level annotation
Method with this annotation Provide data to test case as per choice.
@BeforeClass:excute before each and every<class> tag presnt in testing.xml
@AfterClass:execute after <class> tag present in testing.xml

@Parameter:method with this annotation will accept parameter from testing.xml file.
Method level
@Parameters({“rollNumber”})
@Test
Parameters of @Test annotation:
invocation count – how much time test case will be executed.
@Test(invocationCount=3)

invocationTimeout:
@Test (invocationTimeout=1000) -> it will 1000 mili sec for execute

@expected Exception – what kind of exception ur method may throw

Thread Pool Size = how many threads are invoke during test case

Single Threaded – only 1 thread can access

description – description of test case


@dataProvider :
@dataprovider annotation with name attributes
Return object []/object [][] array
Dataprovider method should be written n maintain in separate diff class

Public class Test{


@Test(dataProvider=”LoginDataProvider”,dataProviderClass=dataProviders.class)
Public void m1(String uname,String pass) throws InvalidUserexception {
If(uname.contains(“user”)&&pass.contains(pass)){
Syso(uname+”\t”+pass)
}else
Throw new ArithmeticException();
}}

@dataprovider(name=”LoginDataProvider”)
Public object[][] loginData(){
Object[][] values={{“user1”,”pass1”},{“user2”,”pass2”},{“user3”,”pass3”}}
Return value;
Read test data from excel sheet and providing case by mean of data provider

Reading excelsheet:
.xls
.xlsx

3rd party lib to handle excel sheet:


1.JXL(javaexcel)
2.Apache poi

Diff between jxl & POI


Classes of jxl:
1.Workbook- abstract class of jxl
2.Sheet (I)

fileInputStream fis = new FileInputStream(“d://abc.xls”);


WorkBook book = Workbook.getWorkbook(fis);
Sheet sheet = book.getSheet();
Int lastRow = sheet.getRows();
Int lastCol = sheet.getColumn();
For(int i=0;i<=lastRow;i++){
For(int j=0;j<=lastCol;j++){
Syso(sheet.getCells(j,i).getContent());
}}
APACHE POI :
HSSFworkbook
XSSFworkbook

Groups:
If want to exclude particular group
Listener:

ITestListener(I)
1. onStart() – executed before each <test> tag of testing.xml
2. OnFinish() – executed after <test> tag of testing.xml
3. OnTestSuccess() –invoked after passing each test cases mentioned in class or
testing.xml
4. onTestfailure() – invoke after failure of test case mentioned in class.
5. onTesttStart() – invoked before every invocation of every test case
6. OnFailedButWithSuccessPercentage() – invoke after failing a test case if it is in success
percentage
7. OnTestSkipped() – invoked after test case is skipped.

How to implement and execute listener:


Create simple java class which implement iTestListener
Implement the method of iTestListener as per requirement.

How to execute:
From test case class
FRAMEWORK:
POM:
Operations and elements of particular page in one java class

PageFactory class:
ClassA a = new ClassA();
Lazy proxy for every webelement
Reflection API:

Reflection is use to create image of any class,so that we can get detailed info about class,like method
haing body,no of abstract method,constructor,return type of any mrthod,Access modifier

Return type of reflection is “class” class


forName()

getClass
class Reflection=new Demo.getClass();
the .class syntax
class Reflection=demo.class;

for methods:
For field:

AUTOIT
ControlFocus("Open","","Edit1")
ControlSetText("Open","","Edit1","D:\puja\flat_pics\IMG_0049.JPG")
ControlClick("Open","","Button1")

You might also like