Java Basics for selenium

Jan. 10, 2014

More Related Content


Java Basics for selenium

  1. 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.
  2. 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.
  3. 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.
  4. Components 1)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.
  5. 4)Selenium Web Driver: Selenium WebDriver was developed to support dynamic web pages where elements of a page keep changing. 5)Frameworks with real time applications: Linear Automation Framework. Function Driven ,Data driven, Module driven Framework.
  6. Why java for selenium • Selenium is platform independent • Java is also platform independent
  7. 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
  8. • • • • • • • • • • • Features of java Simple Secure Portable Object oriented Robust Multithreaded Architecture neutral Interpreted High performance Distributed dynamic
  9. OOP Principles • • • • Data Abstraction Encapsulation Polymorphism Inheritance
  10. 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.
  11. 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.
  12. 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.
  13. 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
  14. 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…..
  15. Program made up of • Program made of 1.Keywords 2.Identifiers 3.Literals Ex: Int EmpId =10310; Int = keyword EmpId =identifier 10310 =literal
  16. • • • • • • • • • • Strurture of java program //documentation section //package section //import section //class section { Variables Methods } Comments // for single line comment Multiline comment /*-------*/
  17. 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.
  18. 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
  19. 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 name 3.Inside class body we can develop any java script Main method is mandatory to start the execution 4.Java file is compiled using a command javac
  20. Note contd…. 5.compiler generates .class file if there are no errors default .class file will be saved in same location where java file is saved 7.every statement in java must be terminated by ; 8.The java class can be executed by using a cmd java ClassName 9.When ever a class is executed java starts the execution by running main method 10.Java executes all the statements sequentially of main method 11.Java throws error if main method is not defined .
  21. 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
  22. • String class We can store String data in 3 ways 1.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”);
  23. 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 }
  24. 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
  25. loops • • • • Java’s iteration statements are For While Do-while
  26. 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.
  27. 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];
  28. 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];
  29. 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.
  30. 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.
  31. 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.
  32. 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
  33. EX public 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 } }
  34. 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); } }
  35. 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 .
  36. Static Function public 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 )); } }
  37. 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 )); } }
  38. 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.
  39. v)all static members of class reside in an area called static pool vi)java calls main methods for execution vii)main method enters into stack on top of java viii)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 memory xiii)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.
  40. 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 references String Str1=new String(“Java”); String Str2=Str1;
  41. 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.
  42. 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
  43. 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.
  44. 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
  45. Super keyword • Using super keyword • We can call immediate super class instance variable.
  46. this 1.this keyword can be used to refer current class instance variable. 2.this() can be used to invoke current class constructor 3.this keyword can be used to invoke current class method (implicitly). 4.this can be passed as an argument in the method call 5.this can be passed as argument in the constructor call 6.this keyword can also be used to return the class instance. 7.We cannot use this and super at a time
  47. 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)
  48. 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.
  49. 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.
  50. Types of inheritance • • • • There are 3 types of inheritance Single Circular(no prg supports ) Multiple (java does not support) a A B b B A c C
  51. Interface • Java supports 3 different structures 1. Fully implemented 2. Fully unimplemented 3. 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
  52. 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.
  53. 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
  54. 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”
  55. 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.
  56. 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 .
  57. 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
  58. Packages • Java Package is a mechanism for organizing Java classes in to a namespace. • Classes present in the package can access the each 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.
  59. 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.
  60. 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.
  61. 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
  62. contd Types of Exception 1)Checked Exception: A checked exception is an exception that is typically a user error or a problem that cannot be foreseen by the programmer. EX: If a file is to be opened, but the file cannot be found, an exception occurs 2)A runtime exception is an exception that occurs that probably could have been avoided by the programmer. EX:ArrayIndexOutOfBoundException 3)Error describes internal error and resource exhaustion. Mostly beyond the programmers control.
  63. 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
  64. Keywords of Exception • • • • • Try Catch Throw Throws finally
  65. 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){ }
  66. 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 }
  67. 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 .
  68. 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;
  69. 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).
  70. 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)
  71. 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()
  72. 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.
  73. Reflection API

Editor's Notes

  1. If you feel that a method doesn&apos;t know how to handle a particular error, you can throw an exception from the method and let someone else deal with it. If you throw a &quot;checked&quot; exception, you enlist the help of the Java compiler to force client programmers to deal with the potential exception, either by catching it or declaring it in the throws clause of their methods.