0% found this document useful (0 votes)
10 views

Selenium Java

Selenium is an open source tool that supports web application testing across various browsers and operating systems. It supports various programming languages and has tools like IDE, WebDriver, and Grid. Selenium tests can be written using Java, executed in parallel, and detailed reports generated.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views

Selenium Java

Selenium is an open source tool that supports web application testing across various browsers and operating systems. It supports various programming languages and has tools like IDE, WebDriver, and Grid. Selenium tests can be written using Java, executed in parallel, and detailed reports generated.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 29

Selenium is a Suite of Software tools. (Java has Lib of classes and methods organized in Packages).

It supports only web applications.

Open source.

It supports various operating environments. (OS)Windows, Linus, Mac

It supports various browsers, MF, Chrome, IE, Safari and Opera.

Selenium IDE supports only Mozilla FireFox(MF) only.

Selenium Gird – Its for test execution.

Supports various programming languages such as Java, Jscript, OOPs, Python , c#, Perl, Ruby, PhP

It came in 2004.

2006 selenium web driver

2008 – Merging web driver and RC. V2.0

Selenium 1:

IDE + RC+ Grid

Selenium 2 :

IDE +RC+Web Driver + Grid

Selenium IDE => Record and play back. Its not an independent tool. Its firebox plugin.

Element locator for object recognizing and selenese for execution.

Default format in html.

Demerit for IDE:

supports MF browser only.

It doesn’t support programming languages to enhance TC.

Did not support data driven testing.

Selenium RC :

Selenium Web Driver: It’s a programming interface to create and execute automation tc.

It doesn’t have IDE.

UFT has IDE as well as programming interface.

To recognize objects and performing operations we use programming approaches.

It supports Java, c#, Perl, Python, Ruby and PhP.

Using Object locators.


Ex: Automation done using Chrome, if we want to execute the script for IE, how to perform. (We need to
set browser driver path)

Default driver is Mozilla Firefox.

If it is another browser, we need to download the browser driver and set the path.

Demerits:

It doesn’t generate detailed test reports. It generates summary only.

No centralized maintenance of objects/elements.

Selenium Grid:

Its only for test execution. It did not support test automation design.

It’s used for parallel execution (multiple browsers, operating environments and multiple machines)

Selenium gird 2 supports, selenium RC test and Selenium web driver tests.

*** Selenium Web Driver, Java Programming, testing frame work (junit or testNG – exe batches,
generate detailed reports, grouping the TC).

Supporting environments:

Operating Environment: It will support all OS.

Application environment: CUI based applications Command user interface applications. (Selenium does
not support CUI based applications)

Windows based applications (1 tire application and 2 tire). Selenium does not support windows-based
applications.

Web based – Selenium supports web-based applications.

Mobile applications – Selenium supports – Native (Selenium does not support), Hybrid (Selenium does
not support), web apps (Selenium supports)

Programming environment: Java, Perl, python, c#, ruby and PHP.

Browser environment: it supports all browsers.

Selenium License: Open source. But it has license. All selenium projects are released under Apache 2
license. (anyone can download and use all selenium projects with free of cost, anyone can modify the
source code, distribute the source code anyone, selling modified source code is not allowed)

Testing frame works, and other tools used in selenium:

J-Unit: Unit test frame work. it can be used as a test runner in selenium.

TestNG: it can be used as a test runner in selenium.

Mozilla Plug Ins: Fire bug and Fire path. – to spy elements in Firebox.
IE and Chrome – we have built in developers’ tools F12.

Selenium Environment setup:

Eclipse IDE for code development. – create and execute any programs.

Add selenium Jar files.

Install testing/Junit testing frame works.

 Choose selenium tools. Web Driver.


 Programming language.
 IDE tools.
 TestNG frame work.
 If required, for cross browser, we need to install browser drivers.
 Inspecting elements, needs to install Firebug and Fire path.

Configure selenium:

 Download eclipse IDE and install/extract.


 Download Java software and install. (JDK)
 Set environment path in OS.
 Download selenium web driver Java bindings and add web driver JAR files to java projects in
eclipse IDE. (seleniumhq.org)
 Download and install firebug and firepath from Mozilla.
 Download IE, Chrome and etc if required.
 Download and install TestNG from Eclipse IDE.

Advantages of selenium:

Open source.

Multiple programming language.

Cross browser. Many operating environments.

Multiple browser (Parallel execution)

It is consuming less hard ware resources.

Disadvantages of Selenium:

 Web applications supports.


 No reliable technical supports from anyone.
 No centralized maintenance of objects/elements.
 Difficult to setup and config environments.
 Difficult to use.
 Limited support for image-based testing.
 No tools integration for test management.
 New features may work or not work.
 It doesn’t generate detailed test result.

Selenium Test Process: Life Cycle.

Test planning, test design, generating basic test, enhancing test, running and debugging test,

Analyzing test result and reporting defects.

Doing POC.

element identification – element locators/ web driver methods.

Enhancement: adding Java programming.

Web Driver:

Inserting verification points – using java conditional statements. Also using testNG assertion methods we
can do verification.

Selenium IDE: Using Assert and verify we can do verification.

Parametrization: replacing constant values with parameter. Looping statement to parametrize values.

Synchronization: we can use web driver sync such as wait

Error handling: Handling Expected and un expected errors.

Adding comments: Using java syntax we can add commands.

Running and debugging: Java execution and debugging methods.

Locating and isolating errors called debugging.

Test Run:

Single test run. Batch Test run

Analyzing Test reports and reporting defects: Using TestNG, we can generate detailed test steps.

Selenium 5:

Java for Selenium: Selenium written in Java. Why? Java is platform independent language. More
compatibility. Knowledge sharing is quite easy.

Java topics: Core Java, java fundamental and OOPS. For Test Automation using selenium – Core Java

Core Java Concepts:

Java Fundamentals –(Object Oriented Programming system) and OOPS.

Comments in Java – It supports single line and multiple line comments

1) Data Types is Java: It is a classification of the type of data, that a variable or object can hold in
computer programming. Integer, characters, Constant, string, float, Boolean , logical
2) Two types of data types - Primitive Data types. Reference Data types

3) Java Modifiers- Modifiers are used to access level for classes, variables, methods etc…

Two types of modifiers in Java:

Access modifiers – Default, Public, Private, Protected.

Non Access modifiers- Static, Final, Abstract, Synchronized and etc..

4) Variables in Java: Variable is temp memory used in function. It’s a name location to store temporary
data. Variable stored in primary memory – RAM

Three types of variables in Java – Local, instance, class or static

5) Operators: it used to perform math, comp and logical operations.

Types: Arithmetic Operators, Relational Operators, Bitwise Operators, Logical Operators,


Assignment Operators, Miscellaneous Operators.

6) Flow control statements:

Conditional Statements, Loop Statements

Conditional Statements:

1. If statement, 2. Switch statement

Types of conditions : 1. single condition(Positive, negative) 2. Compound condition or multi


condition(Positive, negative) 3. Nested condition(Positive, negative)

Usage of conditional statements:

1. Execute a block of statement when condition is True


2. Execute a block of statement when condition is True, otherwise execute another
block of statement.
3. Decide among several alternates.
4. Execute a block of statement when more than one condition is True
5. Decide among several alternates. (Switch)

7) Looping statements:

1. Finite Loop – For loop(Scalar variable ), Enhanced For Loop(arrays) 2. Infinite Loop – Do
While Loop(Scalar variable ), While Loop(Scalar variable )

8) Arrays in Java: Array is an object and contains a similar type of values. Java array is Index based. Each
item in an array called as array element. The length of an array is established when the array is created,
and the array length is fixed.

9) Java Methods – also known as functions(Build in and user defined). In object OOPS we use build in
and user defined .

Types: Build In and User defined.


Build In – Number methods, Character methods, String methods, Date and Time methods, Array
methods and etc..

User Defined Methods: 1. Method with Returning value, 2. Method without returning value.

10) Regular Expressions: Formula for matching patterns. A regular exp defines search pattern for strings.
Java provides java.util.Regex Package(Build in Packages)

11) IO Operations and File Handling in Java: The Java.IO Package contains predefined classes to
perform input and output operations.

1. Reading data using input devices. 2. Display output on the console. 3. Read and write text
files and other files.

Using java class, we can handle text files (Flat files – Note Pad). To work with excel we need to
download excel JAR from external.

12) Exception handling in Java – The exception handling in Java is to handle the run time errors.

13) OOPS –

1. Inheritance- reusing

2. Polymorphism

3. Abstraction

4. Encapsulation.

1. Inheritance: is the Mechanism in which one object acquires all the properties and behaviors of
parent object. Using inheritance, we can create classes that are build in upon existing classes. When we
inherit from any existing class, we can reuse methods and fields(variables) from parent class and we can
add new methods and fields also.

Types of Inheritance: Java supports Single inheritance, Multi-level inheritance, Hierarchal inheritance.

Java doesn’t support multiple inheritance.

2. Polymorphism: Performing tasks in different ways. It derived from two Greek words. Poly means –
Many, Morphs – means ways(forms).

Types: 1. Compile Time Polymorphism. 2. Run Time Polymorphism

We can achieve polymorphism though method over loading and method Riding.

3.Abstraction: is a process of hiding the implementation details and showing functionality to the user.

It shows important things to the user and hide internal details. Abstraction focus on what the object
does instead of how it does. Abstraction can be achieved in two ways. 1. Using Abstract class. (0 to
100%) 2. Interface (100%)

4. Encapsulation: it is a process of wrapping code and data together into a single unit. Ex: Capsule –
Mixed of several medicines. It provides control over the data.
Java hierarchies:

1. Java Packages. (Group of similar types of classes, Interfaces and sub packages). Types – 1. Build
In Packages, Ex – IO Packages, Util Package, SQL Package and etc..2. User defined Packages.
2. Interface in Java – It is a collection of abstract methods. It is not a class but like writing a class.
But both are diff concepts.

Java Programming hierarchies:

 Java Project
>>Java Packages
>> Java Class (Program)/Java Interface.

Note: we write java code in the class or interface.

Session 6:

Introduction to Java:

1. Introducing Java
Object Orientated Programming language, it can be extendable, Platform Independent, Simple
and easy to learn, Securable
It can be complied and interpreted. (Writer, Compiler, executing)
Usage of Java:
App development (Desktop App, Web app)
Mobile app development.
Embedded system development.
Smart cards development.
Games development.
Test Automation is secondary purpose.
 Java Syntax rule:
>>Case sensitive language. Java keywords are case sensitive. But data and message is not
case sensitive.
>> First letter of a class name should be upper case.
>> Method name should start with lower case.
>>Java Program file name should match with class name.
>>Java program execution starts from Main method (Build in).1. Build in method, 2. User
defined method. Main method is mandatory for every java program.
>> Every statement/states should end with semi colon symbol.
>>Code blocks enclosed with {conditional, method, loop}(Curly Phrases)
2. Java Environment Setup
Steps:
 Down load JDK and install
 Set environment path(Path variable). System properties – Advanced Setting –
Environment variables – Path – JDK BIN Path
 To check version cmd – Java or Java -version or Javac

Down Load Eclipse IDE and extract.


In test automation using selenium, we use an integrated development environment like eclipse.

Eclipse – it’s a platform to write and execute programs in many languages.

Installation – eclipse.org

How to create Java Program in eclipse:

Step 1: Launch eclipse

Step 2: Create Java Project

Step 3: Create Java Package

Step 4: Create multiple java class under Package (Create Java Class)

In Comp-Program – writing a program – Compile the program (converting high level lang into
machine lang)– execute the program

Step 1: write a program.

Step 2: Compiling the program – go to cmd - change to java program file directory. (changing the
directory in cmd ex. Cd desktop)

Type -- javac Sample.java --- it creates java class file only.

Step 3: Run or execute the program. Go to cmd – type – java Sample

How to edit Java program:

Edit the Java program file. We need to create a Javac - class file. Then run

3. Java Program Structure/Java Syntax

Session 7: Java Program Structure/Java Syntax

 Documentation section(indent) -Optional


 Package declaration statements.
 Import statements. – System.out.println “accd” – build in and user defined lib filcb.
Import build in and user defined libs.
Import java.io.console;
Import java.lang.*;
import – Java keyword to import lib.
Java – pre defined project.
I/O – package
Console – class
Lang.* - import all classes from lang package.
 Class declaration statement –
Public class Sample {
}
Public – Access modifier.
Class – java keyword to declare a class
 Main method – Pre defined method.
- Program execution starts from main method
- Mandatory statement in every java program.
- Public static void main (string [] args)
Public – access modifier
Static – non access modifier.(Use main method without invoking any object )
Void – return nothing
Main – method name.
 Declaration : we can declare variables and constants.
Other statements.
System.out.println(“hello world”);
System-Pre defined class.
Out-object
Println-method
 Code blocks:
o Condition blocks
o Loop blocks
o Method blocks(method declaration before the main method, but we access
methods after main method)

**every normal statement ends with ;

**every code block enclosed with }

Classname objectname = new classname();

Sample Java Program:

//test program

package seleniumtest;

import java.io.console;

import java.lang.*;

public class Sampletest {

//method declaration/creation

Public int multiply(int a,int b,int c){

int result=a*b*c;

return result;

public static void main(String [] args){

int a=10,b=5,c; // variable declaration


c=30;//initialization

final int money = 100; //constant declaration

System.out.println(“additiona of a,b is + (a+b)”); //exp output is addition of a,b is 30

System.out.println(money);//100

System.out.println(c);

//condition block

If (a>b){

System.out.println(“a is biggest”)

Else{

System.out.println(“B is biggest”)

//loop block

for(int d=1;d<=10;d++){

System.out.println(d);

//create object to access methods. Classname objectname = new classname()

Sampletest objTest = new Sampletest;

Int x=objTest.multiply(1,2,3);

System.out.println(x);

=> Comments in Java: comments are English word for code documentation.

Purpose of comments:

 To make the code readable.


 To make the code to disable from execution

Syntax : // - for single line disbale, /* for multiple line disable ….*/
Java Data Types:

Data type is a classification of the type of data, that variable or constant or object can hold in computer
programing.

Ex: character, integer, float, Boolean etc..

** Java supports explicit declaration of data types. – it means we need to specify the data type before
declaring the variable.

Syntax :

Datatype variablename;

Datatype variablename = value;

Datatype v1,v2,v3;

Example:

Int a;

Char b=’c’;

Int a,b,c;

Two type of datatypes in Java: Primitive and Non-Primitive (Reference data types)

Primitive data types: 8 Primitive data types.

1. Integer => byte(8 bits), ex: byte a =10;

=>short (16 bit) ex: a=10000;

=>integer (32bits)ex: int a = 1000000;

=>long (64bits) ex: a=10000000000;

2. Relational Types : numbers with decimal places.

=>float (32 bit) ex: float a=1.23;

=>double(64 bits) ex: double a=123.3454;

3. Character ex: char a = ‘q’;

4. Conditional : Boolean (logical value) ex: Boolean a = True

Non primitive or reference data types – in java are objects and arrays.

Ex: button a = new button(“ok”)

Session 8:

Java variables and Operators.


Modifiers:

It’s keywords, that we add to those definitions to change their meaning.

1. Access Modifiers: we use access modifier to define access control for classes, method and
variables.
Types : 4 types.
Private – it is accessible with in class. Ex: Private int a=100;
Default – it is accessible with in Package. If we did not specify any modifier, it can be treated as
default. Ex: class sample {

}
Protected: it is accessible with in Package. Outside of the package through inheritance only.
Ex: protected class sample{
….
}
Public : it is accessible in everywhere.
Ex: public class sample{
….
}

Modifier With in class With in package Outside of Outside of


package (by sub package
class(inheritance))
Private Y N N N
Default Y Y n N
Protected Y y y n
Public y Y Y Y

2. Non-Access Modifiers. We have many non-access modifiers. But in general, we use three.
1. Static: it is used to create class, methods and variables.
Ex: Static int a=10; // static variable
Static void int add(){ // static methods
..
}
2. Final : it is to finalizing the classes, methods and variables.
Ex: final int a =100; // variable
3. Abstract: (in complete) it is to create abstract classes, methods.
Ex: abstract class sample{
..
}

Java variables: a named memory location to store that temporary data in a program.

1. RAM – Primary 2. Secondary – HDD, and tec..


Declaration of variables: java supports explicit declaration of variables.

Syntax :

datatype variablename;

ex: int a;

datatype variablename=value;

ex: int a=10;

datatype var1,var2,var3;

ex: int a,b,c;

datatype var1=value;var2=value;

ex: int a=10;b=20;

Assigning values to variables:

Initialization and reading.

Ex: int a=100; //initialization

Int a=10, b;

b=a; //reading

Variable naming restrictions(rules):

 Variables are case sensitive


 Variable name should start with a letter or dollar sign or underscore sign.
 Variable name should not match with java keywords (reserved words)
 Variable name must be unique in the scope of declaration
 Variable names should not exceed 255 charactors.

Ex: myvar, MYVAR, $myvar, _myvar,myvar_1;

Types of variables:

1. Local 2. Instance 3. Class or static


Local: it is declared in methods or blocks.
Instance: it is declared in a class but out side of a method or any block.
Class: A variable that is declared as static, it can not be local.

Operators:

Java has many operators. But for test automation we use four operators.

1. Arithmetic
2. Relational – used for comparison
3. Assignment
4. Logical

Arithmetic Operator:

+ => Addition. Operations – numbers for addition. Strings – concatenation.

-=> subtraction. Number subtraction. For negative value also.

*=> multiplication

/=> division

%=> modules. It returns remainder.

++=> increment

--=> decrement

Relational Operators: it returns Boolean or logical result

== equal to

!=

>

>=

<

<=

Logical operators:

1. Logical NOT operator !


2. Logical AND operator &&
3. Logical OR operator ||

Result: it return Boolean results

Assignment Operators:

1. Assignment operator (=) a=10;


2. Add and assign (+=)
3. Subtract and assign
4. Multiply and assign

Int a=10;Result = 10

a+=10; result : a = 20

a-=10; result : 10

a*=10; result : 100


Session 9: flow control

Conditional statements:

Types: If statement , Switch statement.

3 types of conditions.

Single condition if(a>b) or if (!(a<b))

compound condition or multi – if (a>b) && (a>c){} ; if (a>b)||(a>c) ** one else is enough

nested condition: if (a>b){

if(a>c){

if(a>d){

** here we should write 3 else.

Usage of conditional statements:

1. Execute a block of statement when condition is True


2. Execute a block of statement when condition is True, otherwise execute another block of
statement.
3. Decide among several alternates.
4. Execute a block of statement when more than one condition is True
5. Decide among several alternates. (Switch)

Several alternate – else if structure:

If (condition){

//statement

Else if (condition){

//statement

Else{ ///optional

//statement.
}

Execute a block of statement when more than one condition is true.

Syntax : if (condition){

If (condition){

//statements

Decide among several alternates: (Switch case)

Syntax:

Switch (expression){

Case value:

Statements;

Break;

Case value:

Statements;

Break;

Default

Statements;

Java Looping statements:

Loop statements for repetitive execution. For loop structures in Java.(It repeats a block of
statement for specified number of times)
1. For Loop
2. While loop
3. Do while loop
4. Enhanced for loop

For Example: for(startvalue, endvalue, increment/decrement){

Statements

Statements..

}
Program : print 1 to 10 numbers. Print 10 to 1 numbers, Print 1 to 10 numbers except 7.

While Loop: it repeats a block of statement while condition is true.

Syntax:

Initialization

While ( condition){

Statements

..

Do Loop : it repeats a block of statement while condition is true. It executes a block of statement once
before checking the condition.

Syntax:

Initialization

Do

Statements;

} while(condition);

Enhanced for loop:

It executes all elements in an array.(in Java array is object)

Syntax: array declaration;

For(declaration: expression/array){

Statements;

Session 10: Strings and Arrays in Java:

1. String handling in Java


2. Arrays in Java

String handling in Java:

String – is a sequence of character written in double quotes.

How to handle data in Java – numbers – integers-byte, short, int, long and floating/decimal values-float,
double.

Character data types – char.


Boolean data types handling - using Boolean data types.

How to handle strings – in Java String is Object. String may have alphabets, numbers and special chars.
System.out.println("Selenium"); // Selenium)
System.out.println("123Selenium");
System.out.println("Selenium * &123");
System.out.println("1234");

Create Strings:
String myTool="Selenium"; //strinvariable
String [] myTools= {"UFT", "Selenium", "RFT", "LOadrunner"}; // array of
strings

System.out.println(myTool);

for (String tool:myTools) { //to get string array use enhanced array
System.out.println(tool);
}

Operations on strings:

String concatenation: +
String str1 = "Selenium";
String str2 = "Testing";
System.out.println(str1+" "+str2);
System.out.println("Selenium" + 1 + 1 ); //Selenium11
System.out.println(1+1+"Selenium");//2selenium

String Comparison:

1. 2 way comparison
2. 3 way comparison (0, > 0, <0)

String comparison using (== relational operator) double equal to operator. This supports 2 way
comparison. Result will be Boolean result(true/false)

String comparison using equals() method. 2 way


//string comparison using == operator.
System.out.println(str3==str4);//false
System.out.println(str4==str5);//true

//string comparison using equals method

System.out.println(str3.equals(str4));//false
System.out.println(str4.equals(str5));// true

String comparison using compareTo() method. 3 way comparison. (0, < 0, > 0)

//string comparison using compareTo method


System.out.println(str5.compareTo(str6)); //negative value

Arrays: in java array is object. It is an object that holds a fixed number of values of a single data type.

The length of an array is established when the array is created.

Array length is fixed.

Array index starts from zero.

Declaration of arrays:

1st Method:

Datatype arrayname []; //creating array

arrayName = new datatype[size]; // define size

arrayName[0]=value; //assigning value

2nd Method: declaring array with length.

Datatype [] arrayname = new datatype[length];

Arrayname[index]=value;

3rd Method:

Declaring array with length and assign values.

Datatype [] arrayname = { value1, value2, value 3,…};

Example: int [] arrtest = {10,20,30,40};

Creating different types of arrays:

char [] sam = {'a','b','c'}; // array of character


int [] num = {1,2,3,4,5,6}; // array of integers
String [] strval= {"UFT","Selenium","RFT"}; // array of strings
boolean [] blnflag= {true, false}; // array of Boolean

Copy arrays one to other:


int [] num2 = num; // copy array from one to other

Types of arrays:

2 types of arrays in Java. 1. Single dimensional array 2. Multi-dimensional array.

When we want to print multi-dimensional array we can nested for loops.

For (….){
For(…){ }

Advantages/ Disadvantages of arrays:

 Using arrays, code optimization is easily.


 Data can be collected by index.

Disadvantage:

 We can store fixed number of elements only.


 We can’t change the size during run time.

Selenium Class 11: IO Operations and file handling in Java.

1. IO Operation.
2. File handling in Java.
3. Exception handling in Java.

IO Operations:

There are 3 ways to reading input in Java.

1. Scanner – build in class


2. Data input stream
3. Buffered reader

Using Java Util Scanner is the easier way to reading data. Also it includes many methods to check input is
valid to read.
package testexamples;
import java.util.*;
public class IOoperations {
public static void main(String [] args) {
Scanner scanobj = new Scanner(System.in); // system.in is a input stream

//reading the name


System.out.println("Enter ur name");
String name = scanobj.nextLine();
System.out.println("Your name is "+name);// if we use next method
instaead of nextline, it will return one word from the sentence

//reading the name


System.out.println("Enter ur city");
String city = scanobj.next();
System.out.println("Your city name is "+city);

//reading the number


System.out.println("Enter ur number");
long num = scanobj.nextLong();
System.out.println("Your mobile number is "+num);

//reading the character


System.out.println("Enter a character");
char anychar = scanobj.next().charAt(0);
System.out.println("Your character is "+anychar);

//reading the BOOLEAN


System.out.println("Enter a character");
boolean blnflag = scanobj.nextBoolean();
System.out.println("Your character is "+blnflag);
}
}

Data input Stream and buffered reader.

……

File handling in Java: (it is only for flat files)

Using file class we can handle computer flat files.

Examples.

1. Create a folder
2. package testexamples;
3. import java.io.File;
4. public class Filehandling {
5. public static void main(String [] args) {
6. File fileobject=new File("D://testexamples");
7. fileobject.mkdir();
8. }
9.
10. }
Check the existence of folder:
package testexamples;
import java.io.File;
public class Filehandling {
public static void main(String [] args) {
File fileobject=new File("D://testexamples");
fileobject.mkdir();
boolean blnstatus=fileobject.exists();
if (blnstatus==true) {
System.out.println("folder is exist");
}
else {
System.out.println("flder is not exist");
}
}

Delete a Folder: fileobject.delete();


Create flat files – notepad:
package testexamples;
import java.io.File;
import java.io.IOException;
public class Filehandling {
public static void main(String [] args) throws IOException {
File fileobject=new File("D://testexamples");
boolean blnstatus=fileobject.exists();
if (blnstatus==true) {
System.out.println("folder is exist");
}
else {
System.out.println("flder is not exist");
fileobject.mkdir();
}
File newfileobject=new File("D://testexamples//javatestfile.txt");

newfileobject.createNewFile();
}

Delete Text File: newfileobject.delete();

Exception handling in Java:


An exception is an event, it occurs during execution of a program. When normal execution of the
program is interrupted.

It is the mechanism to handle exceptions.

Common scenarios where exception may occur:


1. Scenario where arithmetic exception occurs. (divide any number / 0) => arithmetic
exception occurs.
2. Scenario where null pointer exception occurs. (if we have null value in any variable,
performing any operations by the variable
Sting s = null;
System.out.println();
3. Scenario where number point exception occur. – wrong formatting of any value.
String s=”abc”;
Int a=Integer.parseInt(s);
System.out.println(y);//number format exception
4. Scenario where arrayindex out of bound exception occurs. If we insert any value in the
wrong index.
Example :
Int [] a = new int [5];
A[100] = 123; // exception occur

Selenium session 12: Java Methods.


1. Introduction to Java methods.
2. Types of methods.
3. User defined methods.
4. Build in methods.
1. Introduction to Java methods.
It is a set of statements, that are grouped together to perform an operation.
Methods are also known as functions.
In structured programing we use functions - ex: c language.
In Object oriented programming we use Methods. – ex: java.
2. When we choose methods. – whenever we want to perform any operation multiple times, we
choose Methods.
3. Advantages Methods: Code reusability and reduce code size.

Types of Methods:
1. Build in Method or predefined methods.
Read only, Limited,
Ex: import java.io.console;
Import java.util.*;
To use build in methods we need to import packages or classes.
Java.lang package is automatically imported in every java program.
Using import keyword we can import java classes and packages.
Categories of Build in methods:
String Methods.
Array methods.
Number methods
Character method.

2. User defined Method. – 2 types.


=> Method without retuning any values.
=> Method with retuning any values

Two ways we can user defined methods.


1. Calling method by invoking object.
2. Calling method without invoking object.

Writing methods: (with returning a value)


1. By invoking object.
Syntax for creating a method (calling the method by invoking object)
Accessmodifier returntype methodname(parameters){
Method body (Statements);
}

Calling the method by creating a object.


Classname objectname = new Classname();

//call method by invoking object.


Datatype variablename=object.method(values of the parameter);
Or
Syso..println

Example:
package testexamples;

public class methodssample {

public int addition(int number1, int number2){


int addres = number1+number2;
return addres;
}
public static void main(String [] args) {
methodssample objadd = new methodssample();
int result = objadd.addition(12, 13);
System.out.println(result);
}
}

Without invoking object:


Syntax : accessmodifier nonaccessmodifier returntype methodname(parameters){

Method body;
}
Call Method
Datatype variablename = methodname(values);
Or
System.out.println(methodname(values));

public static int multiply (int a, int b) {


int result = a*b;
}
public static void main(String [] args) {
int x = multiply(10,20);
System.out.println(x);
System.out.println(multiply(11,11));
}

Method without retuning any value by invoking object:


1. Syntax for creating a method (call the method by invoking object)
Sysntax :
Accessmodifier returntype_nothing methodname (parameters){
Staements;
}

Calling method:
Classname onjname = new classname();

Objname.method(parameter);

public void studentrank(int marks) {


if (marks >= 90) {
System.out.println("First rank");
}
else if (marks >= 70 && marks < 90) {
System.out.println("Second rank");
}
else {
System.out.println("last rank");
}
}

public static void main(String [] args) {


methodssample objrank = new methodssample();
objrank.studentrank(56);
}

Method without retuning any value – without object:


Syntax:
Accessmodifier nonaccessmodifier retruntypenothing methodname(paramters){
Statement;
}
Call method:
Methodname(parametervalue);

Usage of methods.
1. Internal methods. (creating and calling methods with in same class)
2. External methods. (calling methods from other classes)

External Methods:
1. By invoking object.

//create method
public int add(int a, int b) {
int c = a+b;
return c;
}
public static void main(String [] args) {
//create object for internal method
externalmethodsam objadd = new externalmethodsam();
int resultc=objadd.add(1, 2);
System.out.println(resultc);
externalmethods objmul = new externalmethods();
int exres= objmul.multiply(1, 2, 3);
System.out.println(exres);
}

2. Without invoking object.


public static void main(String [] args) {
externalmethods.agefactor(19);
Using class name we can access external non return methods.

Selenium Session 13: Build in methods.


Categories of build in methods.
1. String methods.
2. Number methods.
3. Character methods .
4. Array methods.

String methods:
1. compareTo() method(it compares two strings and supports three way comparison)
result : zero, greater than zero and less than zero.
Str1.compareTo(str2);

Two way comparison : equals () method.


Result : true or false
Str1.equals(str2);
2. concat() method (it concatenate two stgrings)
syntax : str1.concat(str2);
str1+str2;(using concat operator)
3. charAt() method : returns a char by index position.
Sytax : str1.charAt(1); // index starts from 0
4. equalsIgnorecase() method : capital letter ignore will return Boolean. Compare both strings but
ignore capital letters.
syntax: str1.equalsIgnorecase(str2); // True or false
5.
Selenium Tutorial: PDF : J Unit – Annotations:

@Test : running a test. All methods should attach with the class.

@Before : its like pre requestee of the TC(Temp variable, default values, invoking test environment)

@after: its like end of TC. Releasing memory, temp var, generating result)

@beforeclass: this instruct the Junit fw tells that, the method attached to it run only once before any
other method in the class is executed. We can use this annotation like the task that can be done only
once for all test such as connecting db, intestinal computational task.

@afterclass: used to release resources allocated or open by @beforeclass.


Selenium Methods:

Get() – Loads a new web page in the current browser with the help of http protocol.

Navigate()-Access the browser history and navigates given URL

getTitle()-fetches the title of the current opened web page for assertion.

GetcurrentUrl()-fetches the url of the currently opened web page.

getPageSource-getting page source of the web page.

findElement- locate the unique web element by given locator.

findElements- locate all web element by given locator.

getWindowHandles()-returns a set of all opened browser window.

getWindowHandle()-returns a unique browser window to identify the elements and work with them.

Close()-closes the currently open or active window

Quit()-quits the web driver instance and close all bowser windows.

Selenium Tutorials:

Assertion:

Assert - when an assert fails, the test is aborted

Verify – when verify fails, the test will continue execution, logging the failure

waitFor – like qtp dynamic wait functions

xpath – absolute xpath – capturing the elements with static html attributes- begin with single slash (/). I
can select an elemnt from root node.

Relative xpath – capturing the elements with static html attributes-

You might also like