java basics for selenium

73
Why Automation? Test Automation->A software tool to run test cases repeatedly against the application. To check the correct whether the application is behaving as expected or not. EX: Regression Testing. Test Automation Supports: Regression testing. Finding defects missed by manual testing Disciplined documentation of test cases.

Upload: apoorvams

Post on 19-May-2015

5.934 views

Category:

Education


3 download

DESCRIPTION

Selenium component overview with detailed concepts on java

TRANSCRIPT

Page 1: Java Basics for selenium

Why Automation?

Test Automation->A software tool to run test cases repeatedly against the application.

To check the correct whether the application is behaving as expected or not.

EX: Regression Testing.Test Automation Supports:Regression testing.Finding defects missed by manual testing Disciplined documentation of test cases.

Page 2: Java Basics for selenium

When not to automate?

• We should not use the automation tool when the UI or web application behavoiur keeps changing like when the application behaviour is not stable.

• If an application has a very tight deadline, there is currently no test automation available.

Page 3: Java Basics for selenium

Selenium Overview

• Selenium is a portable software testing framework for web applications.

• Selenium provides a record/playback tool for authoring tests without learning a test scripting language(Selenium IDE)

• Selenium provides a domain specific language i.e, tests can be written in any language like java, c#...

• Selenium can be deployed on any platform.

Page 4: Java Basics for selenium

Components1)Selenium IDE is a complete integrated development

environment (IDE) for Selenium tests. • It is implemented as a Firefox extension• It allows recording, editing, and debugging tests.2)Selenium RC: RC makes it possible to write

automated tests for a web application in any programming language.

3)Junit: it is a unit testing framework for java where it promotes “First testing then coding” using annotations and assertions.

3)TestNG:It is testing framework which covers all categories of testing requires JDK5 or higher.

Page 5: Java Basics for selenium

4)Selenium Web Driver: Selenium WebDriver wasdeveloped to support dynamic web pageswhere elements of a page keep changing.5)Frameworks with real time applications:Linear Automation Framework.Function Driven ,Data driven, Module drivenFramework.

Page 6: Java Basics for selenium

Why java for selenium

• Selenium is platform independent• Java is also platform independent

Page 7: Java Basics for selenium

Installing java and eclipse

->Go to selenium software's folder->java software’s folder->double click .Check in c drive->Java-> jre6, jre1.5.0_12

Jre=java run time environment(it has supporting files to run java)Jde=java development kit(it has code)

-> selenium software’s folder->eclipse->click on round purple color eclipse icon or create short cut for it on desktop

Page 8: Java Basics for selenium

Features of java• Simple• Secure• Portable• Object oriented• Robust• Multithreaded• Architecture neutral• Interpreted• High performance• Distributed• dynamic

Page 9: Java Basics for selenium

OOP Principles

• Data Abstraction• Encapsulation• Polymorphism• Inheritance

Page 10: Java Basics for selenium

Data abstraction• Abstraction involves extracting only relevant information .• In other words, Abstraction means “looking for what you want “ in an object or a

class • Ex: An Automobile salesperson is aware that different people have different

preferences.some people are interested in the speed of car, some in the engine, some in style.although all of them want to buy a car, each of them is interested in a specific attribute or feature.

• Sales man knows all the details of a car, but he presents only the relevant information to a potential customer.As a result, the sales man practices abstraction and presents only relevant details to customer.

Page 11: Java Basics for selenium

Encapsulation • Encapsulation literally means “to enclose in or as if in a

capsule”.• Encapsulation is defined as the process of enclosing one or

more items with in a physical or logical section.• It involves preventing access to non essential details• Ex:when u plug in the cord of the vaccum cleaner and turn on

the switch, the vaccum cleaner starts.we do not see the complex process needed to actually convert electricity into suction power.

• In other words,the exact working of the cleaner has been encapsulated.

• Therefore encapsulation is also defined as information hiding or data hiding because it involves hiding many of the important details of an object from the user.

Page 12: Java Basics for selenium

polymorphism

• It is the ability that helps in executing different operations in response to the same message.

• We can implement polymorphism by creating more than one function with in a function within a class that have the same name.

• The difference in the functions lies in the number and types of parameters passed to each function.

Page 13: Java Basics for selenium

Inheritance

• Deriving the properties from parent to child is inheritance

• with parent reference ,we can access child class methods

• With child reference, we cannot access parent class methods

Page 14: Java Basics for selenium

Concept of class and object

• Class is collection of properties and methods• Object is the instance of class• Ex of class =car• Properties=colour,power,speed,model,height• Methods=fwd(),bkd(),stop(),start()• Ex of object= honda car , toyota car…..

Page 15: Java Basics for selenium

Program made up of

• Program made of 1.Keywords2.Identifiers3.LiteralsEx: Int EmpId =10310; Int = keyword EmpId =identifier 10310 =literal

Page 16: Java Basics for selenium

Strurture of java program• //documentation section• //package section• //import section• //class section• {• Variables• Methods• }• Comments // for single line comment• Multiline comment /*-------*/

Page 17: Java Basics for selenium

Platform independence• The output of java compiler is not executable

code. rather it is byte code.• Byte code is highly optimized set of

instructions designed to be executed by java run time system, which is called java virtual machine.

• Translating a java program into byte code helps makes it easier to run a program in a wide variety of environments. Only the JVM needs to be implemented for each platform.

Page 18: Java Basics for selenium

Explanation of structure• To tell about the program like when, who, what, why• Package is like a folder,folder contain any thing but package contains all

related classes• We use “ Package” keyword to specify it is package ex: Package pk.sub• In a class only one package is created; multiline packages cannot be

created• Package will be the first line in program.• By default “Java.lang “Package is imported• Import java.lang.*; all methods are available in program; but not included.• We can import many packages in one class• Class is a user defined method ;it is collection of variables and methods.• At least one class must be created in a program;program can contain

many classes• Program name can be any thing but extension must be .java• Program name need not be same as class name • .class file is created same as class name

Page 19: Java Basics for selenium

note

1.Every java program should have class definition block

class ClassName { body }2.While saving a java program the file name should

be same as class name3.Inside class body we can develop any java script Main method is mandatory to start the execution4.Java file is compiled using a command javac

Page 20: Java Basics for selenium

Note contd….5.compiler generates .class file if there are no errors6.by default .class file will be saved in same location where

java file is saved7.every statement in java must be terminated by ;8.The java class can be executed by using a cmd java

ClassName9.When ever a class is executed java starts the execution

by running main method10.Java executes all the statements sequentially of main

method 11.Java throws error if main method is not defined .

Page 21: Java Basics for selenium

Datatypes in java• Java support 8 different types of datatypes under 4 families:• Integer : 1.Byte 2.Short 3.Int 4.Long• Real: float ,Double• Char: char• Boolean: boolean• Length of datatypes• 1byte – 8 bits =(-2^7 to (2^7-1)= -128 to +127• short -2bytes=16bits=(-2^15 to +(2^15-1))• Int -4 bytes = 32 bits=(-2^31 to (2^31-1))• Long -8 bytes=64 bits=(-2^63 to (2^63-1))• Float -4 bytes• Double - 8 bytes• Char – 2 bytes• Boolean -1 byte• Default values for datatypes:• Integer =0,char=space ,boolean = false,real=0.0

Page 22: Java Basics for selenium

String class• We can store String data in 3 ways1.charArray Char name[]={‘o’,’n’,’e’,’f’,’o’,’r’,’c’,’e’}2.String class object String name =“oneforce”; or String name= new String(“oneforce”); name = name.concat(“jayanagar”);

3.String Buffer class StringBuffer sb =new StringBuffer(“oneforce”); Sb.append(“jayanagar”);

Page 23: Java Basics for selenium

Conditional and concatenation operator

• If(condition){ statment1;}• If-else• If (condition){stat1}else{stat2;}• If(condition){stat1}-else if(condition){stat2}• Switch statement allows a variable to be tested

for equality against a list of values.switch(expression){case value1 : //Statements break; default : //Statements }

Page 24: Java Basics for selenium

Concatenation operator

• public class concatenation {• public static void main(String[] args)• {• int a=10;• int b=20;• String str1="Hello";• String str2="world";• System.out.println(str1+str2);• System.out.println(str1+str2+a+b);• System.out.println(a+b);• System.out.println("sum of two numbers :"+(a+b));

• }• }• //for numbers + symbol acts as arthemetic operator• //for non numerics +symbol acts as concatenation operator

Page 25: Java Basics for selenium

loops

• Java’s iteration statements are • For• While• Do-while

Page 26: Java Basics for selenium

Arrays

• Grouping the data objects of same type in a contiguous block of memory.

• Array is an object created with new operator.• Array index starts with zero.• Array size cannot be resized.

Page 27: Java Basics for selenium

Array Declaration and Instantiation-> Array Declaration:<Data type> [ ]<array name >Ex: int[] myArray;

-> Constructing an Array:<array name > = new<data type> <array Size >myArray=new int[5];

Page 28: Java Basics for selenium

Initialization of Array

-> Primitive Array:Int[] myArray={1,2,3,4,5}-> Explicit initialization:MyArray[0]=10;MyArray[1]=20;Two dimensional Array:int sample[][] = new int[3][3];

Page 29: Java Basics for selenium

Drawbacks of Array

• Large arrays take up space.• Arrays can hold only one data type at a

time.• Searching and sorting arrays is difficult.• Inserting and removing data from arrays

is clumsy.

Page 30: Java Basics for selenium

Local Variables

Local variable are variables defined inside methods, constructors or blocks.The variable will be declared and initialized within the method and the variable will be destroyed when the method has completed.

Page 31: Java Basics for selenium

Global variable• Global variables are declared in a class, but outside

a method, constructor or any block.

• Global variables can be accessed any where in the class ,methods defined in the class.

Page 32: Java Basics for selenium

Static and Non Static Variables-> Static variables are declared with

the static keyword in a class, but outside a method, constructor or a block.

->A single copy will be maintained irrespective of number of objects.

• Static variables can be accessed by calling:• With classname• Without object

-> NonStatic variables are can be accessed by object.-> It can have multiple copies as much as object

creation for class

Page 33: Java Basics for selenium

EXpublic class Test { static int a= 6 ; int b= 8; public static void main(String[] args) { Test obj1=new Test(); Test obj2=new Test(); obj1.a=10; obj2.a=12; obj1.b=24; obj2.b=3 6 ; System.out.println("Static a“ + obj1.a); //12 System.out.println("Static a“ + obj2.a); //12 System.out.println("Static a“ +a); //12 System.out.println("Static b “ + obj1.b); //24 System.out.println("Static b “ +obj2.b); //36 }}

Page 34: Java Basics for selenium

Static variable Example

public class Statvariable {private static int salary;

public static void main(String args[]){//classname.salary

salary = 1000;System.out.println("salary: is “ +salary);

}}

Page 35: Java Basics for selenium

Static and Non Static Functions

-> Static Functions belongs to the class and can be accessed by the main method directly and also by the object creation or by class name.

-> A static method can access only static members

-> Non Static Functions belongs to the object of Class and can only be accessed by object .

Page 36: Java Basics for selenium

Static Functionpublic class A { static int add(int i,int j) { return( I + j); }}

public class B extends A { public static void main(String args[]) { int s= 9; System.out.println(add(s, 6 )); }}

Page 37: Java Basics for selenium

Non Static Function

ppublic class A { int add(int i,int j) { return( I + j); }}public class B extends A { public static void main(String args[]) {B b =new B(); int s= 9 ; System.out.println(b.add(s, 6 )); }}

Page 38: Java Basics for selenium

Static/NonStatic members works

when ever a java program is executed .....the following steps happen

i)memory is allotted for execution ii)and this memory is divided into heap and

stack iii)java enter into stack and calls class loader iv)the class loader loads static members of

class into heap memory.

Page 39: Java Basics for selenium

v)all static members of class reside in an area called static poolvi)java calls main methods for executionvii)main method enters into stack on top of javaviii)when ever a object creation statement encounters , object will get created into heap.ix)on that time, the non static members of the class will be loaded into object.x)we can create multiple objects of a class .for each object creation a copy of non static members will be loaded.xi)after the completion of main method , the JVM calls garbage collection to clean the heap.xii)After that java releases the memory back to main memoryxiii)local variables are created in the stack and the life of the variable is as long as the method is in the stack.java gives preferences to local variables.xiv)if any object does not have a reference then such object are known as abundant object.

Page 40: Java Basics for selenium

Object and Object References• Object is the instance of class.• Object Reference is the information on how to find

the object.• A Single object can have more than 1 object

references.EX : 2 objects[java,C+ +)] 2 reference

objects(Str1,Srtr2).String Str1=new String(“Java”);String Str2=new String(“C+ + “);EX : 1 object with 2 object referencesString Str1=new String(“Java”);String Str2=Str1;

Page 41: Java Basics for selenium

Call By Value

• Passing a value held in the variable as an argument to the method.

• The value is copied to method parameters and changes takes place to that parameters.

• That is why changes made to the variable within the method had no effect on the variable that was passed.

Page 42: Java Basics for selenium

Call By Reference

• The Object is passed as an argument to the method.

• No copy of object is made here.• Changes made in the method will be reflected

in the original object

Page 43: Java Basics for selenium

constructors• It can be tedious to initialize all of the variables in a class each

time an instance is created.• it would be simpler and more concise to have all of the setup

done at the time the object is first created.• Java allows objects to initialize themselves when they are

created. This automatic initialization is performed through the use of a constructor.

• Constructor is a special block in java class invoked at the time of object creation

• Constructor should always be public• A constructor name is same as class name ,the constructor

should not have return type and return statement• Whenever we create an object , the constructor body will get

executed.

Page 44: Java Basics for selenium

Difference between constructor and method

Method• Method can be executed

when we explicitly call it.• Method name will not have

same name as class name• Method should have return

type • A method can be executed

n number of times on a object

constructor• Constructor gets executed

only when object is created• Constructor name will be

same as class name• Constructor should not

have return type • Constructor will get

executed only once per object

Page 45: Java Basics for selenium

Super keyword

• Using super keyword• We can call immediate super class instance

variable.

Page 46: Java Basics for selenium

this

1.this keyword can be used to refer current class instance variable.

2.this() can be used to invoke current class constructor3.this keyword can be used to invoke current class method

(implicitly).4.this can be passed as an argument in the method call5.this can be passed as argument in the constructor call6.this keyword can also be used to return the class instance.7.We cannot use this and super at a time

Page 47: Java Basics for selenium

final

• Final is the keyword to avoid inheritance• We use final in three ways 1.Before a variable(you can’t change)2.Before a method (you can’t over ride)3.Before a class(you can’t inherit)

Page 48: Java Basics for selenium

Inheritance • Deriving members of one class to another class is known as inheritance.• The class from where member s are inherited are known a super class or

base class• The class to which members are inherited are known as subclass or

derived class• The general syntax to write inheritance class• Class SubClassName extends SuperClassName• Using extends keyword a class can inherit from super class• Always inheritance happens from super class to subclass.• Static members of the super class will not be inherited to subclass

because the static members will not be loaded into object memory• Whenever an object of subclass is created both super class member and

sub class member will be loaded into object• Inheritance happens through constructor chain.

Page 49: Java Basics for selenium

Inheritance contd…

• Whenever an object of sub class is created ,the subclass constructor calls super class constructor ,the super class constructor calls its super class constructor . this is known as constructor chain.

Page 50: Java Basics for selenium

Types of inheritance

• There are 3 types of inheritance• Single • Circular(no prg supports )• Multiple (java does not support)

A

B

a

b c

A B

C

Page 51: Java Basics for selenium

Interface • Java supports 3 different structures1. Fully implemented 2. Fully unimplemented3. Partly implemented/unimplemented• Interface contains abstract methods(with no body)• Interface is an fully unimplemented structure• We need to provide body for all methods in interface• In interface, we cannot create the object of interface• Can contain constants, but not variables• All methods, variables are public static final

Page 52: Java Basics for selenium

Interface

• It is a class with no implemented methods• Interface must not be static• It contains only declarations• Methods in interface must be static • All variables must be assigned a value• Interface variables are static ;we cannot change values• Interface methods are neither static nor non static• Creating interface reference ,we can access implemented

class methods which are defined in interface class but not methods defined in implemented class.

Page 53: Java Basics for selenium

Abstract class

• It is partly unimplemented or partly implemented class which contains zero or more abstract methods

• Concrete method is the method with body• Abstract method is the method with out body• If user want to inherit the abstract class;he

need to extend but not implement

Page 54: Java Basics for selenium

Difference between interface and abstract class

interface• Fully unimplemented

structure that contains all abstract metods

• Interface contains only constants

• The object of interface can’t be created directly ,anomous class is recquired to create object for this class

• Uses “implements “

Abstract class• Partly implemented or

unimplemented structure• Can contain variables• Can contain constructors• Abstract class object get

created automatically when sub class object got created

• Uses “extends”

Page 55: Java Basics for selenium

Overloading and over riding methods

• Redefining method of parent class with the same name in child class is method over riding

• Redefining same method with different parameters is called method overloading

• Note:1.Reference type determines which overloaded

method is used at compile time.2.Object type determines which over riden

method is used at runtime.

Page 56: Java Basics for selenium

Over loading • Overloading is about creating multiple methods with the

same name, but different signatures, in the same scope. • overloading can take place in the same class or in the

subclass.• overloaded methods MUST have a different argument

list.• overloaded methods MAY change the return type (in

case argument list is different).• overloaded methods MAY change the access modifier.• reference type determines which overloaded method

will be used at compile time.• constructors MAY be overloaded .

Page 57: Java Basics for selenium

Over Riding • Overriding is about changing the behavior of a certain method in

the child class from the way it is behaving in the parent class.• Applies ONLY to inherited methods• is related to polymorphism• object type (NOT reference variable type) determines which over

riden method will be used at runtime• overriding method MUST have the same argument list (if not, it

might be a case of overloading)• Abstract methods MUST be overridden• Final methods CANNOT be overridden• Static methods CANNOT be overridden• Constructors CANNOT be overridden

Page 58: Java Basics for selenium

Packages• Java Package is a mechanism for organizing Java

classes in to a namespace.• Classes present in the package can access theeach others class members.• We are going to import classes from the package.• Package name usually starts with lower case.• Classes within a package can access classes and

members declared with default access and class members declared with the protected.

Page 59: Java Basics for selenium

Access Control Modifiers

Java provides a number of access modifiers to set access levels for classes, variables, methods and constructors. The four access levels are:

• Default:-Visible to the package. No modifiers are needed.

• Private:-Visible to the class only .• Public:-Visible to the world.• Protected:-Visible to the package and all

subclasses.

Page 60: Java Basics for selenium

Non Access Modifiers

Java provides a number of non-access modifiers to achieve many other functionality.

• The static modifier for creating class methods and variables

• The final modifier for finalizing the implementations of classes, methods, and variables.

• The abstract modifier for creating abstract classes and methods.

• The synchronized and volatile modifiers, which are used for threads.

Page 61: Java Basics for selenium

Exception Handling->Exception is an Event which halts normal execution

abruptly and alternatively the program will be terminated.

• Exception occurs when our code asks JVM to do technically impossible tasks.

• Ex:Divide by Zero.• All Exception classes are subclasses of Throwable.• Throwable has two subclass :Exception and Error

Page 62: Java Basics for selenium

contdTypes of Exception1)Checked Exception: A checked exception is an exceptionthat is typically a user error or a problem that cannotbe foreseen by the programmer. EX: If a file is to be opened, but the file cannot be found, an

exception occurs2)A runtime exception is an exception that occurs thatprobably could have been avoided by the programmer.EX:ArrayIndexOutOfBoundException

3)Error describes internal error and resource exhaustion.Mostly beyond the programmers control.

Page 63: Java Basics for selenium

Exception Handling

1. Anticipate the error by the user/system.

2. Return the program to a safe state that enables the

user to execute other commands.

3. Inform the user of the error’s cause.

4. Allow the user to save work and terminate the

program gracefully.

63

Page 64: Java Basics for selenium

Keywords of Exception

• Try• Catch• Throw• Throws• finally

Page 65: Java Basics for selenium

Try-Catch block

• In this mechanism Try block will contain the code which may throw the exception.

• Catch block will declare the type of exception occurred.

• EX:try{ } catch(Exception E){ }

Page 66: Java Basics for selenium

Throws-Throws

• If a method does not handle a checked exception, throws keyword should be used at the end of a method's signature.

• To explicitly throw the exception of a newly instantiated one or an exception that you just caught, we use Throw keyword.

• EX: public void deposit(double amount) throws RemoteException { // Method implementation throw new RemoteException(); } //Remainder of class definition }

Page 67: Java Basics for selenium

Finally

• The finally keyword is used to create a block of code that follows a try block. A finally block of code always executes, whether or not an exception has occurred.

• A finally block appears at the end of the catch blocks .

Page 68: Java Basics for selenium

Collections

• Collection is a set containing the classes and interfaces which implements reusable data structures like List,Array,HashTable.

• There are so many interfaces available like java.util.ArrayList; java.util.Iterator; java.util.List; java.util.ListIterator;

Page 69: Java Basics for selenium

Array List

1)We are Creating the ArrayList as ArrayList<String> list = newArrayList<String>();2)To add elements to the list is list.add("A");List.add(2,”S”);//index=2 3)To get the element from list list.get(index).

Page 70: Java Basics for selenium

stack

• Stack is a subclass of Vector that implements a standard last-in, first-out stack.

• boolean empty() • Object peek( )• Object pop( )• Object push(Object element)• int search(Object element)

Page 71: Java Basics for selenium

HashTable

• The java.util.Hashtable class implements a hashtable, which maps keys to values.

• Hash function will compute unique value as a index to the key.

• Methods are:• Set<Map.Entry<K,V>> entrySet()• Collection<String> collection =ht.values();• Set<String> set1 =ht.keySet()

Page 72: Java Basics for selenium

Linked HashSet

• Linked HashSet maintains a list of the entries in the set, in the order in which they were inserted. This allows insertion-order iteration over the set.

• The values will be retrieved in same order of insertion using iterator.

Page 73: Java Basics for selenium

Reflection API