1 |
JDK |
Java Development Kit |
JDK = Compiler + JVM + JRE > Java Virtual Machine, Java Runtime Environment. |
Compiler compiles source code to Byte code, JVM execute Byte code and convert it to Binary code. JVM responsible for running Java application. JRE is a collection of tools that run Java application. |
Jdk is owned by Oracle, Stable version is 8, can use 11. |
Open Jdk is like corretto 1.8, some Third Party organization like amazon who derived their Jdk from Oracle version and further support and maintained it. For Example : JDK Corretto 1.8 is useful to run uiautomatorviewer |
Core Java vs Java Standard Edition > Core Java is the standard edition from which other editions are derived, So both are same. |
Install Jdk | ||||
2 |
Computer Architecture Languages |
High Level Language |
Human Understandable |
Is more english like language | ||||||||
Low Level Language |
M/c Understandable |
Is a language in binary numbers | ||||||||||
3 |
Java Files |
.java file in which High level code written |
compiled by compiler to .class file which have byte code |
class loader is Java internal API which upload .class file to JVM (Java virtual Machine), JVM on the target machine will convert this byte code to machine understandable binary code and executes it. |
JVM then pass on instructions to Interpreter for Mac, Windows or Linux which then show result on output console. Interpreter is from OS side | |||||||
.class file created in same folder if created by terminal or .class file created in bin folder if created by eclipse | ||||||||||||
In Eclipse, .class file can be seen by Navigator view under Window Menu which is deprecadted now | ||||||||||||
4 |
Maven |
online repository for dependencies |
Download jar files automatically in Project |
Download and unzip it in any folder. Stable version 3.6.3 | ||||||||
5 |
Environment Variables |
System Variables are available to all Users. It is at OS Level |
are in the form of KEY and VALUE pair. |
“Path =” This key already defined in OS (in-built variable) and value given against this key is understood by OS > executables or batch files values given against this key |
Such as here for Java, path is to given upto bin folder where all executables files are present |
JAVA & JAVA_HOME are two different variables | ||||||
3rd Party varaibles are available to all Users. It is at OS Level |
3rd Party variables are set to make connections between system softwares & applications |
Third Party Variabales are like “JAVA_HOME “. These variables name are standard and can be used by third party applications or other applications installed in the OS |
Such as here for JAVA_HOME, path is to given upto jdk folder where all files are present |
Set MAVEN_HOME too by path upto Maven Folder/bin on Hard Disk | ||||||||
User varaibles are avaible specifically for that user who is logged in | ||||||||||||
6 |
Integrated Development Environment (IDE) |
Code Editor Which integrates with JDK + Maven + Others |
Eclipse > |
Download from packages and unzip it: Eclipse IDE for Java Developers | ||||||||
Set Jdk path in Eclipse > |
Eclipse > Window > Preferences > Java > Installed JRE > Add > Std JVM > Select jdk folder from SSD > finish | |||||||||||
Java library > contains all jar files of JRE framework |
rt.jar > |
Its contains all compiled class files for the Core java and bootstrap classes which required during runtime. These classes comprise of Java platform Core API | ||||||||||
Java perspective (Right icon with J letter) & Open Perspective icons at top right corner of Eclipse |
This means nature of Eclipse to be to associate with projects |
Default is Java perspective | ||||||||||
Console view in eclipse is like terminal in Mac OS |
Shows us the output while executing Program | |||||||||||
Add/Choose specific Jdk for Specific project > |
Project Folder > R.click > Properties > Java build Path > Libraries Tab > JRE Library > Add Library > Select Jdk > Apply and close | |||||||||||
Shorcuts > |
To type main method in Java class is : main (ctrl+space) |
Ctrl + S > saves and compiles the file | ||||||||||
CODING :- | ||||||||||||
7 |
Logic |
Logic is the working principle on which software built (What, Why & How). It is also called Business Logic. |
It is contained in the set of instructions written by programmer. | |||||||||
8 |
Object |
Simply its entity having knowledge of something of specific point of time which may or may not update according to set conditions |
More Clarity: Its copy of class at given point of time |
Object can be Value, Variable, Data Structure, Method, Table or combination of these. It also defines the Instance of class in class based OOPS | ||||||||
9 |
Object Oriented Programming Structure (OOPS) |
Object called to get or set the value |
Is the type of computer programming where programmer is using the idea of object for defines the data type of data structure and also defines the type of fx’s that can applied to data structure. Simply means which data to get or set by the use of object | |||||||||
10 |
Keyword |
Reserved words whose meaning already defined to compiler | ||||||||||
11 |
Template |
It is a file which is pre-formated in some way and serves as a starting point for new document | ||||||||||
12 |
Instance |
Is also called State |
Concrete Occurance of Object | |||||||||
13 |
Inheritance |
Is a mechanism where which one object/class acquires all the properties and behaviors of a parent object/class |
Can access the member of inherited class into inheritance class | |||||||||
14 |
Name Space |
Means Group, Collection of classes, It may be nested | ||||||||||
15 |
Data Structure |
It is the data organization, management & storage format, that enables efficeint access and modifcation. |
It Is the collection of data values and relationship amoung them | |||||||||
16 |
String |
It is sequence of characters stores in character array and marks in double quotation marks ” “ | ||||||||||
17 |
Array |
Character array is collection of variables of char data type and stores in consecutive memory addresses | ||||||||||
18 |
Concadinate |
Joining two texts together in one cell from two different cells | ||||||||||
19 |
Pointers |
Is a variable that store address of memory location | ||||||||||
20 |
Create a Java Project |
New – Java Project |
src folder |
package |
class |
main method |
run as Java application | |||||
21 |
Create a Maven Project |
New – Maven Project |
src/main/java & src/test/java folder |
package |
class |
main method & pom.xml file or Convert to TestNg execution approach which creates testng.xml |
run as Junit / TestNg Test | |||||
22 |
Class |
Class is defining idea in OOPS |
It is template definition of methods & variables or it can be a particular kind of object. It is also collection of similar data types. |
Used for re-usability, Also Called Business Object |
public class name { } | |||||||
Instance Properties > |
Block |
{ } |
Execute before to Methods and runs every time as the objects created |
{ } constructor(); method(); Methods run after constructor and Constructor run after Instance block |
static block Loads first along with the class and execute once only even if many objects created during execution. It runs before to instance block | |||||||
These are the properties of the class and declared directly within class and have scope everywhere in the class but are always used with object. |
Variable |
It is the entity that changed, It use to store & retrieve data from memory location |
Just inside the Class Curly Brackets & Declare (Just create) or Initailize (provide first value) there. |
public class name { int A = 100; } |
; called statement terminator | |||||||
Method |
Defines the behaviour of object, it is the action that object can able to perform. Methods required an object of its class to be created before it can be called. |
Inside class curly Brackets |
public void methodOne() {}; | |||||||||
A method is a block of code which only runs when it is called. Methods are used to perform certain actions, and they are also known as functions. |
Method start with return type either primitive, non-primitive or void |
name() { } with or w/o arguments |
public static void main(String args[]) { } :- main method in Java :- | |||||||||
>> same name methods can be use but number of arguments or sequence of arguments must be different |
void is also the return type as it will return nothing |
If Return type is of Primitive data types then method returns value and If Return type is of non-Primitive data types then method returns object |
main method is entry point in java and excution of java program starts from this method, all other methods called in this method | |||||||||
Local Properties > |
If any above property used inside Method it is called Local Property to that Method |
They have scope from their point of initialization to the end of block in a class. i.e. end of method |
Local variables have no default value and they must be initialized (or have some value) before being used otherwise there is compile-time error. | |||||||||
Static Properties > |
Any property used at Instance Level can be static, static not use with local property |
If we use Keyword Static then its means we call method without creating object |
Static property Called with class name or directly But normal property always called with object |
non static method/property can be called from static method with the help of object And static method can called static property directly. |
from inside static method, non static method can be called in same class with the object of class like object.nonStaticMethod(); AND static method can call static method directly or with class name. | |||||||
Static means no duplicacy, only one instance of thing which once updated then always keep its updated value |
static block at instance level executes onece only but normal block at instance level execute all time when ever class constructor run |
Static method can call static variable or static method directly, static method can call non static constructor as static keyword Not Applicable to constructor |
non static method called static method with the class name like ClassName.static Method | |||||||||
23 |
Naming Convention (Camel Case) |
Variable Name => |
start with small letter + Camel Case > |
startName = 1; | ||||||||
Method Name => |
start with small letter + Camel Case > |
startName() { }; | ||||||||||
Class Name => |
start with first Capital letter + Camel Case > |
StartName { } | ||||||||||
Project Name => |
start with first Capital letter + Camel Case > |
StartName | ||||||||||
final Variable Name => |
all Capital Leters + can use _ > |
final START_NAME = 1; | ||||||||||
Packages Name => |
Domain_Name.Application_Name.Module_Name > |
com.neimanmarcus.kids > |
Package can be of 2 types, like inbuilt package & user defined package > |
1) One class called into other class in same package then not need to import and need to import if called from other package |
import com.package.*; > This call all classes under this package | |||||||
Interface Name => |
start with small letter + Camel Case > |
startName(); |
2) class can be called also as package_Name.class_Name object = new package_Name.Class_Name(); This is called fully qualified class name | |||||||||
24 |
Data Types |
Capacity: byte = 8 Bits = 1Byte => |
Range of Values: Signed: -128 to 127 OR Unsigned: 0-255 |
<<— Primitive Data types –> |
These are basic data types and their value directly stored in memory like Byte, short, int etc and from these other data types can be derived > |
like String is derived data type | ||||||
short = 16 Bits = 2Bytes => |
-32768 to 32767 |
Primitive int variable has default value of 0. | ||||||||||
int = 32 Bits = 4Bytes => |
[ -2147483648 (2^31) to 2147483647 (2^31-1) ] |
Primitive boolean data type has default value “false”. | ||||||||||
long = 64 bits = 8bytes => |
-9223372036854775808(-2^63) to 9223372036854775807(2^63 -1) |
Primitive char variable has default value – nothing. | ||||||||||
float = 32 Bits = 4Bytes => |
[ -3.40E+38 (3.4 * 10 raise to power 38) to 3.40E+38 ] |
it is mandatory to write f or F with float value like float abc = 54.66f; | ||||||||||
double = 64 bits = 8Bytes => |
[ -1.7e+308 (1.7 * 10 raise to power 308) to 1.7e+308 ] |
no need to write f or F with double value like double abc = 54.66465747; | ||||||||||
char = 8 Bits = 1Byte => |
take any characters out of these from 0-127 => ‘a’-‘z’ or ‘A’-‘Z’ ‘&’, ‘@’, ‘0’-‘9’ AND Other symbols | |||||||||||
boolean = 1 bit => |
true or false = 0 or 1 | |||||||||||
bit = 0 or 1 |
Signed means it contains negative & positive values AND unsigned means it start from zero |
Non – Primitive Data type —>> |
is a class and can be access by object |
String is non-primitive data type and it is the class defined in Java and its take set of characters/integers or symbols written under double quotes |
String store as object | |||||||
User defined classes are also as Non – primitive data types and have non – primitive variables which are accessible thru object |
Addition obj; > Addition here class name and obj is its object name, Can have multiple data types in it |
Array List eee; > Can have rows only, Can have rows & colums, Can have Key : Value pair, Is of one data type | ||||||||||
Non-Primitive instance variable has default value null. |
Null is a Object in Java with no size and no dimensions | |||||||||||
Local variables have no default value and they must be initialized before being used otherwise there is compile- time error. | ||||||||||||
Reference Variables –>> |
Refers to memory location which stores data Like Null Object and thus value assigned to null object after execution of code | |||||||||||
25 |
Type casting for Data |
Are of two types :- implicit (means happened automatically) & explicit (means need to do intentionaly) |
implicit is also called widening like byte to short > int > long > float > double |
this convertion happened automatically like short + byte = int by default in java or int + double = double | ||||||||
explicit is also called narrowing like double to float > long > int > short > byte |
this need to do intennationally by type cast like int = (int) (long + double) | |||||||||||
26 |
Access Modifiers |
public |
private |
protected |
if no modifier given => it is also called default modifier but no keyword to write there |
These can be applied to class, variable, method, block & Constructor | ||||||
scope/available thru out in same class |
available thru out in same class |
available thru out in same class |
available thru out in same class | |||||||||
available to other class in same package |
not available to other class in same package |
available to other class in same package |
available to other class in same package | |||||||||
available to other class in different package |
not available to other class in different package |
available to other class only if this first class is sub class of Called class which means “extends” as Parent – Child relation. Variable from Parent class called with object of current class which created wih new keyword |
not available to other class in different package even if “extends” | |||||||||
Not available in other project |
Not available in other project |
Not available in other project |
Not available in other project | |||||||||
protected methods and variables work with keyword “this” as (current class) object and not with “new” object of extends class ? | ||||||||||||
27 |
Creation of Object |
Object is something which occupies memory, has size and dimensions |
When object created, whatever is with class at that time, comes to that object > Simple Means copy of class created which have all the Instance properties |
Object can be initialised by Puppy1 pup1; or Puppy1 pup1 = null; Here Puppy1 is the class |
also use to create object => packageName.constructor(); | |||||||
Box obj = new Box(); :- |
Box > |
Is the class name > |
Its load the class in JVM and also load the static variables and static methods and final variables, final methods |
static variables and static methods can be access without object of classs & with the class name | ||||||||
obj > |
is the object name > |
Object is used to access instance variables and instance methods | ||||||||||
new > |
is the keyword > |
New memory allocated and After this keyword, instance variables and instance methods loads in JVM |
new keyword also execute instance object created in that class with new keyword and execute constructor which associated with it | |||||||||
Box() > |
is the constructor of class > |
after this, object creation completed | ||||||||||
28 |
Class Constructor |
1) |
Constructors are not Properties of class but variable and methods are. |
Constructor is like method with class name and have no return type | ||||||||
2) |
are used to create object | |||||||||||
3) |
Puppy = Puppy(); |
Left side Puppy is class name and right side is that class constructor | ||||||||||
4) |
have no return type | |||||||||||
5) |
constructor can be multiple and can be overloaded inside class |
Overloading means : Same name with in same class but arguments or sequence of arguments can be differ | ||||||||||
6) |
If argument pass on to constructor then it is called Parameterized constructor |
If no argument pass then it is called default constructor |
default constructor can only be created automatically in class if no any parameterized constructor present so far |
If to use default and parametrised constrcutor, then both need to present in class | ||||||||
7) |
Constructor can be used to initialize instance variable without calling method> |
int x ; > Puppy(100); |
One class constructor called from other class without extending the first class | |||||||||
29 |
“this” Keyword |
“this” : it is a object and called as calling object and defined as current class – current object |
It called implicitly, means automatically. If any instance object or varaible is called (at class level)) then this keyword add automatically. |
If same name varaible or object is present in current method and to call instance object then this keyword to use like :- |
this.name = name :- |
By this statement, local variable assigned to instance variable by using keyword this | ||||||
It is not used where static keyword is in use |
instance object called when this keyword used or when same name object is not present in current method then “this” keyword fixed automaticlaly but it is in hidden state |
class example { float dd = 50.54; void abc() { float dd = 100.11; System.out.println(this.dd); System.out.println(dd);} | ||||||||||
local object called with in current method only without keyword this |
This print 50.54 as instance variable called with keyword “this” and 2nd ans id 100.11 |
instance object called when this keyword used or when same name object is not present in current method then “this” keyword fixed automaticlaly but it is in hidden state |
local object called with in current method only without keyword ‘this’ | |||||||||
30 |
“final” keyword |
This keyword is used where to provide value for variable which would not be change at any stage |
It can be use before class, method or variable |
If final used then value must be given for that variable. | ||||||||
final means constant value |
final variable cant be change |
final method cant be override |
final class cant be extend and cannot extend other classes | |||||||||
31 |
Null Pointer Exception |
It is caused when Object refrence is null and trying to access its properties > |
class Addition1 { int x = 100; Addition1 add = null; System.out.println(add.x);} |
If the object is null even then its know about all the static properties of class of which that object is. So it can show result for static properties | ||||||||
null have no size, no dimension, no memory but points to memory location |
Printing of x here gives null pointer exception as object “add” have null reference however x was defined. x when merged with any object then it should not be null to avoid NPE. | |||||||||||
32 |
Escape Sequence |
System.out.println(x + ” \” ” + name) > |
here \ called as Escape Sequence which means just ignore itself & ignore next character as a code and take it as a String Object – one of member in String value |
10 ” Kamal |
these only charters to use after back slash : \b, \t, \n, \f, \r, \”, \’, \\ | |||||||
System.out.println(x + ” \” amit \” ” + name) > |
10 ” amit ” Kamal | |||||||||||
System.out.println(x + ” \\” amit \” ” + name) > |
10 \” amit ” Kamal | |||||||||||
“\n abc “ |
Print abc in new line |
“\r abc “ |
Print abc in next row | |||||||||
” \t abc |
Print abc after one tab space | |||||||||||
” \b abc |
Print abc with one back space | |||||||||||
33 |
Prement Increment |
x = 5 > plus plus x (++x) > |
This means 1+x = 6 & the value of x this time update as 6 as increment predone to original x |
int ab = ++x; System.out.println(ab); System.out.println(x); | ||||||||
Post Increment |
x = 5 > x plus plus (x++) > |
This means x+1 = 6 but the value of x this time remains as 5 as increment done after running this code |
int y = 5;
int z = y++; System.out.println(z); System.out.println(y); |
//this statement increases the value of y by 1 //but will use its current value this time //and next time when you will use y, you will get its incremented value. | ||||||||
34 |
two == or .equals Operator |
two == check the memory location or compare memory location |
.equals compare content or value |
.equals operator is not applicable to Primitiave Data type | ||||||||
abc == xyz variables should have same value then returns boolean true but both objects should made by String Literal Method |
abc.eqauls(xyz); should have same value then returns boolean true whether the objects made by String Literal or String Object Method by ‘new’ Keyword |
Equality can be check for same data type | ||||||||||
Called Object equality |
Called Content Equality | |||||||||||
35 |
4 Pillars of JAVA |
# Polymorphism > |
Same name but arguments are differents or sequence is diff. called overloading |
Same name and same argument but in other class called overriding | ||||||||
# Encapsulation > |
variables are private and assigned values by public setter or getter methods | |||||||||||
# Inheritance > |
aquiring properties of parent class with extends Keyword |
Upcasting & Class Casting is also related to it | ||||||||||
# Abstraction > |
Body for method provide in child class | |||||||||||
36 |
Polymorphism |
Poly means many and morph means forms => means many forms |
Polymorphism is of 2 types :- Overloading and Overriding |
Overloading means : Same name with in same class > |
in this case method name should be same but its number of arguments or sequence of arguments should be different |
gives compile time error if something wrong | ||||||
Overriding means : Same name with in other class > |
ditto same but called with class name |
gives Runtime time error if something wrong | ||||||||||
37 |
Encapsulation |
Variables are taken as private and those are assigned values by public getter and setter methods |
also called data hiding class |
If class have not main method inside it is called entity class and also called POJO class which means Plain Old Java Object. |
Encapsulation class is example of entity class and it is used in Page Object Model framework | |||||||
Generation of getter setter methods => |
private string name; |
R.Click on Variable Name > Source > Generate getter & setter > select which one -> after method -> sort by -> generate | ||||||||||
38 |
Inheritance |
this is about to acquired properties of other class by using keyword “extends” |
Parent can be class or interface to child class or interface |
extends or implements / extends & implements |
Is a mechanism where which one object/class acquires all the properties and behaviors of a parent object/class | |||||||
all classes inherited from java.lang.object – directly or indirectly | ||||||||||||
every class extends object class which called automatically or implicitly if not mentioned otherwise |
If Object class already present in same package then extends this local class first |
system.out.println(super.name); > super here used to call name variable from Parent class | ||||||||||
39 |
Overriding (in Polymorphism) |
@override |
Override is kind of warring and method can be used with or w/o this keyword |
>> Static Methods cannot be override | ||||||||
public void sleep(){ } |
If same method is available in parent class with same arguments or with same sequence of argurments then it is called overriding |
It just an indication for developer |
>> private method not be inheritted | |||||||||
super(); |
Calling Parent class constructor |
>> final method cannot be override | ||||||||||
this(); |
Calling child class constructor | |||||||||||
super(10, 10) or super(); |
at a time, one constructor of parent class called in Child class and that should be metioned to before all inside child class constructor |
super(); this is also called default constructor & It called implicitly | ||||||||||
class constructor is called in class only, not inside the method |
super(); this(); cannot be come together as who so ever written first, same called and consider in execution | |||||||||||
40 |
Recursive Invocation |
If one constructor called and points again to calling constructor which goes on loop then this situation is called Recursive Invocation |
On the fly Object OR Anonymus Object :- |
If the object created without name like new Animal().run(); then is called as “On the fly OR Anonymus” Object | ||||||||
41 |
Upcasting |
Animal a1 = new Dog(); |
Here Animal is the Parent class & Dog & Bird are Child classes |
a1 have state of instance variable & instance method of Parent class and method state of child class and execute method of child class during runtime |
During upcasting approach, Methods execute from Child class but the variables are called from Parent class i.e. instance variables |
In other words, Object have knowledge of all the properties of Parent class and only methods of child class |
UPCASTING is from Parent to Child, not from child to parent while creating object, Child obj = new Parent() is wrong | |||||
Animal a2 = new Bird(); |
Reference of Parent class and Object here created of Child class |
Parent class called here as Reference class and child class called as object class |
Same name method need to be present in Parent class and in child class then child class method execute implicitly otherwise class casting need to use | |||||||||
If Animal extends to Bird, Bird extends to Dog then obj.Method() executes method from the first child class like dog, if not availble there then execute from next child class like bird and final from parent class if not available in any child class |
If Animal extends to Bird, Bird extends to Dog then obj.Constructor() executes constructor from top most parent class, then next parent class and then finally execute from Child / current class constructor |
DMD (Dynamic Method Dispatch) or run time Polymorphism :- |
During run time, it is decided to execute method of Child class if upcasting approach used. Run from upper child class even if method is not available in lowest child class |
If the methiod is static and present in child and parent class both then @override annotation is not applicable and method run from parent class only during runtime | ||||||||
42 |
Class Casting |
((Dog)a1).runFast(); |
Here run Fast method is not available in parent class i.e. Animal so Child class casting is need to provide to confirm executon of method in child class i.e. dog. This is called Class casting |
When method not present in parent class and have in child class and to execute from child class, class casting is required | ||||||||
43 |
instanceof Operator |
returns boolean value like true or false > |
boolean flag = a1 instanceof Animal; |
This retuns true as a1 is object of Dog class which is the child class of Animal class (Parent Class) |
instanceof here means contains…… | |||||||
44 |
Interface |
all methods are abstract inside interface. abstract keyword is optional |
Body to Method is must given inside child class who implements it. Body here means logic/statements which to execute when that interface/method called |
used for declaration not to define. we can implement multiple inteface in single class with keyword “implements”. if interface public then its member are public also. We can inherit interface within interface with kewords “extends”. |
public class abc implements Football, Basketball { } |
public interface Football extends Basketball { } |
Football and Basketball both here are interfaces | |||||
public interface Football { public void startRun(); } |
OR public interface Football { public abstract void startRun(); } |
Interface have 100% abstract methods and body / logic is to provide in class or can implement customised logic in class |
Interface have no constructors |
private & protected modifiers are not allowed in interface | ||||||||
variables can be provide inside interface but those are “public static final” |
In jdk version 8 or called as 1.8 > By using default keyword, body can be given inside interface to abstract method which can be available to all child classes without implementing it in class > |
default void print() { statements; } > Called with > |
ClassObjectName.print(); | |||||||||
Also the public static void method can also be use in interface in jdk 1.8 > |
public static void print() { statements; } > Called with > |
interfaceName.print(); | ||||||||||
45 |
Abstract Methods |
If only signature given for method without Body then it is called Abstract Method > |
abstract void setName(String name); |
abstract methods are not be final | ||||||||
By default all abstract methods are public |
abstract public void multiplication(); | |||||||||||
abstract methods are meant to Overriden in child class |
public abstract void division(); | |||||||||||
46 |
Abstract Class |
The class which can have abstract methods or solid Methods or both [Solid methods means normal method who have body] |
Keyword: abstract class abc { } or public abstract class abc { } |
It is concept of Logic hiding > |
Abstract classes have a rule that if the class contains even a single abstract method, it is mandatory to declare class abstract but if the class is abstract, it may or may not have abstract methods. | |||||||
No Object can be created for abstract class |
MyFirstAbstractClass1 obj = new ClassSolid(); By upcasting approach, constructors from top most parent class run first, then from Junior class and lastly from child class |
we can not use abstract with final keyword and also you can’t use abstract with static keyword. | ||||||||||
47 |
Random Class |
Returns int from 0 to 1 upto 12 decimal points > |
0.012345679 | |||||||||
This Method in Math class > |
Math.random(); | |||||||||||
48 |
String Class |
String V1 = “Ram”; |
Called String Literal |
created new object, if updated then also new object created |
Two objects created by String Literal have same value then points to same memory location | |||||||
String V2 = new String(“Sham”); |
Called String Object |
always created new object, if updated then also new object created | ||||||||||
In string class, whenever new value store, new object created in JVM memory every time > |
If, V1 = V1.concat(“123”); => Ram123 => New object created in memory, not updated the earlier stored V1 memory > |
This is the reason, String class called immutable | ||||||||||
49 |
String Interning Property |
String abc = “abc”; |
These two objects, created by String literal, have same value, points to same memory location in string pool and is called String interning | |||||||||
String xyz = “abc”; | ||||||||||||
String ddd = new String(“abc”); |
This always create new Object in the memory location. | |||||||||||
Object abc & ddd are different and have different memory location> |
abc = ddd.intern(); > |
This merge the memory location of both variables having same content |
Not working in code? | |||||||||
50 |
index of |
println(abc.indexOf(“c”); > |
returns int, first occurence of c > 2 |
(abc.indexOf(“Gon”)); > give index of starting character | ||||||||
println(abc.lastIndexOf(“c”); > |
returns int, returns last occurence of c > 3 | |||||||||||
println(abc.indexOf(“z”); > |
returns int, if no value present then retuns negative value > -1 | |||||||||||
51 |
charAt() |
println(abc.charAt(2)); > |
returns character at that index > c |
Index start from 0 | ||||||||
length() |
abc.length(); |
Returns int as Total count. abc is the variable |
count start from 1 | |||||||||
52 |
compareTo |
int x = abc4.compareTo(abc3); > |
retunrs int in positive and negative value |
It is not applicable to primitive type | ||||||||
If abc4 > abc3 => |
retuns + integer | |||||||||||
If abc4 < abc3 => |
retuns – integer | |||||||||||
If abc4 = abc3 => |
retuns 0 | |||||||||||
53 |
Garbage Collection |
Delete unused objects from memory. |
abc = “Raghu”; | |||||||||
We can tel JVM for the unused object but its upto JVM when to delete it |
abc = null; > |
this tell jvm that it can delete object Ragu now and this called garbage collection | ||||||||||
Garabage collection never be final, its depends on JVM to execute it or not |
abc = “Sham”; | |||||||||||
54 |
String Buffer Class |
Its mutable class |
StringBuffer sb = new StringBuffer(“abc”); |
sb.append(“john”) > john ad up to abc in same memory location > abcJohn |
sb.toString(); print object value to string | |||||||
(Similar have String Builder Class) |
New value update at same memory location of same object |
StringBuffer sb = new StringBuffer(); |
sb.replace(0, 6, “123”); > |
Startig from 0, at 6th index, replace 123 > abcjoh123 | ||||||||
All values update at same location if two objects of same name, both the objects created by ‘new’ keyword |
sb.replace(0, sb.length(), ” “); > |
Startig from 0, at entire lenght, replace empty String > ans is nothing | ||||||||||
55 |
Loops |
for > |
for(initialize; Check Condition; Increment/Decrement;) { statement; } |
for(int i=1; i<=5; i++;) { prinln(i) } |
For every iteration of outside for loop, the nested for loop initializes itself(starts from beginning) | |||||||
while > |
initialize; while(check condition) { statement; Increment / Decrement;} |
int i=1; while(i<=5) { prinln(i); i++; } | ||||||||||
do – while > |
initialize; do{ statement; Increment / Decrement;} while(check condition); |
int i=1; do{ prinln(i); i++; } while(i<=5); | ||||||||||
enhanced for loop > |
for(Collection_type New_Obj_Name : That_Collection_Object_ from which data to get) { statement; } |
for(collection_of_String ob1_name: ArrayOb2) { } | ||||||||||
56 |
if – else Conditions |
if() { } |
if only one statement is to provide for condition then curly brackets not required | |||||||||
else if () { } | ||||||||||||
else { } | ||||||||||||
57 |
Operators & && | || |
& |
AND operator checks both the conditions in if condition |
Binary Operator |
if(i=1 & i.length()=5) > returns NPE as i is null and 2nd condition gives NPE | |||||||
&& |
AND AND operator do not check 2nd condition in if condition if the first condition returns false |
Logical operator and also called Short circuit operator |
if(i=1 && i.length()=5) > returns nothing as first condition fails | |||||||||
| |
OR operator checks both the conditions in if condition |
Binary Operator |
When NPE comes, Code does not execute ahead. | |||||||||
|| |
OR OR operator do not check 2nd condition in if condition if the first condition returns true |
Logical Operator | ||||||||||
58 |
Ternary Operator |
int result = val.equals(“ram”) ? 55:100; |
If val is equal to ram then return 55 or otherwise 100 | |||||||||
59 |
break; & continue; |
break – exit from loop > |
After this keyword, code written ahead does not excute for current loop also terminate the loop counter as well |
continue – Skip one iteration / iterations as per the condition given and execute loop > |
After this keyword, code written ahead does not excute for current loop but start next loop | |||||||
60 |
Arrays |
Size must need to provide |
int[] arr1 = new int[5]; |
print(arr2.toString()); returns array values. OR Arrays.toString(arr2); -> returns arrays values |
Important Method :- Arrays.asList() :- convert Array to List |
String capitalArray[] = {“Oslo”, “Stockholm”, “Washington”, “Copenhagen”, “Seoul”, “Rome”, “Madrid”}; String countryArray[] = {“Italy”, “Norway”, “South Korea”, “United States”, “Spain”, “Denmark”, “Sweden”}; | ||||||
arrays can be of Primitive and non primitive type |
int[] arr2= {1, 2, 3, 4, 5}; //Array initialize |
print(arr2); returns junk value. or called hash code value |
This method takes the array which is required to be converted into a List. |
List<String> countryList = Arrays.asList(countryArray); | ||||||||
array have homogenous data – same type data |
int [] arr2 = null; //Array initialize |
arr2.length; – returns size. |
return a fixed-size list backed by the specified array. | |||||||||
It has AIOBE – Array Index Out of Bound Exception |
arr2 [0] = 1; //adding element to array at this index |
arr2[1].length; – returns value at that index. ?? |
The returned list is serializable and implements RandomAccess. | |||||||||
Arrays are collections of objects with the same type of a defined size. We access elements in an array using an index object, and can initialize arrays both with and without elements. |
arr2 [1] = 2; |
StringObject.length(); – returns count. |
This method acts as a bridge between array-based and collection-based APIs, in combination with Collection.toArray() | |||||||||
elements to array can be provide at the time of initialize, otherwise if it declare only then elements add with index values one by one |
int [] arr3; //Array declare |
String val = “ravi; kani; sham”; String[] arr3 = val.split(“;”); ? | ||||||||||
If array size given then it is still possible to add element in that but that cant be execute/print and give error out of bound |
int [] arr6 ; // NO! Initializers can only be used in declarations // arr6 = { 1, 2, 3, 4, 10, 11, 12 } ; |
< Gives error as values can be given only when declare | ||||||||||
61 |
Arrays vs Collection |
Arrays |
Collection | |||||||||
Arrays are fixed in size |
Expands and Collapse automatically | |||||||||||
Store same data type |
Hold multiple data type | |||||||||||
Store primitve and objects |
Stores only object | |||||||||||
62 |
String to Integer thru parseInt |
System.out.println(Integer.parseInt(args[0]) + Integer.parseInt(args[1])); |
args here can be like > |
args = argumentsForMain(); |
String args[] = {“1”, “2”}; | |||||||
This convert String to Integer and perform mathematical operation |
public static String[] argumentsForMain() { String arr4[] = {“1”, “0”}; return arr4; } |
String number1 = “40”; String number2 = “50”; |
System.out.println(Integer.parseInt(number1) + Integer.parseInt(number2)); | |||||||||
63 |
Wrapper Classes |
Eight in number |
Stores object of primitive data type by accepting primitive value |
Number num = new Long(999999); |
Integer obj2 = new Integer(5); double ll = obj2.doubleValue(); This is method in Integer class and returns value in double |
AutoBoxing :- |
If primitive data type value input then it automatically converts to wrapper class called autoboxing | |||||
Byte, Short, Integer, Long, Float, Double, Character, Boolean |
Numerical classes extends from abstract Number class |
Integer num2 = new Integer(789); |
same meaning as Integer num5 = new Integer.valueOf(789); It does not accept string value |
UnBoxing :- |
If result to get in primitive data type then it automatically convert wrapper class object to primitive data type called unboxing | |||||||
Short num3 = new Short((short)100); //?? |
int xx =Integer.parseInt(“12”); //takes in string & returns integer value | |||||||||||
Integer num4 = new Integer(“abc”); // If string convert in integer value then it shows that otherwise gives Number Format Exception | ||||||||||||
64 |
Collection Framework |
have interface & classes in package java.util; |
store objects and not store primitrive data type | |||||||||
Iterable Interface |
It has iterator() method |
which returns object of Iterator Interface & Use to read collection |
top in hierarchy, all the collection interfaces like List, Set, Map automatically implements iterable interface | |||||||||
Iterator Interface |
have following methods :- |
ArrayList al = {1, 2, 3, 4,5 }; | ||||||||||
hasNext() |
returns boolean, to check if there is element in collection |
iterator itr = al.iterator(); |
iterator methods returns object of iterator interface from collection | |||||||||
next() |
returns object of collection |
while(itr.hasNext()) | ||||||||||
remove() |
returns void, remove element from collection |
{System.out(itr.next()); } | ||||||||||
Collection Interface |
Collection coll = new ArrayList(); Collection Print all values but Array print Junk Value and Collection have methods > |
.add(“abc”) |
returns boolean >> [add element] to collection | |||||||||
.remove(“abc”) |
returns boolean >> [remove element] from collection | |||||||||||
.contains(“abc”) |
returns boolean >> used to search an element | |||||||||||
.clear() |
returns void >> remove all elements from Collection | |||||||||||
.isEmpty() |
returns boolean | |||||||||||
.size() |
returns int >> total nos of Elements in Collection | |||||||||||
Collections.sort(List_Object) & Collections.reverseOrder(); |
Sort the List in accending order & reverse the order of current object | |||||||||||
Interfaces of Collection down in Hierarchy :- |
List Interface |
Set Interface |
Map Interface | |||||||||
can have duplicate elements |
no duplicate elements |
Elements in Key Value pair, cant have duplicate Keys |
Map object need to convert in Set object to read via Map.Entry Interface | |||||||||
have Methods > |
add(1, “abc”) > insert abc at index 1 and shift earlier elements to next index, returns void |
have Methods > |
add(1, “abc”) > returns false if duplicate value added in collection |
have Methods > |
Set<Map.Entry<Integer,String>> setObj = mapObj.entrySet();, Set<Integer> setObj = mapObj.keySet(); | |||||||
get(5) > returns value at index 5 |
entrySet() > returns all entries | |||||||||||
set(1, “xyz”) > replace xyz at index 1 |
keySet() > return all Keys | |||||||||||
indexOf(“abc”) > return index of first occurrence of value abc |
put(Key, Value) > add entry in Map object | |||||||||||
lastIndexOf(“abc”) > return index of last occurrence of value abc |
entry(Key, Value) | |||||||||||
get(Key) > return value at that key | ||||||||||||
getKey() > return Key | ||||||||||||
getValue() > return Key Value at key in just above method | ||||||||||||
have classes :- |
Java new generic collection allows you to have only one type of object in a collection. ArrayList<String> al=new ArrayList<String>(); |
have classes :- |
have classes :- | |||||||||
ArrayList Class > |
maintain insertion order |
HashSet > |
returns element in Random Order due to mechanism Hashing (each object awarded hash code value which then return in accending order), allow one null value |
HashMap > |
returns keys in Random Order, have one null key | |||||||
LinkedList Class > |
maintains insertion order & have methods :- getFirst(); getLast(); addFirst(); addLast(), addAll(object) |
LinkedHashSet > |
returns element in inserted Order, allow one null value |
LinkedHashMap > |
returns keys in inserted Order, have one null key | |||||||
Vector Class > |
its Synchronised Class and hence slow |
Sorted Set Interface > |
Sorted Map Interface > | |||||||||
TreeSet Class > |
returns element in accending Order, contains one type of elements only, does not allow null value |
TreeMap Class > |
returns keys in accending Order, no null key | |||||||||
65 |
Exception Handling |
Exception come during runtime which abruptly stops the execution of program |
try { } catch(Exception e) { System.out.println(e.getClass().getName() + ” ” + e.getMessage()); } finally { } |
method() throws FileNotFound, NullPointerException or Exception {} > this provide multiple exception |
If the exception is handled in corresponding catch block, then normal flow of the program continues after executing “finally” block |
If the exception is not handled, then the program ends execution abruptly after executing “finally” block |
Error Class Exceptions :- | |||||
When exception occurs inside method, it create Exception object and handover it to JVM, If exception handling not used in code then JVM handover exception to default exception handler which show exception detail in console and abruptly close the program. |
multiple catch can be used with one try, Only finally can also be use with try w/o catch |
method() throws Throwable { } < it means same as Exception, which is equal to throw Exception {} |
throws or throw > throw new RuntimeException(“delibrate end”); |
1) OutOfMemory | ||||||||
Some Types of Exception :- |
Exception is the parent class of All type of Exceptions. catch(Exception e) is the top in hierarchy and its always comes down in line while writing code as when execution transfer to this then it catches the error and abruptly close the furthur execution of code |
compile time exception – called checked exception |
throw is used to deliberately/explicitly end the execution of code like > |
2) VirtualMachineError | ||||||||
1) Airthmetic Exception |
3) AssertionError | |||||||||||
2) NullPointer Exception | ||||||||||||
3) ArrayIndexOutOfBounds Exception | ||||||||||||
4) Runtime Exception |
catch(RuntimeException e) { Print} |
Runtime exception – called unchecked exception | ||||||||||
5) Exception | ||||||||||||
6) NoSuchElementFound Exception | ||||||||||||
7) FileNotFound Exception | ||||||||||||
8) NumberFormat Exception |
Unchecked Exceptions >> |
<< Checked Exceptions | ||||||||||
File Input, File Reader & exception Message |
try { File file = new File(“\\user\\abc”); FileReader fr = new FileReader(file); } catch(Exception e) { System.out.println(e.getClass().getName() + ” –> ” + e.getMessage()); } |
java.io.FileNotFoundException –> \user\abc (No such file or directory) | ||||||||||
Selenium | ||||||||||||
1 |
Selenium |
is free and open source suite of tools for automating web apps across different browsers and platforms |
selenium is an API. | |||||||||
2 |
WebDriver |
It is a tool which helps selenium to interect with Browser driver, further Webdriver can easliy integrate with third party tools like appium, TestNg, (Cucumber or Maven) |
WebDriver is an API |
Jointly both called Selenium WebDriver | ||||||||
Selenium have client Library for various languages (Java, Python etc) which can access the properties of selenium classes | ||||||||||||
Selenium along with WebDriver transfer execution to JSON Wire Protocol which convertes the instructions (selenium commands) to JSON and pass on to Browser driver which then perform action on browser | ||||||||||||
Browser driver pass on JSON to browser over inbuilt HTTP server and get back response over HTTP server in the form of JSON which sent back to Selenium by converting to desired client library | ||||||||||||
For Java, Selenium Client library available in the form of jar files which are basically zip form of java class files. These are executable files in zipped form. jar means Java Archieve | ||||||||||||
3 |
Selenium Components |
Selenium IDE :- |
Selenium IDE is a Chrome and Firefox plugin which records and plays back user interactions with the browser | |||||||||
Selenium RC (Remote Control) :- |
Earlier is a “Selenium core” which has limitations that selenium core (a javascript program) and Web application source code should be on same machine. This issue overcome by Selenium RC which create a proxy server that browser understand selenium core and web app are coming from same domain | |||||||||||
Web Driver :- |
Another framework created for cross platform testing which is not depend on Java Script. It has its own driver to interact with browser instead of injecting javascript. Webdriver merged with Selenium RC to form Selenium 2 |
further enhancements come in Selenium 2 > Selenium 3 > Selenium 4 | ||||||||||
Selenium Grid :- |
It aims to run tests on several machines/OS and several browsers by distributing them in Hub & Node M/c (its used for parallel execution) | |||||||||||
4 |
Integrate Selenium Library in Project |
Selenium Project Website :- |
www.selenium.dev | |||||||||
Use stable version of selenium :- |
3.141.59 > copy paste it under lib folder created inside project |
Go to Java Build Path > Add jars > select the 3.141.59 jar from lib folder | ||||||||||
If the proper documents of selenium jar files are not visible in Eclipse then > |
client-combined-3.141.59-sorces.jar > (place in lib folder) |
file need to attach by click attach button which was thus open by click on “open Declaration” of WebDriver written code in class | ||||||||||
Website to try automation testing :- |
app.box.com |
This manual approach is not required if Maven Project created | ||||||||||
Browser Driver Location :- |
Browser driver can be kept inside jdk bin folder where all executables files kept as path for the same set in OS variable under the key name ‘path’ > In this case, browser driver path not need to give inside code |
Usually keep the browser driver in project folder and give path of its in code so that its push to GIT along with all other files | ||||||||||
DOM :- |
Document Object model > |
The complete HTML page structure is known as page DOM | ||||||||||
5 |
Create Maven Project |
Eclipse > New Maven Project > Create Simple Project > |
Group ID: KJiTechCorp |
Artifact ID: WebAppAutomate > Finish | ||||||||
pom.xml file > |
<?xml version=”1.0″ encoding=”UTF-8″?> <project xmlns=”http://maven.apache.org/POM/4.0.0″ xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance” xsi:schemaLocation=”http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd”>
<modelVersion>4.0.0</modelVersion> <groupId>KjTech</groupId> <artifactId>WebAppAutomation</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>WebAppAutomation</name> <url>http://www.example.com</url> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <maven.compiler.source>1.8</maven.compiler.source> |
Updated Latest dependencies to run project | ||||||||||
<maven.compiler.target>1.8</maven.compiler.target>
<!– Environment Variables to be pass from Terminal command –> <env>QA</env> <!– seems not working –> </properties> <dependencies> <!– this dependency for selenium to interect with driver–> <dependency> <groupId>org.seleniumhq.selenium</groupId> <artifactId>selenium-java</artifactId> <version>3.141.59</version> </dependency> <!– this dependency for testNG to manipulate test cases–> <dependency> <groupId>org.testng</groupId> <artifactId>testng</artifactId> <version>7.3.0</version> </dependency> |
continue part 2 | |||||||||||
<!– this dependency for Extent Report–> <dependency> <groupId>com.aventstack</groupId> <artifactId>extentreports</artifactId> <version>4.0.0</version> </dependency> </dependencies>
<build> <!– Code related to to Non Java resources which refer to classes in Resources package like Listener class etc–> <resources> <resource> <directory>src/main/java/Resources</directory> <filtering>true</filtering> </resource> </resources> <!– Code related to Maven Sure Fire Plugin giving knowledge of test cases in src/test/java as class_name_Test.java –> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-surefire-plugin</artifactId> <version>3.0.0-M5</version> |
continue part 3 | |||||||||||
<!– Code related to Maven Sure Fire Plugin giving knowledge of testng.xml file–> <configuration> <suiteXmlFiles> <suiteXmlFile>testng.xml</suiteXmlFile> </suiteXmlFiles> </configuration>
</plugin> </plugins> </build>
</project> |
continue part 4 | |||||||||||
6 |
R.Click Project > TestNG > Convert to TestNG > testng.xml |
By this testng.xml file created which used to run test cases via maven commands |
<?xml version=”1.0″ encoding=”UTF-8″?> <!DOCTYPE suite SYSTEM “https://testng.org/testng-1.0.dtd”> <suite name=”Suite”> <!– Invoke Report Generation–> <listeners> <listener class-name=”Resources.ExtentReporterNG”/> <listener class-name=”Resources.Listeners”/> </listeners>
<test thread-count=”5″ name=”Test”>
<groups> <dependencies> <group name=” ” depends-on=” “></group> </dependencies> </groups>
<classes> <class name=”Memberse.WebAppAutomation.wSmokeTest”/>
</classes>
</test> <!– Test –> </suite> <!– Suite –> | |||||||||
More Details on Maven & pom.xml file is below in this document |
Test Class must end as classNameTest.java to understood by maven sure fire plugin | |||||||||||
7 |
Project Design Pattern |
Follow Page Object Model |
Web Elements declare in one package under folder src/main/java |
use one Class per Web Page | ||||||||
Base & Utilities Classes declare in one package under folder src/main/java |
Package Name like BasePost | |||||||||||
Reports & Listeners Classes declare in “Resources” package under folder src/main/java |
This Resources package linked via code written in pom.xml file | |||||||||||
All the Test case classes declare in package under folder src/test/java |
Package Name like BetaTests | |||||||||||
Any other related stuff to be kept under src folder | ||||||||||||
Create desired Classes under packages mentioned above :- | ||||||||||||
Create a Base Class under BasePost Package & Declare Variables there | ||||||||||||
Create BrowserDriver Folder in src Folder and place Webdriver there |
Place it by accesing folder location on SSD | |||||||||||
Set Browser Capabilities / Options & provide driver location | ||||||||||||
Set TestNG Annotations | ||||||||||||
Add Web Elements in/as samplePage under Page Objects Package |
Name of Method is ditto same as of class name for Page Factory code to play in Page object model | |||||||||||
Add sampleTestCase under src/test/java |
Run it | |||||||||||
8 |
Web Element :- |
it takes in Object of By class |
Important methods :- |
String cValue = Web_Element.getCSSValue(“color”), takes in attribute of CSS under computed tab in inspect element, then Print String |
getAttribute(“data-resin-target”), takes in attribute of tag and returns value of that attribute |
.getElementIfPresence(By by) | ||||||
9 |
By Class :- |
have static methods and can return object of By Class |
id, name, class, xpath, css, linkText, partialLinkText and tagName |
driver.findElement(By.name(“value”)); | ||||||||
10 |
Search Context Interface :- |
This interface has 2 methods :- |
findElement() & findElements() |
findElement returns WebElement & findElements returns List of WebElements | ||||||||
this extends by 2 more interfaces :- |
WebDriver Interface :- |
Implements by Chromedriver, Firefoxdriver classes etc | ||||||||||
WebElement Interface :- |
Implements by …. | |||||||||||
11 |
Web Element Locators :- |
Selenium Commands |
id |
name |
className |
xpath |
cssSelector |
linkText |
partialLinkText |
tagName | ||
driver.getTitle; |
driver.findElement(By.id(“value”)); |
driver.findElement(By.name(“value”)); |
this locator to use least |
//tagName[@attribute=’value’] |
tageName[attribute=’value’] |
used for <a> |
used for <a> | |||||
Web_Element_Name.clear(); |
class name have spaces due to multiple classes applied for that element |
//button[@class=’value’ and text()=’value’] |
button[dark-resin-target=’accountmenu’] |
full text is given under this locator |
partial text can be given from full text for this locator | |||||||
findElement(By.cssSelector(“button[dark-resin-target=’accountmenu’]”)); |
Use this tag name if there is only one class used or there is no space in the value of className |
(//button[@class=’value’])[1] :- index in HTML start from 1 not from 0 |
select[id=’value’][name=’value’] |
By by1 = By.linkText(“Visit QA University”); |
By by2 = By.partialLinkText(“University”); | |||||||
driver.get(“https:www.google.com”); |
Exception get due to multiple classes is NoSuchElementFound |
(//div[@class=’value’])/b[contains(text()=’value’)] :- / means here just after child tag of div tag AND // means any child tag of div tag |
select#value.value :- here # stands for id & . stands for class | |||||||||
driver.quit(); |
(//*[contains(text(),’Contact Us’)])[1] |
select#value option[value=’500′] :- space here means any child down the line and in place of space if > provided that means just after child of select tag | ||||||||||
List<WebElements> lw = driver.findElements(By.id(“passes”)); lw.get(0).sendKeys(“abc”); |
(//div[@role=’row’ and @tabindex=’0′]) |
button[class*=’btn-full-width’] :- here * means contains and for value we can provide the one class from full className | ||||||||||
Get Web element :- |
List<WebElement> dotsMenu = ewait.until(ExpectedConditions.visibilityOfAllElements(hp.ThreeDotIcon())); //List<WebElement> dotsMenu = driver.findElements(By.xpath(“//span[@class=’w-8 h-8 flex items-center justify-center’]”)); System.out.println(dotsMenu.size()); dotsMenu.get(1).click(); |
//div[@role=’row’ and .//a[text()=’new23′]] :- . means here child tag |
button[class*=’create-dropdown-menu-toggle-button’]:not([class*=’upload-button’]) | |||||||||
above Page Factory class code :- |
@FindBy(xpath=”//span[@class=’w-8 h-8 flex items-center justify-center’]”) private List<WebElement> ThreeDotIcon ; public List<WebElement> ThreeDotIcon () { return ThreeDotIcon; } |
//button[@attribute=’value’]//span[@attribute=’value’] |
By.cssSelector(“li[class*=’menu-item’][class*=’submenu-target’]:not([class*=’integrations-menu-item’]):not([class*=’CollectionsMenuItem’])”) | |||||||||
String cValue = sp.searchButton().getCssValue(“color”); String atbValue = sp.searchButton().getAttribute(“class”); |
//a[text()=’new23′]/ancestor::div[2role=’row’] :- ancestor here means parent tag |
….Above using multiple class from single class atrribute | ||||||||||
//button[.=’New’] :- use dot in case of text() if the text provided in child tag of button | ||||||||||||
xpath can traverse up and down in DOM |
css can traverse down only in DOM | |||||||||||
//li[@class=’menu-item submenu-target’]//ul[@tabindex=’-1′]//span[contains(text(),’Rename’)] |
By.cssSelector(“div[class*=’selectedGroupStart’] button[aria-label=’More Options’]”) | |||||||||||
….above using second tag in xpath with any child tag with // |
….above space used for any child tag | |||||||||||
By.xpath(“//button[@class=’btn btn-primary ‘]//span[contains(text(),’Save’)]”)) | ||||||||||||
//*[contains(text(), ‘Your TestMonitor domain’)]. //a[contains(text(), ‘testmonitor.com’)] | ||||||||||||
12 |
Exceptions :- |
NoSuchElement Exception > |
Given by findElement() |
Timeout Exception |
< given by WebDriverWait untill() | |||||||
ClickIntercepted Exception > |
Element is present in DOM but not visible |
Assertion Error |
< given by Assert.assertTrue like methods | |||||||||
MalformedURL Exception > |
If the http or https keyword not added to url of website as these request goes to browser over HTTP server understands url with these keywords | |||||||||||
13 |
Implicit Wait :- |
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); |
This wait applicable for all Web elements in class who are using driver.findElement() |
There are 5 interface inside Web Driver Interface :- | ||||||||
This wait checks/poll for element at every 500 miliseconds, that is twice in a second and when the element located, action performed. |
1) Option Interface :- Option interface extends WebDriver Interface. |
Webdriver manage() method returns Options interface which is required for managing different stuff in a browser like deleting cookies, managing options etc. |
Options opt = driver.manage(); |
manage method is of WebDriver, Returns Option interface object |
void deleteAllCookies(); |
Timeouts timeouts(); |
Window window(); | |||||
This wait keep on checking for element till the time given under the method, like here its checks for upto 10 secs |
2) Timeout Interface :- Timeout Interface extends Option Interface |
Options interface timeouts() method returns Timeouts interface, required for implementing implicit wait and script or page timeout. |
Timeouts to = opt.timeouts(); |
timeouts method is of Options, Returns Timeouts interface object |
to.implicitlyWait(25, TimeUnits.SECONDS); –>> is a method of Timeouts |
to.pageLoadTimeout(25, TimeUnits.SECONDS); |
to.setScriptTimeout(25, TimeUnits.SECONDS); –> gives timeout for the execution of Test Script | |||||
If the element not located during 10 secs, then no such element found exception thrown |
3) Window Interface :- extends Options Interface |
Options interface window() method returns Window interface, required for setting size and position of current window. |
Window win = new Window(driver); Dimension dim = new Dimension(500, 500); win.maximize(); win.fullscreen(); > |
win.setPosition(Point targetPosition); send x, y here |
win.getPosition(); |
win.getSize(); |
win.setSize(dim); | |||||
4) Navigation Interface :- |
Webdriver navigate() method returns Navigation interface, required for doing browser back, forward, to and refresh. |
driver.navigate().refresh(); > |
navigate().forward(); |
navigate().back(); |
navigate().to(“url”); | |||||||
5) Targetlocator Interface :- |
Webdriver switchTo() method returns TargetLocator interface, required for switching to window, frame or alert. |
Alert alert(); > |
WebDriver window(String nameORHandle); |
WebDriver frame(String nameORId); | ||||||||
14 |
Explicit Wait :- |
Used with conditions and for particular Web Element |
WebDriverWait extends FluentWait extends Wait Interface | |||||||||
1) Static |
Thread.sleep(); | |||||||||||
2) Dynamic | ||||||||||||
WebDriverWait w = new WebDriverWait(driver, 25 ); |
taking two arguments – driver & time in seconds | |||||||||||
w.untill(Expected Condition can be null / true or false); |
until() method is of FluentWait Interface |
Condition till the time false or null, it look for it / poll till total time at the frequency of every 500 mili secs, i.e. 2 times in 1 secs |
Wait<WebDriver> wait2 = new FluentWait<WebDriver>(driver) .withTimeout(Duration.ofSeconds(30)) .pollingEvery(Duration.ofSeconds(5)) .ignoring(NoSuchElementException.class); |
Wait<WebDriver> wait3 = new WebDriverWait(driver, 10) .pollingEvery(Duration.ofSeconds(5)) .withTimeout(Duration.ofSeconds(30)) .ignoring(NoSuchElementException.class); | ||||||||
always throw Timeout Exception on completion of time |
When the condition becomes true, next line code executed | |||||||||||
Expected Condition.oneOfMethod(take object of By class like xpath, css etc) |
ExpectedCondition is class here | |||||||||||
Expected Condition methods return Web Element, List or Boolean. these are methods of ExpectedCondition Class :- | ||||||||||||
w.until(ExpectedConditions.presenceOfElementLocated(By.xpath(“//*[@attribute=’value’]”))); |
> Element present in DOM |
returns Web Element or List | ||||||||||
w.until(ExpectedConditions.visibiltyOfElementLocated(By.xpath(“//*[@attribute=’value’]”))); |
> Element present in DOM + Visible on screen. visible means element height & width > 0 |
returns Web Element or List | ||||||||||
w.until(ExpectedConditions.elementToBeClickable(“By.xpath(//*[@attribute=’value’]”))); |
> Element present in DOM + Visible on screen + Able to click |
returns Web Element or List | ||||||||||
w.until(ExpectedConditions.invisibilityOf(WebElement)); |
> Element was visible but not visible currently | |||||||||||
w.until(ExpectedConditions.invisibilityOfElementLocated(By.xpath(“//*[@attribute=’value’]”))); |
> Same as above method but takes in object of By class | |||||||||||
w.until(ExpectedConditions.tittleIs(“BOX | Login”)); |
> Title of Web is |
returns true or false | ||||||||||
w.until(ExpectedConditions.titleContains(“BOX | Login”)); |
> Title of Web Page contains this |
returns true or false | ||||||||||
w.until(ExpectedConditions.elementToBeSelected(By.xpath(“//*[@attribute=’value’]”))); | ||||||||||||
w.until(ExpectedConditions.urlContains(“BOX | Login”)); | ||||||||||||
w.until(ExpectedConditions.urlToBe(“BOX | Login”)); | ||||||||||||
Actions act = new Actions(driver); WebElement rowElement = wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath(“//div[@role=’row’ and .//a[text()='”+bookmarkEntry+”‘]]”))); act.moveToElement(rowElement).build().perform(); wait.until(ExpectedConditions.presenceOfNestedElementLocatedBy(rowElement, By.xpath(“//input[contains(@id,’checkbox’)]”))).click(); |
Use of Nested Element concept | |||||||||||
15 |
Assert :- |
For Java Project, import org.junit in class file and import JUnit library under java build path |
Assert.assertTrue(” Message to display in case of False “, boolean type variable) |
If the result is true then happens nothing and next line code executes |
> More Methods :- |
Assert.assertEquals(” expected value”, “actual value”) | ||||||
If the result becomes false then return assertion Error and program ends |
Assert.assertNotNull(String message, Object object) | |||||||||||
16 |
Math Class :- |
Java have Math Class which have following usefull methods :- |
Math.random(); |
returns any float value from 0 to 1 upto 12 Decimal places | ||||||||
random().nextFloat(); |
returns any float value from 0 to 1 upto 1 Decimal place | |||||||||||
17 |
Select class for dropdown :- |
1. Create Web Element for Select tag > |
WebElement selection = wait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector(“select[name=\”invite-permission\”]”))); |
If the dropdown created by select tag then send keys are possible as like > |
WebElementOfSelectTag.sendKeys(“Viewer”); |
This will choose the value from drop downlist accoridng to visible list | ||||||
2. Create Object of Select Class > |
Select permissionSelect = new Select(selection); |
If also excepts partial text and will select value where it get partial text at very first time | ||||||||||
3. Use these methods to search for specific value on drop down > |
permissionSelect.selectByVisibleText(“Viewer”); | |||||||||||
permissionSelect.selectByIndex(0); | ||||||||||||
permissionSelect.selectByValue(“Viewer”); |
Value here is the attribute of option tag and its value given inside ” “ | |||||||||||
get options method returns List of Web Elements :- |
List <WebElement> elementCount = permissionSelect.getOptions(); | |||||||||||
System.out.println(elementCount.size()); // for(WebElement sample: elementCount) { // if(sample.getText().equals(“Viewer”)) // sample.click(); //break; // } | ||||||||||||
.isMultiple() |
returns Boolean = true if multiple values exists in dropdown | |||||||||||
18 |
Advanced wait Methods :- |
Attribute Validation :- all these methods return Boolean value > |
wait.until(ExpectedConditions.attributeToBe(By Object, attribute_Name, attribute_value)); |
takes in 3 Arguments > |
boolean flag = wait.until(ExpectedConditions.attributeToBe( By.cssSelector(“div[class*=’ItemListActionBar’]”), “data-testid”, “actionbar”)); | |||||||
wait.until(ExpectedConditions.attributeContains(By.cssSelector…, attribute_Name, attribute_value)); | ||||||||||||
wait.until(ExpectedConditions.attributeToBeNotEmpty(element, attribute_Name)); |
takes in 2 Arguments | |||||||||||
Waiting for element count :- the method of numberOfElement() returns List of Web elements > |
wait.until(ExpectedConditions.numberOfElementsToBe(By Locator, Elements Number)); | |||||||||||
wait.until(ExpectedConditions.numberOfElementsToBeLessThan(By Locator, Int)); | ||||||||||||
wait.until(ExpectedConditions.numberOfElementsToBeMoreThan(By Locator, Int)); |
takes in 2 Arguments > |
List<WebElement> list = wait.until( ExpectedConditions.numberOfElementsToBeMoreThan(By.xpath( “//button[@class=’btn explore-button’]”), 0)); | ||||||||||
Waiting for text in element :- returns boolean > |
wait.until(ExpectedConditions.textToBe(By Locator, Pattern.compile(“textStringPart”)); |
takes in 2 Arguments > |
boolean flag = wait.until(ExpectedConditions.textToBe(By.xpath( “//button[contains(@id,’menubutton’)]//span[text()=’New’] “), “New”)); | |||||||||
wait.until(ExpectedConditions.textMatches(By Locator, “text”)); | ||||||||||||
19 |
Actions Class :- |
Actions action = new Actions(driver); |
here driver is called agumented driver |
all methods of Actions class return object of Actions class except few methods |
This class used Action chaining as all methods return object of Actions class so each method can able to call other method like method1().method2() and so on | |||||||
action.moveTo(WebElement).build().perform(); |
here build is the method of Actions class and return object of Action Interface which is not implemented by Action class. AND further we are calling perform method of Action Interface along with the object of Action Interface |
.build() complies all events & .perform() execute the event | ||||||||||
OR |
Use firefox > do mouse hover > press shift + R.click > inspect | |||||||||||
action.moveTo(WebElement).perform(); |
perform() is the method of Actions class and called to build method of Actions class and then same calling perform method of Action Interface which is same as above | |||||||||||
Important Methods for mouse events are :- |
clickAndHold() |
Important Methods for keyboard events are :- |
keyDown(modifier_key) > key press | |||||||||
contextClick() > for Right click |
keyUp(modifier_key) > key release | |||||||||||
doubleClick() |
sendKeys() | |||||||||||
dragAndDrop(source_element, target_element) | ||||||||||||
dragAndDropBy() | ||||||||||||
moveToElement(WebElement) > move the mouse to middle of that element | ||||||||||||
moveByOffset() | ||||||||||||
release() | ||||||||||||
Actions Class, DragAndDrop Methods :- |
DragAndDrop |
source = wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath(“//div[contains(@id,’box’)][text()=’Oslo’]”))); destination = wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath(“//div[contains(@id,’box’)][text()=’Norway’]”))); act.dragAndDrop(source, destination).build().perform(); |
act here is the object of Actions class | |||||||||
DragAndDropBy |
source = wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath(“//div[contains(@id,’box’)][text()=’Stockholm’]”))); destination = wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath(“//div[contains(@id,’box’)][text()=’Sweden’]”)));
Point currentLocation = source.getLocation(); Point finalLocation = destination.getLocation(); int xOffset = finalLocation.getX() – currentLocation.getX()+1; int yOffset = finalLocation.getY() – currentLocation.getY()+1; act.dragAndDropBy(source, xOffset, yOffset).build().perform();
|
here point class used, getLocation() returns the x & y pixels of starting of that Web element. X means horizontal & Y means verticle. Here starting points get for source and destination elements and offset calculated by destination – current location | ||||||||||
ClickAndHold() |
source = wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath(“//div[contains(@id,’box’)][text()=’Madrid’]”))); destination = wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath(“//div[contains(@id,’box’)][text()=’Spain’]”))); act.clickAndHold(source).moveToElement(destination).release().build().perform(); |
here, release need to use at the end to release the hold part | ||||||||||
Keys Class :- |
org.openqa.selenium.Keys is a enum (group of named constants) representing keyboard pressable keys that aren’t text. |
Using static method chord() of Keys: • static String chord(CharSequence… value) – Simulate pressing many keys at once in a “chord“ • Appends each key value to a string, and adds the chord termination key (Keys.NULL) and returns the resultant string. |
Copy / Paste Action using Keys class :- |
Select all > |
Actions builder = new Actions(driver); builder.keyDown( Keys.CONTROL ).sendKeys( “a” ).keyUp( Keys.CONTROL ).build().perform(); | |||||||
WebElement textBox = driver.findElement(By.id(“123”)); textBox.sendKeys(Keys.Enter); |
WebElement ele1 = driver.findElement(By.id(“123”)); String pressMultipleKeys = Keys.chord(Keys.CONTROL, Keys.RETURN); ele1.sendKeys(pressMultipleKeys); |
Copy > |
builder.keyDown( Keys.CONTROL ).sendKeys( “c” ).keyUp( Keys.CONTROL ).build().perform(); | |||||||||
-> Key Control + Enter -> opens link in new tab. Chord method takes in more than 2 arguments if multiple keys are to press in one go |
Paste > |
builder.keyDown( Keys.CONTROL ).sendKeys( “v” ).keyUp( Keys.CONTROL ).build().perform(); | ||||||||||
20 |
Point Class :- |
.getLocation() > returns starting x & y pixels | ||||||||||
21 |
Diemension Class :- |
.getSize() > returns …. | ||||||||||
22 |
Cookie class :- |
Cookies created by web server when first time request goes to the server, are in key – value pair (it is user information), returned along with the response to the browser, stored on client side and execute on server side as send along with second request to server |
Cookies class implements Options Interface > |
driver.manage().getCookies(); returns Set Collection |
Get Cookies Method > |
Options opt = driver.manage(); Set<Cookie> notloggedInSet = opt.getCookies(); System.out.println(“Not logged-in Cookies –>> “+notloggedInSet); |
Set<Cookie> ckSet = driver.manage().getCookies(); for(Cookie ck:ckSet) { System.out.println(ck.getName()+”******”+ck.getDomain()+”######”+ck.getValue()); } | |||||
Add Cookies Method > |
Cookie newck = new Cookie(“user1”, “qamentor”); opt.addCookie(newck); | |||||||||||
Get specific Cookie name & value Methods by passing in Cookie Key > |
Cookie newC = driver.manage().getCookieNamed(“user1”); System.out.println(newC.getName()+”—>>>”+newC.getValue()); | |||||||||||
Delete All Cookies Method > |
opt.deleteAllCookies(); | |||||||||||
23 |
Javascript Executor Interface :- |
It is the interface. |
Any element can be locate and action performed by javascript which apply over HTML |
Javascript Executor <= Remote WebDriver => Take Screenshor Interface |
Parent class of Remote WebDriver is WebDriver. |
Chromerdriver etc extends Remote WebDriver | ||||||
JavascriptExecutor jse = (JavascriptExecutor)driver; | ||||||||||||
jse.executeScript(String script, Object args) |
Takes in script as string and 2nd or 3rd argument….. as object which is optional. This method returns object | |||||||||||
OR | ||||||||||||
((Javascript)driver).executeScript(” “); |
Javascript methods are :- |
Click on Element by Id > |
jse.executeScript(“document.getElementById(“123″).click();”); | |||||||||
Gives Javascript Exception if anything is wrong for jse code |
click on element at Zero Index if multiple arguments passed > |
jse.executeScript(“argument[0].click();, WebElement OR elements as arg[0], arg[1], arg[2]”); |
executor.executeScript(“arguments[0].click();”,emailTextField, “11”, “kk”, “abc”); | |||||||||
javascriptExecutor even used if to locate element rather to perform any action on that |
assigned values to some webelement > |
.value=’abc’ => this method is like SendKeys in Javascript |
executor.executeScript(“arguments[0].value=arguments[2]”,emailTextField,”qacult”,21.21f); // Here value 21.21 pass on element at index[0] | |||||||||
Open Website > |
((JavascriptExecutor)driver).executeScript(“window.location.href = ‘https://app.box.com’;”); | |||||||||||
Scrolling jse script > |
js.executeScript(“window.scrollTo(0, document.body.scrollHeight)”); Thread.sleep(3000); js.executeScript(“window.scrollTo(document.body.scrollHeight, 0)”); Thread.sleep(3000);
js.executeScript(“document.getElementById(‘rhf’).scrollIntoView();”); |
WebElement element = driver.findElement(By.id(“rhf”)); js.executeScript(“arguments[0].scrollIntoView();”, element); |
js.executeScript(“window.scrollBy(0,100000)”); |
((JavascriptExecutor) driver).executeScript(“arguments[0].scrollIntoView(true);”, element1, “ll”, “kk”); | ||||||||
Get CSS code by javascript Executor > |
WebElement searchField = driver.findElement(By.id(“twotabsearchtextbox”));
//get css of webelement by applying following script with JavascriptExecutor JavascriptExecutor executor1 = (JavascriptExecutor)driver; String script = “var s = ”;” + “var o = getComputedStyle(arguments[0]);” + “for(var i = 0; i < o.length; i++){” + “s+=o[i] + ‘:’ + o.getPropertyValue(o[i])+’;’;}” + “return s;”;
Object allCss = executor1.executeScript(script, searchField); System.out.println(“——–>>>>>>>>>> ” + allCss);
//splits the String into array to show every css separately. String[] cssArray = allCss.toString().split(“;”); for(String str : cssArray){ System.out.println(str); } |
<<– amazon.com |
Get content height and content width of web page > |
int contentHeight = ((Number) ((JavascriptExecutor)driver).executeScript(“return window.innerHeight”)).intValue(); int contentWidth = ((Number) ((JavascriptExecutor)driver).executeScript(“return window.innerWidth”)).intValue(); | ||||||||
24 |
Take Screenshot Interface :- |
Complete code > |
String screenshotPath = System.getProperty(“user.dir”)+”/screenshots/screenshot_”+System.currentTimeMillis() + “.png”; File srcFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE); //Returns file use to store screenshot on file system System.out.println(“Screen capture saved at location “+ screenshotPath);
try { FileHandler.copy(srcFile, new File(screenshotPath)); } catch (IOException e) { System.out.println(e.getMessage()); } |
File srcFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE); //Returns file use to store screenshot on file system //byte[] byteArray = ((TakesScreenshot) driver).getScreenshotAs(OutputType.BYTES);//Returns array of Bytes and use for embedded screenshot in report //String srcString = ((TakesScreenshot) driver).getScreenshotAs(OutputType.BASE64);//Returns String and use store screenshot in database |
If output type target is class, then return type of method is Class<org.openqa.selenium.OutputType> | |||||||
25 |
Event Firing WebDriver :- |
EventFiringWebDriver is an API for tracking and logging the various events that happen when test scripts are executed using WebDriver. |
Many navigation events get fired before and after a WebDriver internal event occurs (such as before and after navigating to a URL, before and after browser back-navigation, before and after findBy, before and after click etc), and these can be tracked and captured. |
For capturing WebDriver events, you have to use: • EventFiringWebDriver class which is used to wrap WebDriver around to throw events • WebDriverEventListner interface that you have to implement to catch the WebDriver events |
EventFiringWebDriver class has a method register() which let you register our implementation of WebDriverEventListner to listen to the WebDriver events | |||||||
EventHandler Class > which implements WebDriverEventListener > |
In ecplise | |||||||||||
Test class thur which we can use Event Firing WebDriver and WebDriver Event Listener > |
public static void main(String[] args) throws InterruptedException { System.setProperty(“webdriver.chrome.driver”, System.getProperty(“user.dir”)+”/chromedriver/chromedriver”);
WebDriver driver = new ChromeDriver(); EventFiringWebDriver eventDriver = new EventFiringWebDriver(driver); EventHandler handler = new EventHandler(); eventDriver.register(handler); eventDriver.get(“https://app.box.com”); Thread.sleep(2000);
WebElement element = eventDriver.findElement(By.name(“login”)); element.click();
element.sendKeys(“qacult.demo@gmail.com”); } | |||||||||||
26 |
Desired Capabilities Class :- |
extends MutableCapabilities Class which further inherits from Capabilities interface. |
This class is use to provide capabilities to project like the type of OS, Which browser to use etc, This class is provided in “org.openqa.selenium.remote” package. > |
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.setBrowserName(“chrome”); capabilities.setCapability(“platform”,Platform.WINDOWS); capabilities.setCapability(ForSeleniumServer.PROXYING_EVERYTHING, true); // Dont know why to use this capabilities.setCapability(CapabilityType.ACCEPT_SSL_CERTS, true); capabilities.setCapability(CapabilityType.SUPPORTS_ALERTS, true); capabilities.setCapability(CapabilityType.SUPPORTS_JAVASCRIPT, true); capabilities.setCapability(“marionette”, true); //This is use for Firefox browser only so that logs appear properly in console
WebDriver driver = new RemoteWebDriver(new URL(“http://localhost:5556/wd/hub”), capabilities); |
in WebDriver API is a series of key/value pairs that stores the browser properties like browser name, browser version, the path of the browser driver in the system, supports javascript or not etc. to determine the behaviour of the browser at run time. |
DesiredCapabilities class is used to set some specific testing environment like web browser, Mobile device, mobile emulator or mobile simulator using setCapability() method. | ||||||
27 |
ChromeOptions OR FirefoxOptions :- |
extends MutableCapabilities Class. Both are the child class of MutableCapabilities class which is also parent class of DesiredCapabilities class. |
With the Chrome options, take screenshot (via screenshot class) is possible even in headless execution too but that is not possible for HtmlUnitDriver |
Headless Execution :- |
ChromeOptions options = new ChromeOptions(); options.addArguments(“headless”); options.addArguments(“window-size=1200×600”); // or you can also do // options.setHeadless(true);
WebDriver driver = new ChromeDriver(options); | |||||||
28 |
HtmlUnitDriver Class :- |
This is Old class. |
HtmlUnit is a java based implementation of a web browser without a user interface. |
With the Chrome options, take screenshot (via screenshot class) is possible even in headless execution too but that is not possible for HtmlUnitDriver |
Script :- HtmlUnitDriverClass | |||||||
This class is in “org.openqa.selenium.htmlunit “ package. |
This class is not in hierarchy of RemoteWebDriver class and does not implement TakesScreenshot interface. | |||||||||||
HtmlUnitDriver class is direct implementation of WebDriver and implements JavascriptExecutor. |
To use HtmlUnitDriver class, include htmlunit-driver-xxx.jar as a dependency in your project’s build-path. | |||||||||||
Constructors for doing headless execution with HtmlUnitDriver > |
HtmlUnitDriver() – Constructs a new instance with JavaScript disabled, and the default BrowserVersion | |||||||||||
HtmlUnitDriver(boolean enableJavascript) – Constructs a new instance, specify JavaScript support and using the default BrowserVersion. | ||||||||||||
HtmlUnitDriver(com.gargoylesoftware.htmlunit.Brows erVersion version) – Constructs a new instance with the specified BrowserVersion. | ||||||||||||
HtmlUnitDriver(com.gargoylesoftware.htmlunit.Brows erVersion version, boolean enableJavascript) – Constructs a new instance with the specified BrowserVersion and the JavaScript support. | ||||||||||||
29 |
TargetLocator Interface :- |
TargetLocator is an inner interface of WebDriver for changing the focus of the driver to another frame, window or alert. |
Script :- NaukariUpload |
Switching Window :- |
String homePage = driver.getWindowHandle(); |
It is the method of Web Driver Interface and return String as in Unique Id of currect active window | ||||||
TargetLocator switchTo() – This method when used with WebDriver instance, returns the object of TargetLocator interface. > |
TargetLocator tl = driver.switchTo(); |
Script :- NotesCompleteFinal |
java.util.Set<String> windows = driver.getWindowHandles(); |
It is the method of Web Driver Interface and return Set of String type as in Unique Id of all opened windows by driver | ||||||||
Instance methods of TargetLocator Interface > and all these methods return WebDriver Instance except alert() method > |
WebDriver window(String nameOrHandle) |
– Switch the focus of future commands for this driver to the window with the given name/handle. | ||||||||||
WebDriver frame(int index) |
– Select a frame by its (zero-based) index and switches to it. | |||||||||||
WebDriver frame(String nameOrId) |
– Select a frame by its name or ID and switches to it. | |||||||||||
WebDriver frame(WebElement frameElement) |
– Select a frame by frame(webelement) and switches to it. | |||||||||||
Alert alert() |
– Switches to the alert dialog. | |||||||||||
This code also opens multiple windows upto 5 > |
String homePage = driver.getWindowHandle(); System.out.println(“handle is:- “+homePage);
for(int i=0; i<5; i++) { ((JavascriptExecutor)driver).executeScript(“window.open(‘http://google.com’, ‘_blank’);”); } //This opens multiple Tabs in Browser
// driver.switchTo().window(homePage); Thread.sleep(3000); WebDriverWait wait = new WebDriverWait(driver, 100);
System.out.println(“homePage”);
//********************************************** // get all window handles in a collection java.util.Set<String> windows = driver.getWindowHandles(); //********************************************** System.out.println(windows); System.out.println(windows.size()); for (String windowHandle : windows) { if (!windowHandle.equals(homePage)) { WebDriver dr = tl.window(windowHandle); dr.close(); dr.switchTo().window(homePage); } } |
int windowSize = driver.getWindowHandles().size(); //1 notesBtn.click();
wait.until(ExpectedConditions.numberOfWindowsToBe(windowSize + 1)); //2 |
Set<String> allWindows = driver.getWindowHandles(); System.out.println(allWindows.toString()); System.out.println(allWindows.size());
/* int count = 0; for(String obj : allWindows) { if(count == allWindows.size()-1) //Taking size here as 1 but it serves the index as argument in next line driver.switchTo().window(obj); //Switch to next window in Object ? count++; } System.out.println(driver.getWindowHandle().toString());
OR */
List<String> windowsList = new ArrayList<String>(allWindows); String windowToSwitch = windowsList.get(windowsList.size() – 1); driver.switchTo().window(windowToSwitch); System.out.println(driver.getWindowHandle().toString()); | |||||||||
30 |
iframe :- |
iframe Tag means, their is separate HTML inside main HTML OR iframe is a web page which is embedded in another web page or an HTML document embedded inside another HTML document. |
Methods are :- |
driver.switchTo.frame(id/name/index/Webelement); |
returns WebDriver object. > |
driver.switchTo().frame(0); driver.switchTo().frame(1); |
driver.switchTo().frame(“name of the element”); driver.switchTo().frame(“id of the element”); |
driver.switchTo().frame(WebElement); | ||||
If any element is inside of iframe then it is need to switch to that iframe to perform action on that iframe |
ExpectedCondition.frameToBeAvailableAndSwitchToIt(id/name/index/Webelement); |
> |
//driver.switchTo().frame(“service_iframe”); //OR wait.until(ExpectedConditions.frameToBeAvailableAndSwitchToIt(“service_iframe”)); //Same method as like above
| |||||||||
iframe can be locate by id, name, by index or by creating Web Element thru any suitable locator method |
driver.switchTo().parentFrame(); |
Returns to the main iFrame of child iframe in which you stand | ||||||||||
An iframe tag is defined using <iframe></iframe> tags. |
driver.switchTo().defaultContent(); |
Returns to main HTML from any iframe | ||||||||||
There can be multiple iframes inside one iframe |
.size(); |
returns size of only all child iframes in which currently you are in | ||||||||||
31 |
Alert Interface :- |
A small message box on screen which does not have HTML or we can say a dialog box from OS side |
Methods :- |
TargetLocator tl = driver.switchTo();
//Switching to Alert Alert alert = tl.alert(); |
Alert have 4 methods :- |
alert.accept(); | ||||||
It has message, can takes in input as text, have Ok and cancel button |
driver.switchTo().alert(); |
returns intance of alert interface |
alert.dismiss(); | |||||||||
It has its own javascript. When the alert closed then control automatically switched to last window |
Alert alert = new WebDriverWait(driver, 20).until(ExpectedConditions.alertIsPresent()); |
> This method check for alert is present and if yes then switch to it |
alert.sendKeys(“abc”); | |||||||||
If alert is not there then gives NoAlertPresent Exception |
alert.getText(); | |||||||||||
If try to access web element and alert is present then thos given Unhandled alert Exception | ||||||||||||
32 |
File Upload :- |
If file to upload then there must be <input with class=’ ‘ type=’File’> |
It has class = hidden then upload need to be handle by Robot class |
Method to use for upload is sendKeys() :- |
WebElement element1 = wait.until(ExpectedConditions.presenceOfElementLocated(By.id(“resumeUpload”))); ((JavascriptExecutor) driver).executeScript(“arguments[0].scrollIntoView(true);”,element1); element1.sendKeys(“D:\\Coaching Docs\\appium_android_automation.pdf”); } | |||||||
33 |
Robot Class :- |
This class is in AWT package which deals with Keyboard Keys |
Its work with copy the file path on Clipboard and then paste in OS opened dialog box |
Copy Part > |
//copy the file path in system clipboard StringSelection strSel = new StringSelection(“D:\\Coaching Docs\\appium_android_automation.pdf”); Toolkit.getDefaultToolkit().getSystemClipboard().setContents(strSel, null); | |||||||
Click on Upload Button and thus OS dialog box opens > |
//upload button click WebElement uploadElement = wait.until(ExpectedConditions .presenceOfElementLocated(By.xpath(“//li[contains(@class,’UploadMenuItem’)]//span[text()=’File Upload’]”))); uploadElement.click(); Thread.sleep(4000); | |||||||||||
Paste Part > |
Robot robo= new Robot();
// Press CTRL+V robo.keyPress(KeyEvent.VK_CONTROL); robo.keyPress(KeyEvent.VK_V);
// Release CTRL robo.keyRelease(KeyEvent.VK_CONTROL); Thread.sleep(2000);
// Press Enter robo.keyPress(KeyEvent.VK_ENTER);
// Release Enter robo.keyRelease(KeyEvent.VK_ENTER); |
Press Enter too if required. | ||||||||||
34 |
Web Element Screenshot :- |
This is basically crop the area of full screen screenshot according to desired starting coordinates provided and then crop it upto provided x & y coordinates |
Code :- |
Element located for which screenshot to take > |
//Locate Image element to capture a screenshot. WebElement element = wait.until(ExpectedConditions. presenceOfElementLocated(By.cssSelector(“a.header-logo”))); | |||||||
Take entire screen screenshot > |
//Capture entire page screenshot as File. //Used TakesScreenshot, OutputType Interface of selenium and File class of java to capture a screenshot of the entire page. File screen = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE); | |||||||||||
Get the starting coordinates for element for which screenshot to take > |
//Used selenium Point class to get x y coordinates of Image element. //get location(x y coordinates) of the element. Point point = element.getLocation(); int xcordinate = point.getX(); int ycordinate = point.getY(); | |||||||||||
Get the width and height of element for which screenshot to take > |
//Used selenium getSize() method to get height and width of element. //Retrieve width of element. int imageWidth = xcordinate + element.getSize().getWidth(); //Retrieve height of element. int imageHeight = ycordinate + element.getSize().getHeight(); | |||||||||||
Reading the fullscreen screenshot taken > |
//Reading full image screenshot. BufferedImage img = ImageIO.read(screen); | |||||||||||
Cutting the screenshot according to provided x y coordinates > |
//cut Image using height, width and x y coordinates parameters. BufferedImage destination = img.getSubimage(xcordinate, ycordinate, imageWidth, imageHeight); ImageIO.write(destination, “png”, screen); | |||||||||||
Saving to File system > |
String screenshotPath = System.getProperty(“user.dir”)+”/screenshots/screenshot_element”+System.currentTimeMillis() + “.png”;
//save Image screenshot In project’s location FileHandler.copy(screen, new File(screenshotPath)); | |||||||||||
35 |
Web Storage Class :- |
Session & Local storage set in key value paid and get value by key |
Local Storage :-> |
Session Storage :-> | ||||||||
It can be valid unless the url not changed | ||||||||||||
Before to login, local storage is good to work on | ||||||||||||
After login, session storage is good to work on | ||||||||||||
36 |
Cucumber Framework :- |
Is like TestNG and it is somewhere better from it as it provide more feature |
Repositories used for Cucumber stable version 6.10.0 is io.cucumber |
Gherkins language used :-> |
JUnit Annotations :- @Test |
In src folder > create folder named features (In case of Maven: create folder inside package of src/test) | ||||||
TestNg called Test driven development – TDD, Here test manipulates in .xml file and in class file also |
For Manuall process, keep jar files in lib folder and then add this from PRoject > Java build path > Library > Add jars (hit cancel to the dialog box thus appear on screen) |
Given : It is prerequisite |
A JUnit test is a method contained in a class which is only used for testing. This is called a Test class. |
Inside features folder, create file and named it like Aeroplane.feature | ||||||||
Cucumber called Behaviuor driven development – BDD |
When : It is action to perform |
Install Eclipse plugin from market place which is not necessary but good for color coding of code | ||||||||||
another such framework is Serenity |
Then : Verify the result |
Used gherkins language in .featue file like :- (This is called Test specification) |
Feature: Aeroplane Inspection Report Scenario: 1.Inspection of Passenger Cabin Given Inspector & Aeroplane are available When Open Aeroplane door Then Verify seats for 50 passnegers are present
Scenario: 2.Inspection of Cockpit Given Inspector & Pilots are available When Open Cockpit door Then Verify two Pilots are present | |||||||||
it is built with th help of JUnit |
#Feature: List of scenarios. #Scenario: Business rule through list of steps with arguments. #Given: Some precondition step #When: Some key actions #Then: To observe outcomes or validation #And,But: To enumerate more Given,When,Then steps #Scenario Outline: List of steps for data-driven as an Examples and <placeholder> #Examples: Container for s table #Background: List of steps run before each of the scenarios #””” (Doc Strings) #| (Data Tables) #@ (Tags/Labels):To group Scenarios #<> (placeholder) #”” ## (Comments) |
And : It is used either after Given or When or Then if there are multiple values in the same and in code file when it is implemented thru snippet approach then it is represented by Given, when and then only respectively after which it is used. We can also use * instead for And |
Create Steps defination class, means code file in any package like by using mapping keywords :- |
public class Aeroplane {
@Given(“^Inspector & Aeroplane are available$”) public void aeroplaneCabin() { System.out.println(“Inspector & Aeroplane are present and ready \n”); }
@When(“^Open Aeroplane door$”) public void cabinDoor() { System.out.println(“Inspector opened Aeroplane main cabin door \n”); }
@Then(“^Verify seats for 50 passnegers are present$”) public void cabinResult() { boolean check = true; Assert.assertTrue(“Seats condition failed”, check); System.out.println(“Seat are present for 50 Passengers \n”); }
@Given(“^Inspector & Pilots are available$”) public void aeroplaneCockpit() { System.out.println(“Inspector & Pilots are ready \n”); }
@When(“^Open Cockpit door$”) public void cockpitDoor() { System.out.println(“Inspector opened Aeroplane Cockpit door \n”); }
@Then(“^Verify two Pilots are present$”) public void cockpitResult() { System.out.println(“Both the Piolts are present \n”); } } |
Here the use of ^ $ is not mendatory as that is use before the version 6.0. NOw can give @Given statement inside (” “). One step from feature file cannot be mapped to two different step definitions | |||||||
In Cucumber, Test Specification written in feature file and Steps defination (Code) written in java file which the map togather |
But : It is used either after Given or When or Then if there are multiple values in the same and in code file when it is implemented thru snippet approach then it is represented by Given, when and then only respectively after which it is used. We can also use * instead for And |
Create Test Runner class in other package say com.CucumberExecutor package and add certain code there outside class curly brackets called cucumber options:- |
package com.CucumberRunner; import org.junit.runner.RunWith; import io.cucumber.junit.Cucumber; import io.cucumber.junit.CucumberOptions; import io.cucumber.junit.CucumberOptions.SnippetType; @RunWith(Cucumber.class) @CucumberOptions( features = {“src/features”}, glue = {“com.CucumberTraining”}, monochrome = true, // tags=”@loginparam1 or @calculator”, plugin = {“pretty” , “summary”} // snippets = SnippetType.CAMELCASE, // publish = true, // dryRun=false ) public class JUnitRunner { } |
Run it by Right click and run as JUnit test |
plugin = {“pretty” , “summary”} => If Given, When, Then not implemented in java file then plaugin – summary provide snippets in console on run JUnitRunner which we can copy use in java file. “pretty” shows the mapped methods in console to feature file. AND plugin = {“progress”} => gives console output for code results as like it is bullets points |
snippets = SnippetType.CAMELCASE => this provide the name of snippets methods in camel case but default value is UNDERSCORE. monochrome = true => console output is readable in better manner/remove junk characters. By default monochrome option is false |
dryRun=false => its default value. If it is true then its look for missing step definitation in code file and provide snippet for that and does not execute code |
publish = true => This option allows to publish Cucumber HTML reports in cloud (OR remove warnings from console output) . We can easily share these reports within our organization/teams who will be able to access them from anywhere with unique URL. | ||||
Test specifications define in feature file using Gherkins language |
Background: This keyword allows you to add some context to the scenarios that follow it. It can contain | |||||||||||
In the end JUnit Runner class created to excute the test from feature file/Gherkins files |
We can use the same step as many times as we want in same or different feature files. But there will be only one step definition to the same wording step in java code. But if the same step is mapped with more than one method in the code, it will confuse cucumber-jvm and cucumber will throw DuplicateStepDefinitionException. | |||||||||||
It it open source tool | ||||||||||||
37 |
feature file more elaboration :- |
Common Step in feature file :- If any step written under Backgroud keyword then that step run for each scenerio > Its execure after scenerio heading but before to each step mentioned in that scenerio. This means @before code execute fully and then will execute Background code |
Background: Given browser is “chrome” And user want to Launch to the Box App Then user verify page title “Box | Login” in the app When user enter the “vaas.mj.seenu@gmail.com” and “Srinivas061” and Login to the app Then user verify page title “All Files | Powered by Box” in the app |
Comment in feature file can be givven with # like > |
# I am assuming weekend charges are extra 100 bucks of actual delievery cost. # Weekend charges are levied for Friday, Saturday or Sunday. | |||||||
Tag :- |
Given in feature file and run from JUnit Test runner file. That test case will execute which tag mentioned in test runner file |
@boxbookmark Feature: Create Delete Bookmark Feature Background: Given browser is “chrome” |
Cucumber options to run tag :- |
@CucumberOptions( features={“src/features”}, glue={“com.stepdefination”}, monochrome=true, tags=”@loginparam1 or @calculator”, plugin={ “pretty” , “summary”}, snippets = SnippetType.CAMELCASE, publish = true, dryRun=false ) |
or’ in tags act as And here that means both tags run | |||||||
Tags can be applied to Feature, Scenerio, Cucumber Hooks (called conditional hooks, either to Scenerio or step), Examples table |
@createbookmark Scenario: Create bookmark |
tags=”@amount and @weekend”, |
and’ here means which scenerio have both the tags, only that will execute | |||||||||
Tags are to group scenerio’s and start with @ and can be of any name |
@case1 Examples: |
tags=”@boxbookmark”, | ||||||||||
@calculator Feature: Verify that two numbers are operated on |
tags=”not @boxbookmark”, |
This means not execute tag @boxbookmark abd execute all others | ||||||||||
38 |
Cucmber Hooks :- |
Code run to before every Scenerio even to before Backgroud step for each scenerio> |
@Before |
@Before // public void beforeScenario(Scenario sc) { // System.out.println(sc.getName()); // System.out.println(“before everything”); // } |
getName() –can be used to get name of scenario. isFailed() – Returns true or false if scenario fails or passes. getStatus() – Returns pass or fail status of scenario as String | |||||||
Code run to after every Scenerio > |
@After |
@After public void afterScenario(Scenario sc) { System.out.println(sc.isFailed()); System.out.println(“status is: “+sc.getStatus()); System.out.println(“after everything”); // driver.quit(); } | ||||||||||
Code run to before every step > |
@BeforeStep |
@BeforeStep public void beforeStep(Scenario sc) { System.out.println(sc.getLine()+”step changed”); } | ||||||||||
Code run to after every step > |
@Afterstep |
@AfterStep public void afterStep() { System.out.println(“step ended”); } | ||||||||||
These hooks can be written in any class but in same package in which step definitions are written |
Conditional Hook are :- |
@Before (“@addMul, @addSum”) // public void beforeScenario(Scenario sc) { // System.out.println(sc.getName()); // System.out.println(“before everything”); // } |
This @before hook can only operate for scenerio where tag given as @addMul |
or’ ‘and’ can also be used in conditional hooks | ||||||||
To run hooks, keep the dryrun = false in test runner file |
In conditional hooks, instead of comma for tags, or and can be use | |||||||||||
39 |
Gherkin Parameterized :- |
Instead of text, Integers can be provide in step in feature file which can serve as argument to method in step definition file |
@add @operation Scenario: AddNumbers Given I have two numbers 5 & 10 When I “add” two numbers Then the result must be “greater” than 10 |
5 & 10 here are Integer and “add” & “greater” here is String | ||||||||
Instead of text, String can be provide in step in feature file in ” ” which can serve as argument to method in step definition file |
These scenerio can be written again & again if different test data is to provide | |||||||||||
Gherkin parameterized can be achieved with example table where all the test data given under Examples table and same repeating scenerio can be written once > |
#QACult Assignment # I am assuming weekend charges are extra 100 bucks of actual delievery cost. # Weekend charges are levied for Friday, Saturday or Sunday. Feature: Verify that user is able to ship during weekend at extra cost @weekend Scenario Outline: Weekend Charges Given the system API is not down Then user should be able to see available “<vendors>” for shipping. And user should select “<weight>” and “<area>” And user selects “<service>” type as express Then user should select “<Payment>” type And current “<day>” is Friday, saturday or sunday Then calculated amount should be adding weekend delievery “<charges>”
Examples: |vendors|weight|area |service |Payment | day |charges | |vendor1|400 |90 |Express |COD |Friday |100 | |vendor2|600|160|Express|Prepaid|Saturday|100| |vendor3|700|175|Express|COD|Monday|0| |
here the parameters taken in example table are given defined <> brackets in steps which are taking values from table |
Scenerio Outline serves the same purpose as Scenerio in .feature file and Scenerio name can also be parametrized by < > AND Scenerio Outline is used when Examples table to use or Can use Scenerio Template when to use Examples table |
Can use escape sequence in .feature file, R.click on Example table and choose preety format option to align the values in table. Tags also used on multiple examples table |
Example table parameterized is not possible in Background |
Variable can be declare in code which can be taken dynamically in step to use :-> here Bookmarkentry is the variable taken from step definition >> |
Background: Given browser is “chrome” @bookmarkDataTableHeaderScenario Scenario Outline: Create and delete multiple bookmarks using DataTable Given user navigates to the Box App Then user verify the “<title1>” in the app When user enter the correct “<name>” and “<password>” and Login to the app Then user verify the “<title>” in the app When user create multiple new bookmark with name and verifies the “<Message>” success message as below: | url | name | description | | dcfolder.com | dcfolder | good | | fridge.com | fridge | best | | garage.com | garage | better | When user deletes multiple bookmarks and verifies the “<DeleteMessage>” deletion message When user logout of the application Then user verify the “<title1>” in the app Examples: | name | password | title | title1 | Message | DeleteMessage | | qacult.demo@gmail.com | testing123 | All Files \| Powered by Box | Box \| Login | A bookmark for “bookmarkEntry” was created successfully. | Item successfully moved to trash. | | |||||
40 |
Some Facts :- |
WebDriver scripts with cucumber require all the step definition to be written in one step definition Java class. This is because: If we create one step of the scenario in other Java step definition Class, Java will throw NullPointerException because the driver is not initialized in the other class. Even if the driver is initialized in other class, we will be creating a new instance and will get NoSuchElementException for any element locator we find. | ||||||||||
41 |
Singleton class & single browser for all test cases :- |
Singleton class means have private constructor which called to static instance and instance can be get thru public getter method |
Have project where Single browser open, named: CucmberwithSingleton and feature file name is New Login Example |
Have project where Single browser open and browser name also passed from .feature file > cucumberwithsingletonBrowser and .feature file name is : LoginBrowser | ||||||||
42 |
Cucumber Reporting :- |
Reports can be of 5 types and automatically generated if code written in Test Runner file :- |
HTML Report :- |
“html:reports/htmlreports/report.html”, |
tags=”@bookmarkExampleScenario”, plugin ={“pretty”, “summary”, “html:reports/htmlreports/report.html”, “json:reports/report.json”, “junit:reports/Cucumber.xml”}, monochrome=true, | |||||||
Json Report :- |
“json:reports/report.json”, | |||||||||||
xml report :- (Json mix with xml = HTML) |
“junit:reports/Cucumber.xml”, | |||||||||||
Master Thought Report :- |
Code provide ahead in the row > (to see this report, uner reports folder in project, look for Overviewfeature.html) |
Additional jar need to insert in lib folder for it and those jar already have in project provided by trainer |
If use maven then those can be get from mvn repositery. Add that in pom file and file to import in class file from net package |
It is good and more elaborative form of report |
Code for it to be write in cucmber Hooks under @Before under which called Master thoughts report method and Method can be write any where inside hooks class |
@Before public void beforeAll() { if(!dunit) { Runtime.getRuntime().addShutdownHook(afterAllThread); System.out.println(“Will be executed when dunit is false and changing dunit to true”); dunit = true; } }
Thread afterAllThread = new Thread() { public void run() { System.out.println(“snake!”+” dunit value is: “+dunit); System.out.println(driverSet.size()); for(WebDriver driver:driverSet) driver.quit();
generateMasterThoughtReport(); } }; |
public void generateMasterThoughtReport() { File reportOutputDirectory = new File(“reports/Masterthought”); List<String> jsonFiles = new ArrayList<>(); String jsonPath = System.getProperty(“user.dir”)+”\\reports\\report.json”; System.out.println(jsonPath); jsonFiles.add(jsonPath); String buildNumber = “1”; String projectName = “Box Project”; Configuration configuration = new Configuration(reportOutputDirectory, projectName); configuration.setBuildNumber(buildNumber); configuration.setParallelTesting(false); configuration.setRunWithJenkins(false);
ReportBuilder reportBuilder = new ReportBuilder(jsonFiles, configuration); Reportable result = reportBuilder.generateReports(); } |
Hooks Code :- static boolean mtr need to intialize as instance varaiable :- |
@Before public void beforeAll() { if(!mtr) { Runtime.getRuntime().addShutdownHook(afterAllThread); System.out.println(“Will be executed when dunit is false and changing mtr to true”); mtr = true; } }
Thread afterAllThread = new Thread() { public void run() { generateMasterThoughtReport(); } }; | |||
Extent Report :- | ||||||||||||
43 |
Scenerio :- |
import Scenario.cucumber.java |
Scenario.log(“message”) |
< this helps to write message in report, scenario is intance value getinf value from valiable in cucumber hooks |
Step Definaton code:- public class CreateDeleteBookmarkSteps { WebDriver driver; WebDriverWait wait; int bookmarkVal; String bookmarkEntry; List<String> noOfBookmarks; WebElement succcessMessageNotification; public Scenario scenario;
public CreateDeleteBookmarkSteps() { DriverInstance instance = DriverInstance.getInstance(); driver = instance.getDriver(); wait = instance.getWait(); this.scenario = CucumberHooks.scenario; } …………………… |
scenario.log(“Bookmark success message text verified”); |
Cucumber Hooks code :- @Before public void beforeAll(Scenario sc) { scenario = sc; | |||||
Scenario.attach |
< this helps to attach screenshot to report |
scenario.log(“Bookmark success message text verified”); scenario.attach(UtilityClass.takeByteScreenshot(driver), “image/png”, bookmarkEntry+” verified”); |
take screenshot class code :- public class UtilityClass {
public static byte[] takeByteScreenshot(WebDriver driver) { TakesScreenshot scDriver = (TakesScreenshot)driver; byte[] scBytes = scDriver.getScreenshotAs(OutputType.BYTES); return scBytes; } | |||||||||
44 |
Data Table :- |
If one step is to repeat multiple times then use Data table | ||||||||||
Data table can be used for three cases :- |
If a step row have single column with multiple rows, then used method to read column is asList > …>>>> this code is wrong for asList >>>>> |
@When(“^user enter the username and password as below and Login to the app$”) public void enterWithDataTable(DataTable data) throws Throwable { List<List<String>> dataList = data.asLists(); int count =0; for(List<String> row : dataList) {
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath(“//input[@id=’login-email’]”))).sendKeys(row.get(0)); wait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector(“button[id=’login-submit’]”))).click(); |
@boxScenario_dataTable Scenario: Login into box scenario2 Given user navigates to the Box App Then user verify the “Box | Login” in the app When user enter the username as below and password “Srinivas061” and Login to the app | pfighter@gmail.com | | vaas.mj.seenu@gmail.com | Then user verify the “All Files | Powered by Box” in the app When user logout of the application Then user verify the “Box | Login” in the app | |||||||||
If a step row have multiple columns with multiple rows, then used method to read column is asLists > |
@When(“user create multiple new bookmark and verifies the \”A bookmark for \”bookmarkEntry\” was created successfully.\” success message as below:”) public void createMultipleNewBookmarks(DataTable dataTable) throws Exception {
WebElement newDropdownMenu = wait .until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector(“button[class*=\”create-dropdown-menu-toggle-button\”]:not([class*=’upload-button’])”))); // List<String> dataList = dataTable.asList(String.class); List<List<String>> dataList = dataTable.asLists(); noOfBookmarks = new ArrayList<String>(); Thread.sleep(3000); for(List<String> row:dataList){ System.out.println(“The size of row is :”+row.size());
System.out.println(“aaaaaaa”+newDropdownMenu.getText()); newDropdownMenu.click(); WebElement bookmarkCreationLink = wait.until( ExpectedConditions.elementToBeClickable(By.cssSelector(“li[aria-label=\”Create a new Bookmark\”]”))); bookmarkCreationLink.click(); |
@boxScenario_dataTable2 Scenario: Login into box scenario2 Given user navigates to the Box App Then user verify the “Box | Login” in the app When user enter the username and password as below and Login to the app | pfighter@gmail.com | axa12345 | | qacult.demo@gmail.com | testing123 | Then user verify the “All Files | Powered by Box” in the app When user logout of the application Then user verify the “Box | Login” in the app |
This use key value pair if header is given and then use HashMap > asMaps() :- |
public void userCreateMultipleBookmarkWithName(DataTable dataTable) throws Exception { WebElement newDropdownMenu = wait .until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector(“button[class*=\”create-dropdown-menu-toggle-button\”]:not([class*=’upload-button’])”))); // List<String> dataList = dataTable.asList(String.class); List<Map<String,String>> dataList = dataTable.asMaps(); noOfBookmarks = new ArrayList<String>(); Thread.sleep(3000); for(Map<String,String> row:dataList){ System.out.println(“The size of row is :”+row.size());
System.out.println(“aaaaaaa”+newDropdownMenu.getText()); newDropdownMenu.click(); WebElement bookmarkCreationLink = wait.until( ExpectedConditions.elementToBeClickable(By.cssSelector(“li[aria-label=\”Create a new Bookmark\”]”))); bookmarkCreationLink.click(); WebElement titleBookmark = wait .until(ExpectedConditions.presenceOfElementLocated(By.cssSelector(“h2[class=\”modal-title\”]”))); System.out.println(“title bookmark:”+titleBookmark.getText());
WebElement urlTextField = wait.until(ExpectedConditions.presenceOfElementLocated(By.cssSelector(“input[data-resin-target=\”urlinput\”]”))); WebElement nameTextField = wait.until(ExpectedConditions.presenceOfElementLocated(By.cssSelector(“input[data-resin-target=’nameinput’]”))); WebElement descTextField = wait.until(ExpectedConditions.presenceOfElementLocated(By.cssSelector(“input[data-resin-target=\”descriptioninput\”]”)));
urlTextField.clear(); scenario.log(“Creating new bookmark with name “+row.get(“name”)); // bookmarkVal = (int)(Math.random()*((1000-1)+1))+1; bookmarkEntry = “www.”+ row.get(“url”); System.out.println(“bookmark entry-“+bookmarkEntry); urlTextField.sendKeys(bookmarkEntry); nameTextField.sendKeys(row.get(“name”));
descTextField.clear(); descTextField.sendKeys(row.get(“description”)); noOfBookmarks.add(row.get(“name”)); scenario.attach(UtilityClass.takeByteScreenshot(driver), “image/png”, row.get(“name”)); WebElement createButton = wait.until(ExpectedConditions.elementToBeClickable(By.cssSelector(“button[data-resin-target=\”create\”]”))); createButton.click(); Thread.sleep(2000); }
} | ||||||||
If a step row have multiple columns with multiple rows + Data table header is to use to, then used method to read column is asMaps > |
@When(“user create multiple new bookmark with name and verifies the \”A bookmark for \”bookmarkEntry\” was created successfully.\” success message as below:”) public void userCreateMultipleBookmarkWithName(DataTable dataTable) throws Exception { WebElement newDropdownMenu = wait .until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector(“button[class*=\”create-dropdown-menu-toggle-button\”]:not([class*=’upload-button’])”))); // List<String> dataList = dataTable.asList(String.class); List<Map<String,String>> dataList = dataTable.asMaps(); noOfBookmarks = new ArrayList<String>(); Thread.sleep(3000); for(Map<String,String> row:dataList){ System.out.println(“The size of row is :”+row.size());
System.out.println(“aaaaaaa”+newDropdownMenu.getText()); newDropdownMenu.click(); WebElement bookmarkCreationLink = wait.until( ExpectedConditions.elementToBeClickable(By.cssSelector(“li[aria-label=\”Create a new Bookmark\”]”))); bookmarkCreationLink.click(); |
@bookmarkDataTableHeaderScenario Scenario Outline: Create and delete multiple bookmarks using DataTable Given user navigates to the Box App Then user verify the “<title1>” in the app When user enter the correct “<name>” and “<password>” and Login to the app Then user verify the “<title>” in the app When user create multiple new bookmark with name and verifies the “<Message>” success message as below: | url | name | description | | dcfolder.com | dcfolder | good | | fridge.com | fridge | best | | garage.com | garage | better | When user deletes multiple bookmarks and verifies the “<DeleteMessage>” deletion message When user logout of the application Then user verify the “<title1>” in the app Examples: | name | password | title | title1 | Message | DeleteMessage | | qacult.demo@gmail.com | testing123 | All Files \| Powered by Box | Box \| Login | A bookmark for “bookmarkEntry” was created successfully. | Item successfully moved to trash. | | ||||||||||
45 |
.feature file facts :- |
If one step repeat again in .feature file with small text again then in step definition, code can be written under one method by using forward slash for those OR words > |
@When(“user enter the correct/wrong/credentials {string} and {string} and Login to the app”) public void loginToApp(String uName, String pwd) throws Throwable { wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath(“//input[@id=’login-email’]”))).sendKeys(uName); | |||||||||
46 |
Cucmber Hooks code to quit driver and all windows :- |
@Before public void beforeAll(Scenario sc) { scenario = sc; System.out.println(“scenarioname “+sc.getName()); System.out.println(“runs before background in every scenario and dunit value is “+dunit); if(!dunit) { Runtime.getRuntime().addShutdownHook(afterAllThread); System.out.println(“Will be executed when dunit is false and changing dunit to true”); dunit = true; } }
Thread afterAllThread = new Thread() { public void run() { System.out.println(“snake!”+” dunit value is: “+dunit); System.out.println(driverSet.size()); for(WebDriver driver:driverSet) driver.quit(); } }; |
@After public void executeAtEndOfScenario(Scenario sc) { System.out.println(“status is “+sc.getStatus()); DriverInstance.getInstance().getDriver().manage().deleteAllCookies(); } | |||||||||
47 |
Executing Test Runner/ Junite runner classes thru main() :- |
Give all Test runner files reference here ans those run in sequencential order. |
public class MainExecutor { public static void main(String[] args) { JUnitCore junit = new JUnitCore(); junit.addListener(new TextListener(System.out)); junit.run(TestRunner.class); //These are Test runner classes junit.run(ReRunRunner.class); //These are Test runner classes
} } | |||||||||
48 |
Rerun failed Scenerio :- |
To capture failed scenerio to rerun, code to insert in test runner file. |
In Test Runner file, this code to add :- |
plugin ={“pretty”, “html:reports/htmlreports/report.html”, “json:reports/report.json”, “junit:reports/Cucumber.xml”, “rerun:reports/rerun.txt” }, |
Then to rerun failed test case, Additional Rerun file to create with ref. to .txt file > |
package com.executor; import org.junit.runner.RunWith; import io.cucumber.junit.Cucumber; import io.cucumber.junit.CucumberOptions; @RunWith(Cucumber.class) @CucumberOptions( //Cucumber execute failed scenarios from this file features = {“@reports/rerun.txt”, }, glue={“com.stepDefinition”}, //the path of the step definition files plugin = {“pretty”, “html:reports/htmlreports/cucumber-pretty-rerun.html”, “json:reports/CucumberTestRerunReport.json” }, monochrome = true //display the console output in a proper readable format ) public class ReRunRunner {
} |
Main class to execure all :- |
package com.executor; import org.junit.internal.TextListener; import org.junit.runner.JUnitCore; public class MainExecutor { public static void main(String[] args) { JUnitCore junit = new JUnitCore(); junit.addListener(new TextListener(System.out)); junit.run(TestRunner.class); //These are Test runner classes junit.run(ReRunRunner.class); //These are Test runner classes
} } | ||||
Any scenrio if failed then it capture by that code and it rerun once to try for its pass | ||||||||||||
That failed scenario rerun after executing all current in execution scenarios | ||||||||||||
49 |
Parameterised by DocString :- |
If some lengthy string king of multi lines or paragraph is to send dynamically to code from .feature file then Docstring to use | ||||||||||
any string write inside “”” abcd…. “”” tripple quote marks consider as DocString and as such snippet created for Docstring automatically if dry run or try to execute that scenario from .feature file etc |
When user creates a new bookmark with url “<bookmarkurl>” And user enters the bookmark description as: “”” This bookmark is a link for the code, which explains how to randomise the given text in the following context. “”” Then user verifies the following success message: “”” A bookmark for “www.random.com” was created successfully. “”” When user deletes a bookmark |
@When(“user enters the bookmark description as:”) public void userEntersTheBookmarkDescriptionAs(String docString) { // Write code here that turns the phrase above into concrete actions WebElement descTextField = wait.until(ExpectedConditions.presenceOfElementLocated(By.cssSelector(“input[data-resin-target=\”descriptioninput\”]”))); descTextField.sendKeys(docString); } | ||||||||||
docString can be pass dynamically to stepdefinition file | ||||||||||||
50 |
Maven :- |
Keep Jar in M2 folder which is local to machine |
Set Environment Variables like Path: give path of maven folder upto bin folder |
Terminal Commands are :- |
from Eclipse workspace folder in terminal :- | |||||||
Need internet to download jar files and use those repeatedly for any project |
M2_HOME : give path of Maven Folder |
mvn -version |
mvn archetype:generate >enter, 2007 >enter, 1.4 >enter, groupId: com.cssoft >enter, artifcatId: Admin section >enter, 1.0Snapshot >enter, package(reconfirm) >enter |
snapshot is versioning tool but we are using git | ||||||||
Download Maven from Internet and Unzip the folder like C:\ Maven_Folder |
From Project Folder :- |
groupId is package name & artifactId is Project name | ||||||||||
mvn test > Build and run project | ||||||||||||
mvn install > Check for missing link and run project | ||||||||||||
mvn clean > delete target directiory which have JVM files to run project (compiled files) | ||||||||||||
Create Maven project from eclipse :- |
Choose, Create simple Project | |||||||||||
51 |
Life cycle of Maven :- |
Validate, Compile, Test, Package, Integration test, Verify, Install, and Deploy. |
All these cycles have terminal commands > |
mvn clean: Cleans the project and removes all files generated by the previous build. | ||||||||
mvn compile: Compiles source code of the project. |
Compile: It compiles the source code, converts the .java files to .class, and stores the classes in the target/classes folder. | |||||||||||
mvn test-compile: Compiles the test source code. |
Integration test: It runs the integration tests for the project. | |||||||||||
mvn test: Runs tests for the project. |
Test: It runs unit tests for the project. | |||||||||||
mvn package: Creates JAR or WAR file for the project to convert it into a distributable format. |
Package: This step packages the compiled code in a distributable format like JAR or WAR. | |||||||||||
mvn install: Deploys the packaged JAR/ WAR file to the local repository. |
Install: This step installs the packaged code to the local Maven repository. | |||||||||||
mvn site: generate the project documentation. |
Verify: This step runs checks to verify that the project is valid and meets the quality standards. | |||||||||||
mvn validate: validate the project’s POM and configuration. |
Validate: This step validates if the project structure is correct. For example – It checks if all the dependencies have been downloaded and are available in the local repository. | |||||||||||
mvn idea:idea: generate project files for IntelliJ IDEA or Eclipse. | ||||||||||||
mvn release:perform: Performs a release build. | ||||||||||||
mvn deploy: Copies the packaged JAR/ WAR file to the remote repository after compiling, running tests and building the project. |
Deploy: It copies the packaged code to the remote repository for sharing it with other developers. | |||||||||||
mvn archetype:generate: This command is used to generate a new project from an archetype, which is a template for a project. This command is typically used to create new projects based on a specific pattern or structure. | ||||||||||||
mvn dependency:tree: This command is used to display the dependencies of the project in a tree format. This command is typically used to understand the dependencies of the project and troubleshoot any issues. | ||||||||||||
52 |
pom.xml file :- |
maven complier :- | ||||||||||
source > means complied from |
1.8 |
R.click on pom file can also make it run as like mvn commands |
ok | |||||||||
target > means compiled to |
1.8 |
ok | ||||||||||
<dependencies> |
selenium server 3.141.59 |
ok | ||||||||||
cucumber maven dependencies > |
cucumber jvm : java 6.10 |
ok | ||||||||||
cucmber jvm : Junit 6.10 |
ok | |||||||||||
Masterthought 4.0.0 |
ok | |||||||||||
Junit 4.13 |
ok | |||||||||||
<build> <plugin Management> <plugins> |
maven compiler 1.8 | |||||||||||
maven surefire plugin 3.0.0-M9 |
This is used to run TestNg/cucumber etc. | |||||||||||
exec-maven-plugin – 1.1.1 |
To execute code from java main method | |||||||||||
<phase> test => means mvn test | ||||||||||||
<goal> java => means execute from src/main/java | ||||||||||||
<mainClass> com.test.createDeletebookmark => means packageName ClassName | ||||||||||||
if that class in src/test/java then code is => <callsPath>src/test/java | ||||||||||||
pom file > Run As > Run configuration > Maven build > name_config> Goals> clean compile test | ||||||||||||
for extent report :- adapter are the enhanced version of reports |
<dependency> tech.grasshopper | |||||||||||
extent report – cucumber6-adapter | ||||||||||||
extent report can be create in .pdf file :- need to add additional file in src/test/resources > (project is cucumber maven6) i.e. extent.properties & extent-config.xml |
extent.properties > |
give path here for config file, start = true means for pdf, spark there for html report & json report can also generate etc | ||||||||||
extent-config.xml > |
this about dark theme etc of report | |||||||||||
add 3 more dependencies to pom :- | ||||||||||||
apache.pdfbox –>> 2.0.24 | ||||||||||||
github.vandeseer | ||||||||||||
com.github.ralfstuckert.pdfbox-layout –>> for this need to add exter repo > |
<repositories> jitpack | |||||||||||
3rd step is add plugin code in test runner file :- | ||||||||||||
plugin='”com.aventstack.extentreports.cucumber.adapter.ExtentCucumberAdapter:” |
can use scenerio.log and scenario.attach in this report | |||||||||||
can run 2nd/other .xml file thru runa as run config file and giving this command in goal :- |
-f other_pom_file_name compile test | |||||||||||
53 |
Jenkins :- |
2.332.3 version is good whic required jdk 11 & above |
download lts – generic war file | |||||||||
jenkins have war file, meand web archieve file |
if to give higher jdk version only to jenkins then set path from terminal in jenkins folder:- |
set path = “c:\programfiles….jdk-11\bin” | ||||||||||
it has UI + Plugins |
then run jenkins with java -jar jenkins.war | |||||||||||
mainly used for schedule + reporting + email |
intall suggested plugins | |||||||||||
If to eliminate all Jenkins data then delete .jenkins folder from harddisk under Users etc |
global tool configuration > Add jdk & Add Maven | |||||||||||
54 |
Job Creation from Jenkins :- |
New Item > Name it > Free style project |
Configure it > |
Build :- 1) > |
Execute Window batch…( to run command from terminal/cmd prompt) :- | |||||||
echo “Hello” –> it serve to print in command prompt | ||||||||||||
2) > |
Top level Maven Target :- | |||||||||||
Select Maven Version | ||||||||||||
Goal > clean compile test | ||||||||||||
Copy Project to Jenkins workspace > |
copy all files from any project of eclipse and paste in .jenkins>job_name>workspace> paste > |
But first run the job like build now to create workspace folder under .jenkins folder |
3) Build Triggers > |
Build periodically –> get help from schedule | ||||||||
* –>> for Minute | ||||||||||||
From Manage Jenkins > |
Can install cucmber reports plugin |
* –>> for Hour | ||||||||||
* –>> for day | ||||||||||||
* –>> for Month | ||||||||||||
* –>> for Days of week | ||||||||||||
4) Post Build Actions > |
Select cucmber reports :- | |||||||||||
Advanced Section > Json Report path > reports/htmlreports/ |
> Json report and html report should be in same folder to generate cucumber report | |||||||||||
include patter > **/*.json (already predefined) | ||||||||||||
5) Post Build Actions > |
Select Editable Email Notification :- |
First give email settings in Manage jenkins | ||||||||||
give attachment path | ||||||||||||
6) Post Build Actions > |
HTML publisher for extent reports :- | |||||||||||
use script console which is inside Manage node & builds, this save the script console code to apply css to extent report permanently under system information |
Manage Jenkins-> Manage Nodes-> Click settings(gear icon)-> click Script console on left and type in the following command: System.setProperty(“hudson.model.DirectoryBrowserSupport.CSP”, “”) and Press Run. If you see the output as ‘Result:’ below “Result” header then the protection disabled. Re-Run your build | |||||||||||
55 |
Selenium Grid :- |
Its component of Selenium suite and use Hub / Node concept |
To start Hub manually under the folder where selenium server jar kept, give terminal command :- |
To start Node manually under the folder where selenium server jar kept on other machine or on same machine, give terminal command :- | ||||||||
Version 3 |
java -jar selenium-server-standalone-3.141.59.jar -role hub |
< Hub started at standard port on 4444 |
java -jar selenium-server-standalone-3.141.59.jar -role node -port 5555 -hub http://localhost:4444/grid/register/ |
< Hub started at standard port on 5555 | ||||||||
Use for executing test simultaneously on different machines or on same machine |
java -jar selenium-server-standalone-3.141.59.jar -role hub -port4445 |
< If to start on specific port |
java -jar selenium-server-standalone-3.141.59.jar -role node -port 5556 -hub http://localhost:4444/grid/register/ |
< Hub started at standard port on 5556 | ||||||||
keep hub running while executing the test case |
keep node running while executing the test case | |||||||||||
56 |
Changes in code to execute Test case thru Hub & node :- |
1) Extend Thread class in the code class |
6) Create run class which have main method | |||||||||
Individual classes have for Thread for 2 test cases and parallel run main method class |
2) provide DesiredCapabilities in code class |
7) under main method write code like CodeclassName.start(); |
< start() here call to run method written in code class which then call to execute() | |||||||||
3) Create WebDriver driver = new RemoteWebDriver( url, capabilities) |
< url here to give for hub & capabilities is the object of DesiredCapabilities class | |||||||||||
4) may give name to method as execute() under which code written for Test case | ||||||||||||
5) Write run() method inside this class and call to execute() under this method | ||||||||||||
57 |
CmdUtility class :- |
This class can be use to start Hub & node programatically and to kill those as well. | ||||||||||
57 |
Running cucmber project in parallel :- |
Need to do chnages in pom file > |
add exec-maven-plugin > <phase> Validate | |||||||||
Have project for this cucmber Maven run parallel |
under <configuration> add forkCount>10 |
This means 10 instance can be create for JVM machine | ||||||||||
inside forkCount : give reference if TestRunner files | ||||||||||||
Then run pom file as Maven test | ||||||||||||
Can run in the end End all process class to stop opened hub & node | ||||||||||||
Hub & node can be start from Scnerio/feature file by passing port from there | ||||||||||||
58 |
POM :- (Page Object Model) |
Its design pattern | ||||||||||
With Page Factory |
@FindBy or @FindBys and then pagefactory.elementsint() |
@FindBy(XPATH=” “) WebElement ele1 |
@cachehookup –>> |
Save locators in cache if some webelement remains on all pages so that it cant need to find again and again | ||||||||
without Page Factory > |
Use of By class > |
This Page clas constructor inside value assigned to variables of By class and driver sent to this constructor from code class |
@FindBys(@FindBy(css=” “)) | |||||||||
59 |
GIT :- |
Git Bash in windows installed along with the Git installation and it is terminal for linux commands or can say for mac commands as mac build on linux | ||||||||||
Stages for Git :- |
Untracked |
Unmodified |
Modified |
Staged | ||||||||
Files which are new |
Files which are already with Git and not modified |
Files which are already with Git and but modified |
Staging have 2 steps :- |
First Add file to git which means make file ready for screenshot | ||||||||
Commit File, This means File screenshot created to send to remote repo | ||||||||||||
Push files, Means send commited file to repo | ||||||||||||
Commands :- 1) |
git init |
<< In the project folder in terminal | ||||||||||
2) |
git config user.name “kamal” | |||||||||||
3) |
git config user.email “email” | |||||||||||
4) |
git status | |||||||||||
5) |
git add src/com/… OR git add -A |
<< to add single or all files | ||||||||||
6) |
git commit -m “message” | |||||||||||
Commands for .gitignore :- |
Open Git Bash Terminal :- | |||||||||||
touch .gitignore |
<< In terminal | |||||||||||
Open .gitignore file created in project folder :- |
Add the file and folder there which need to ignore like \bin or bin\ | |||||||||||
Add this .gitignore file & commit it too | ||||||||||||
Commands to revert commits which already done :- |
git checkout src/com….. OR git checkout -f |
to revert single or all files after commit | ||||||||||
Other commands :- |
git log |
<< show last commit ID’s | ||||||||||
git log -P -1 or -2 |
<< show last commit 1 or from last 2 commits | |||||||||||
git show id….. |
<< show what commit thru that id | |||||||||||
Commands for Git repo :- |
public / private repo :- |
10 people can colaborate on free version for private repo |
copy https url for created repo of private nature | |||||||||
in terminal > |
git remote add origin pasteURL | |||||||||||
git remote -v |
<< tells about the added repo url | |||||||||||
git push -u origin master |
<< to push the commit to remote repo |
>> create SSH key before to this step as mentioned in ppt | ||||||||||
run > ssh-keygen… command in terminal | ||||||||||||
press some enters | ||||||||||||
run 2 more commands in bash terminal | ||||||||||||
copy the id_rsa.pub thru terminal command | ||||||||||||
Go to github website, add copied key there | ||||||||||||
copy ssh url to clone that project | ||||||||||||
change repo by > git remote set-url origin pasteURL | ||||||||||||
Old Git Data :- | ||||||||||||
1 |
Git is version control tool & GitHub is code repositery integrated with Git |
BitBucket – its like GitHub (Code Repositery). GitHub is open source and use by public where as Bitbucket is use by Enterprises | ||||||||||
2 |
Git Commands to run on Terminal for code pull, status, add, commit, push & merge |
Steps :- | ||||||||||
Engineer PULL the latest code from Master Branch to local machine in some GIT branch | ||||||||||||
Engineer ADD the code changes to GIT from working branch – Development / QA Branch | ||||||||||||
Engineer COMMIT all the modifications/addition to GIT from working branch | ||||||||||||
Then After PUSH the code/freeze code to GIT Repositery | ||||||||||||
Raise PR (Pull Request) to Merge the Code from GITHUB Working Branch to Master Branch | ||||||||||||
Lastly Merge the code from Working Branch to Master Branch from where code finally deploy at Production Server | ||||||||||||
Jenkins then run the Test Scripts Code deployed at Production Server | ||||||||||||
3 |
Git Terminal Commands :- |
1) git branch |
to know the git branch name in which currently working | |||||||||
2) git status |
to know the git status like anything pending from commit from your side code changes/modifications and to see any new file pending to add | |||||||||||
3) git pull origin master |
to pull the latest code from Master Branch with all the changes done by other persons too to the local machine | |||||||||||
3.1) git pull |
to fetch the latest code from master branch (can also do like this) | |||||||||||
4) git checkout -b HorizontalDynamicRail |
to create new branch & here HorizontalDynamicRail is the branch name | |||||||||||
4.1) git checkout master |
Switch to other branch, master is the branch name here | |||||||||||
5) git add . |
to add new files to Git | |||||||||||
5.1) git add file_path/file_name in project |
to add specific file | |||||||||||
5.2) git diff file_name |
to be use before commit if to see what changes occurred in file wrt old file in GIT | |||||||||||
5.3) git add -u |
to add only modified files & skip untracked / new files to git | |||||||||||
6) git commit -m “type message here for what is commiting” |
to commit all changes (which are with Git Status) to your Git Repository so that same can be merge with Master Branch | |||||||||||
7) git merge master |
Merge branch code to Git Repositery master branch | |||||||||||
8) git push origin branchname |
to send your Git Repositery code to Origin Master branch, to send all the changes & freeze the code and send further for Deployment | |||||||||||
9) git branch -rd Origin/DIGCON-380 |
to delete Remote Branch, Origin/DIGCON-380 is the branch name | |||||||||||
10) git branch -a |
show all branches | |||||||||||
11) git branch -d branch name |
delete local branch | |||||||||||
12) git branch -D branch name |
force delete local branch | |||||||||||
13) git clone https://stash…….. complete url link |
to copy the project in Git Repositery | |||||||||||
14) git checkout –. |
Undo local changes so that things become uncommit (like no change to commit) | |||||||||||
Examples :- | ||||||||||||
cd git |
shift to git directory | |||||||||||
cd cms-automation |
shift to cms-automation directory | |||||||||||
4 |
Other Terms > |
term stash |
to hold changes in code | |||||||||
term clone |
for new project on your computer | |||||||||||
Open GitHub / Bitbucket in browser like stash.mynmg.com/projects/CMSAUT/repos/cms-automtion/browse |
In Bitbucket UI > Merge code here to Master Branch | |||||||||||
Change to Fallbook from SmokeRegression before checkin |
to run test > cd git, cd cmd-automation > ./gradlew clean chromeTest -Dgeb.grid=local -Dgeb.localBrowser=chrome -Dgeb.env=dev-int -Dtest.single=V2OverlapingImages test -Dgeb.selector=SmokeRegression | |||||||||||
git clone http_url |
this clones copy of git repo on local machine in which flder code is to save’ | |||||||||||
60 |
Code to read data from Excel File :- |
import org.openqa.selenium.By; import org.testng.Assert; import org.testng.annotations.AfterMethod; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; public class ExcelExample{ @Test(dataProvider=”testdata”) public void demoClass(String username, String password) throws InterruptedException { System.setProperty(“webdriver.chrome.driver”, “Path of Chrome Driver”); Webdriver driver = new ChromeDriver(); driver.get(“<a href=”https://www.browserstack.com/users/sign_in</a>”); driver.findElement(By.name(“user[login]”)).sendKeys(username); driver.findElement(By.name(“user[password]”)).sendKeys(password); driver.findElement(By.name(“commit”)).click(); Thread.sleep(5000); Assert.assertTrue(driver.getTitle().matches(“BrowserStack Login | Sign Into The Best Mobile & Browser Testing Tool”), “Invalid credentials”); System.out.println(“Login successful”); } @AfterMethod void ProgramTermination() { driver.quit(); } @DataProvider(name=”testdata”) public Object[][] testDataExample(){ ReadExcelFile configuration = new ReadExcelFile(“Path_of_Your_Excel_File”); int rows = configuration.getRowCount(0); Object[][]signin_credentials = new Object[rows][2]; for(int i=0;i<rows;i++) { signin_credentials[i][0] = config.getData(0, i, 0); signin_credentials[i][1] = config.getData(0, i, 1); } return signin_credentials; } } |
AND |
import java.io.File; import java.io.FileInputStream; import org.apache.poi.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook; public class ReadExcelFile{ XSSFWorkbook work_book; XSSFSheet sheet; public ReadExcelFile(String excelfilePath) { try { File s = new File(excelfilePath); FileInputStream stream = new FileInputStream(s); work_book = new XSSFWorkbook(stream); } catch(Exception e) { System.out.println(e.getMessage()); } } public String getData(int sheetnumber, int row, int column){ sheet = work_book.getSheetAt(sheetnumber); String data = sheet.getRow(row).getCell(column).getStringCellValue(); return data; } public int getRowCount(int sheetIndex){ int row = work_book.getSheetAt(sheetIndex).getLastRowNum(); row = row + 1; return row; } |
May the easiest way also available |