Java Selenium
Java Selenium
Java Selenium
Type of method
Default
Parametrised
return type
OOPS concept
When any requirements come to architect, then he/developer will not work on that directly. Java
Architect will first define the functionality.
In Java,
Abstraction can be achieved by 2 ways
In this abstract class we can define abstract methods and concrete methods
We define with and without body method in abstract class and treat that class as parent and now we
need to make another class child and need to inherit by keyword 'extends' and we need to give body to
parent method which was without body.
And then we need to make object of child class and we can call child method and parent method both.
Interface:- It is like a class (It's a blueprint of the class), not fully class
public interface interface1
{
We define without body method in interface and treat that as parent and now we need to make another
class child and need to inherit by keyword 'implements' and we need to give body to parent method
which was without body.
And then we need to make object of child class and we can call child method and parent method both.
Static keyword
For this we need to create a variable a and we make a method and use a in that method because a is
global as it is defined in class.
We will make a method to increment and then in main method we will create the object and call the
increment method and it will display 1 and a is not initialized in class and by default global values have
default value of 0.
Now, we will create another object for that same class and call that same method and again output will
be 1.
As every object is getting separate memory, and that's why different object starts with 1 whenever any
new object call this increment method. (Memory will be allocated at object level)
If we call this method with same object, then it will increment the value by 1 every-time we call the
function.
When class loads, earlier we have studied that whenever a class object is created only then memory
will be allocated but now in this case (when we define static methods or static variables), memory will
be created as soon we define them, no need to create object in this case.
In case of static method call, we don't need to create object of class as we can call static method from
main method by class_name as main method is static too and static to static we can call by class_name.
class_name.method();
Like same if there is any static variable a then we can call that variable directly as well.
syso(class_name.a);
Calling
There is a data type int and there is a class corresponding to int which is Integer
float – Float
As in java, we need to create object of every class but while declaring int value we just give it directly
int a;
no need to create a class.
int a = 12;
Benefit
String s = “123”;
String is a class and int is data type and we want to convert String to int
For conversion, w need to use class Integer
int a = Integer.parseInt(s);
syso(“a”);
Now, a contains 123 (int)
Above, Integer is a Class and parseInt is a method and we are calling it like class_name.method
As main is static and Integer.parseInt(s); is also static and static to static, we can call it by class_name.
Double/Nested Loop
Loop in loop.
File Handling
First of all, we have to make a connection with a file from which we need to read data by using:
File class.
Now we use while loop as we don't know how many times this loop will execute.
Throws exception.
syso((char)a);
to read line by line we use BufferedReader Class like above and it is dependent on FileReader as file
reader is giving us character by character and buffered reader is converting them in line.
String s;
While((s = br.readLine())!=null)
syso(s);
Will start with file class to make a connection and this will create file when we want to write data in a
file. If file is already present, then it will overwrite that file else will create a new file.
In order to print line by line and to pass new line within a file, we will use BufferedWriter class.
Append in a file
Exception Handling
When that condition comes, control will be out of the program and program will be terminated and no
code will execute after this type of condition.
Eg:-
syso(“First Line”);
int a=5/0;
syso(“Second Line”);
In the above program, output will only be First Line and after that divide by zero exception comes and
program will get terminate and second line will not get print.
Exception is a class in java.
And to inherit class we use 'extends' keyword.
Checked Exceptions
Unchecked Exceptions
If we think at particular point in code, if an exception might comes, we can put that code in try block.
And catch block will handle the exception.
try
{
int a = 5/0;
}
catch(Exception e)
{
syso(“Exception handled”);
}
Try will throw an exception when it comes and catch block will handle that exception.
When an exception comes, try will throw an exception and catch block will handle and execute else
catch block will not get executed.
Basically,
Try block will throw an object that will go inside e where e is reference variable and Exception is a
class and try block is throwing an object.
catch(Exception e)
{
e.printStackTrace(); //Method
}
Finally
try
{
int a = 5/0;
}
catch(Exception e)
{
syso(“Exception handled”);
}
finally
{
syso(“final block”);
}
We can do that work with finally block like we want to close the connectivity with database or we want
some resources to get free in last.
Basically, what we want that should happen no matter what , we can put that in finally block.
We can not write try alone, there must be at-least catch or finally or both with try.
eg.
try
catch (ArithmeticException e1)
catch (ArrayIndexOutofBoundException e2)
catch (NullPointerException e3)
catch (Exception e)
Q. Can we put try catch inside try catch ?
A. Yes !
try
try
catch
catch
So, in this case what happens is if there is any failed scenario, exception comes and catch will take
screen-shot and it get executed, otherwise program will execute normally without any failed scenario.
In normal terms, we can put even all the code in try block too. Wherever, we can think exception can
comes just put that code in try block.
try
{
throw new myException(“message”);
int a = 5/0;
}
catch(Exception e)
{
syso(“Exception handled”);
}
finally
{
syso(“final block”);
}
throw is basically for one type of exception at a time but with throws we can handle multiple
exceptions at a time.
Class 7
String Handling
What is String ?
String s = new String (“abc”); // Memory will be allocated in heap in this case.
String s1 = “abc”; // Memory will be allocated in SCP in this case. (String Constant Pool)
String s1 = “abc”;
String s2 = “abc”;
Now in above example s1 object is created and point to abc in SCP. (abc is stored in SCP).
Now s2 object will not get created and will point to same abc in SCP. (because it is already present)
Now it will create another object s3 and that will point to Abc in SCP.
But in case of Heap whether string is same or not, new object will get created every-time.
String Comparison
== (double equal)
It will compare the address. (Which object is pointing to that value, object is same or not)
Eg:-
String s1 = “abc”;
String s2 = “abc”;
String s1 = “abc”;
String s2 = new String (“abc”);
S1.equals(s2)
just compare the values, does not matter if it is available in heap or SCP.
S1.compareTo(s2)
It will compare character by character wherever the first diff comes, it will give the difference between
their ASCII values.
Now,
for loop
String s1 = “Deepak”;
for (int i=0; i<s1.length(); i++)
{
syso(s1.charAt(i));
}
length is a variable in case of array of string and length() is a method in case of string.
StringBuilder
syso(sb);
StringBuffer
API
int r = ws.getRows();
int c = ws.getColumns();
Class
WorkBook
Sheet
Cell
Method
getWorkbook()
getSheet()
getRows()
getColumns()
getCell()
getContents()
Write into Excel(.xls)
WritableWorkBook wb = Workbook.createWorkbook(f);
WritableSheet ws = wb.createSheet(“Jeet”, 0);
Class
WritableWorkBook
WritableSheet
Label (jxl.write)
Method
createWorkbook()
createSheet()
addCell()
write()
close()
Class 8
Apache POI
In this pom.xml, if we do entry of any dependency, then its corresponding jar files will get downloaded
automatically and other jar files as well which are interdependent to that jar.
Eg:-
Now, we will make a java project, and make a package in source and then class in package.
Now right click on project → configure → convert to Maven Project and finish
Then we will get pom.xml file.
Add dependency of jar files which we need, and maven itself maintain jar files and the benefit is if we
need one jar and that jar is further using any other jars, so maven itself maintains all the jars on its own.
In pom.xml file → we need to add tag 'dependencies' (open and close tag) both and in between we need
to add dependencies and press control S.
After saving, we will get folder of Maven dependencies.
Maven maintain .m2 folder and in that all the jar files are maintained, which we can access directly by
run command window and typing .m2
In some companies, proxies are there and due to which jar files wont get download properly and we
can check this by the size of jar files and it is 1kb and 2kb like, so these types of problems can come
and above is the solution.
Or in worst case we have to maintain all the jar files in .m2 folder like written above.
Or else bypass proxy, eg:- where .m2 folder get created there we can maintain setting.xml file and
bypass proxy.
Maven maintain jar files of dependencies and build the project means compile or run the project.
validate - validate the project is correct and all necessary information is available
compile - compile the source code of the project
test - test the compiled source code using a suitable unit testing framework. These tests should not
require the code be packaged or deployed
package - take the compiled code and package it in its distributable format, such as a JAR.
verify - run any checks on results of integration tests to ensure quality criteria are met
install - install the package into the local repository, for use as a dependency in other projects locally
deploy - done in the build environment, copies the final package to the remote repository for sharing
with other developers and projects.
Read from .xlsx file
int r = xs.getPhysicalNumberOfRows();
XSSFRow xr = xs.getRow(i);
for(int j=0; j<xr.getPhysicalNumberOfCells(); j++)
{
XSSFCell xc = xr.getCell(j);
System.out.println(xc.getStringCellValue());
}
}
Class
File //Connection
FileInputStream //dependent on File
XSSFWorkbook //dependent on FileInputStream
XSSFSheet //dependent on XSSFWorkbook
XSSFRow //dependent on XSSFSheet
XSSFCell //dependent on XSSFRow
Methods
Benefit :- Loop will execute as many times as many cells are there and if there is any cell as empty
then it will get error.
Optimize way of reading, how many cells are there only till that time loop will execute.
Write to .xlsx file
XSSFRow xr = xs.createRow(i);
for (int j=0; j<5; j++)
{
XSSFCell xc = xr.createCell(j);
xc.setCellValue("Jitender");
}
xw.write(fo);
fo.flush();
fo.close();
File //Connection
FileOutputStream //dependent on File
XSSFWorkbook // Not Dependent
XSSFSheet //dependent on XSSFWorkbook
XSSFRow //dependent on XSSFSheet
XSSFCell //dependent on XSSFRow
Methods
Class 9
Junit
It's a unit testing tool which is used to run the classes and which do not have main method.
Developers also use it and the benefit of Junit is if we do all the code in main method, it becomes
lengthy so in order to avoid this – we can write the code and run it with the help of Junit.
With the help of Junit – we can break the code and run in any sequence what we want.
Annotations will be applied on the methods. Annotations are the metatag which defines the order of
execution.
Both Testng and Junit are Testing framework used for Unit Testing.
TestNG is similar to JUnit. Few more functionalities are added to it that makes TestNG more powerful
than JUnit.
TestNG is a testing framework inspired by JUnit and Nunit.
Add these 2 jars to work with Junit
Annotations
----------------
Sequence
-------------
BeforeClass
Before
Test //In alphabet order – execution takes place
After
Before
Test //In alphabet order – execution takes place
After
AfterClass
Switch
int a = 10;
int b = 10;
int z;
char c = '*';
switch (c) {
case '+':
z=a+b;
System.out.println("Addition is: "+z);
break;
case '-':
z=a-b;
System.out.println("Subtraction is: "+z);
break;
case '*':
z=a*b;
System.out.println("Multiplication is: "+z);
break;
case '/':
z=a/b;
System.out.println("Division is: "+z);
break;
default:
System.out.println("Invalid Opeartor");
break;
}
Class 10
Selenium Introduction
Selenium is a web based applicaion automation tool. It is a open source tool. It supports multiple
languages(Java/python/c#). It supports multiple platforms like different browser (windows/linux). It supports
android and ios automation.
Apium is the tool in the market for Android and ios automation, which use selenium as well in backend. (use
one of the components)
Disadvantages
1. lots of programming required (there are some tools in which we need to learn any programming eg --> QTP,
Katalon Studio etc. etc. (these work on record and play concept))
2. lots of configurations required
3. no support - when it comes initially
4. support only web based applications
1. Selenium IDE
2. Selenium RC
3. Selenium Webdriver
4. Selenium Grid
Selenium IDE
Selenium RC
Selenium Grid
Interview question
Webdriver is a interface or an API (built in methods and classes), and to inherit interface we use implements
keyword.
Classes are implementing the webdriver interface.
Like - Chromedriver - selenium
Firefoxdriver - selenium
IEdriver - selenium
iosdriver - apium
androiddriver - apium
First of all, we need to identify the web element UNIQUELY on the web page and then we can perform action
on the same.
eg --> on username we need to pass some value (.send)
on button we need to click (.click)
1. id
2. name
3. classname
4. css
4.1 tag with id --> tagname#idvalue
4.2 tag with classname --> tagname.classvalue
4.3 tag with attribute --> tagname[attributename='attributevalue']
4.4 tag with class with attribute --> tagname.classvalue[attributename='attributevalue']
4.5 tag with innertext --> tagname:contains('innertextvalue')
Class 11
Drop-Down
If it is inside the select tag --- then use the Select class
If it is inside some other tag apart from select tag --- then we will use the keyboard key (arrow down) ---
Actions class
1. selectByIndex
2. select ByValue
3. selectByVisibleText
Actions Class
--------------------------------------------------------------------------------------------------------
a.keyDown(Keys.CONTROL).click(login).keyUp(Keys.CONTROL).perform();
Class 12
Collection
Set
List
1. ArrayList -- searching fast on the basis of indexing, insertion deletion slow and tough
2. LinkedList -- searching slow because of nodes, insertion deletion fast and easy
node - info (data) and linked part (address of next node) and last one will contain null
Map
1. HashMap -- will not maintain the insertion order, and we can give duplicate keys but in this case latest value
will come to that key. And also we can give duplicate values(that is ok)
HashMap<Integer, String> hm = new HashMap<Integer, String>();
Set<Integer> all = hm.keySet();
2. LinkedHashMap -- will maintain the insertion order, and we can give duplicate keys but in this case latest
value will come to that key. And also we can give duplicate values(that is ok)
3. TreeMap -- ascending order but as per key, and we can give duplicate keys but in this case latest value will
come to that key. And also we can give duplicate values(that is ok)
To Locate:-
Example - Youtube
Class 13
Modifier Key
Use of collection
System.setProperty("webdriver.chrome.driver", "C:\\Users\\jitender.ahuja\\Downloads\\Jar
Files\\chromedriver_win32\\chromedriver.exe");
driver.get("https://www.facebook.com");
driver.manage().window().maximize();
a.keyDown(Keys.CONTROL).click(login).keyUp(Keys.CONTROL).perform();
int i=0;
for(String s : allwindows)
{
i=i+1;
if (i==2)
{
driver.switchTo().window(s);
break;
}
}
driver.switchTo().window(currentwindowaddress);
driver.close();
Verification Points
System.setProperty("webdriver.chrome.driver", "C:\\Users\\jitender.ahuja\\Downloads\\Jar
Files\\chromedriver_win32\\chromedriver.exe");
driver.get("https://www.facebook.com");
driver.manage().window().maximize();
driver.close();
Class 14
XPATH
Dynamic - Change
Static - Fixed
Techniques
Driver Navigation
driver.get("url");
driver.navigate().to("url");
driver.navigate().back();
driver.navigate().forward();
WAITS
Wait is an interface.
Normal wait
Thread.sleep(1000); //Add throws declaration
// Will wait for next statement for the mentioned time no matter page is launched or not
Implicit wait
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
//Will wait for all the find elements below this implicit wait with a max of mentioned time and if find before
time, it will go forward.
Explicit wait
Wait is an interface.
WebElement is an interface.
WedDriver is an interface.
//Will wait for elements under condition with a max of mentioned time and if find before time, it will go
forward.
For Example:-
Fluent Wait
Fluent wait is a part of the Explicit Wait type. Fluent wait instances define the maximum amount of time to wait
for a condition, as well the frequency with which to check the condition.
IFrame
If on a page there are many windows and in this window if there is one button and if we need to click that
button we can not locate that button, because at that time control is in main window.
So, now here comes the concept of IFrame and we need to switch the control of driver to the window where
the button is.
eg:-
HTML be like,
<HTML>
<HEAD>
<TITLE>
<BODY>
<DIV>
<IMG>
<IFRAME ID = "XYZ">
<HTML>
<HEAD>
<TITLE>
<BODY>
<BUTTON ID = "ABC">
Interview Question
Class 15
TestNG -- It is a unit testing tool which is used to run the classes which don't have main method.
It needs to be set up unlike junit.
It is based on annotations
Annotations will be applied on menthods
Annotations are the meta tag which defines the order of execution
@Test----it is mandatory
@BeforeSuite
@BeforeTest
@BeforeClass
@BeforeMethod
@Test
@AfterMethod
@AfterClass
@AfterTest
@AfterSuite
@BeforeSuite
@BeforeTest
@BeforeClass
@BeforeMethod
@Test
@AfterMethod
@BeforeMethod
@Test
@AfterMethod
@AfterClass
@AfterTest
@AfterSuite