Selenium Java PDF

Download as pdf or txt
Download as pdf or txt
You are on page 1of 214

CONTENTS

1.Framework

a.General Data Driven Framework

b. Testing Web Driver Data Driven Framework

2.JAVA

3.Sample Programs on Java

4.Interview Questions on Java

5.Selenium RC

6.TestNG and JUnit

7.Web Driver.

8.Sample Programs on Selenium

9.Interview Question on Selenium


Page | 2
nd
QEdge TECHNOLOGIES: # 204, 2 Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 

Framework
General Data Driven Framework &
TestNG WebDriver Data Driven
Framework Aim or Goals of Framework:

¾ Tests With Multiple Suite

¾ Run Selective Test Suite

¾ Run Selected Test Cases

¾ Generate Logs

¾ Repeat a test case – Parameterize

¾ Execute Test cases with multiple sets of data

¾ Run complete Project in Console or command line

¾ BAT file for execution through ANT

¾ Generate Html Reports using TestNG

¾ Generate XSLT Reports or Pie Graphs for Result

________________________________________________________________________
QEdge TECHNOLOGIES: # 204, 2nd Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
Page | 3
nd
QEdge TECHNOLOGIES: # 204, 2 Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
Prepare Test Suites - TestSuite.xlsx

Prepare Test Cases and Test data xls for Test Suites. One xls file per test

suite

Introduce Runmodes

Make eclipse Java project

make package- suiteA

make package- suiteB

make package- suiteC

make package- logs

make package- util

make package- base,

in base create initialize function and declare global variables like xls files
with path.

make package- config, create OR.properties and config.properties

make package- xls

Put xls files in xls

Prepare config.properties and OR.properties

Make TestUtil.java in util package

Prepare function to check Runmode of a Test Suite - isSuiteRunnable

________________________________________________________________________
QEdge TECHNOLOGIES: # 204, 2nd Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
Page | 4
nd
QEdge TECHNOLOGIES: # 204, 2 Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
Prepare function to check Runmode of a Test Case in Test Suite -
isTestCaseRunnable

Prepare function to return test data for a test case in two dim array -
getData

Make TestBase.java

Prepare initialize function to initialize the logs,

Make TestSuiteBase.java class in each test Suite package

Prepare all test classes in all suites

Prepare testng.xml and individual suite xmls

Batch run and check empty project

Implement @BeforeSuite and @BeforeTest functions in Project to check


Runmode of Suite and Test

Batch run and check empty project

Implement @dataprovider Functions in all test classes - PARAMETRIZING


THE TEST CASES

Implement build.xml and run project through command prompt

Make a .bat file to run the frameworkDouble clicking on bat file your will
or complete script will execute and generate the reports and logs.

________________________________________________________________________
QEdge TECHNOLOGIES: # 204, 2nd Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
Page | 5
nd
QEdge TECHNOLOGIES: # 204, 2 Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 

Framework is Class Room Training


OnlyPlease Contact Below Contact Number

________________________________________________________________________
QEdge TECHNOLOGIES: # 204, 2nd Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
Page | 6
nd
QEdge TECHNOLOGIES: # 204, 2 Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
 

JAVA    

________________________________________________________________________
QEdge TECHNOLOGIES: # 204, 2nd Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
Page | 7
nd
QEdge TECHNOLOGIES: # 204, 2 Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
 

INDEX of JAVA 
1. Introduction to Java
1.1. History
1.2. Java Virtual machine
1.3. Java Runtime Environment vs. Java Development Kit
1.4. Characteristics of Java
1.5. Development Process with Java
1.6. Classpath
2. Installation of Java
3. Your first Java program
3.1. Write source code
3.2. Compile and run your Java program
3.3. Using the classpath
4. Integrated Development Environment
5. Your first graphical user interface application (GUI)
6. Statements
6.1. Boolean Operations
6.2. Switch Statement
7. Working with Strings
8. Type Conversion
8.1. Conversion to String
8.2. Conversion from String to Number
8.3. Double to int
8.4. SQL Date conversions
9. Cheat Sheets
9.1. Working with classes
9.2. Working with local variable
________________________________________________________________________
QEdge TECHNOLOGIES: # 204, 2nd Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
Page | 8
nd
QEdge TECHNOLOGIES: # 204, 2 Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
10. Thank you  

11. Questions and Discussion


12. Links and Literature

1. Introduction to Java
1.1. History
Java is a programming language created by James Gosling from Sun Microsystems in
1991. The first publicly available version of Java (Java 1.0) was released in 1995.

Over time new enhanced versions of Java have been released. The current version of
Java is Java 1.7 which is also known as Java 7.

From the Java programming language the Java platform evolved. The Java platform
allows that the program code is written in other languages than the Java programming
language and still runs on the Java virtual machine.

1.2. Java Virtual machine

The Java virtual machine (JVM) is a software implementation of a computer that


executes programs like a real machine.

The Java virtual machine is written specifically for a specific operating system, e.g.
for Linux a special implementation is required as well as for Windows.

Java programs are compiled by the Java compiler into so-called bytecode. The Java
virtual machine interprets this bytecode and executes the Java program.

________________________________________________________________________
QEdge TECHNOLOGIES: # 204, 2nd Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
Page | 9
nd
QEdge TECHNOLOGIES: # 204, 2 Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 

1.3. Java Runtime Environment vs. Java Development Kit


Java comes in two flavors, the Java Runtime Environment (JRE) and the Java
Development Kit (JDK).

The Java runtime environment (JRE) consists of the JVM and the Java class libraries
and contains the necessary functionality to start Java programs.

The JDK contains in addition the development tools necessary to create Java
programs. The JDK consists therefore of a Java compiler, the Java virtual machine,
and the Java class libraries.

1.4. Characteristics of Java


The target of Java is to write a program once and then run this program on multiple
operating systems.

Java has the following properties:

• Platform independent: Java programs use the Java virtual machine as


abstraction and do not access the operating system directly. This makes Java
programs highly portable. A Java program which is standard complaint and
follows certain rules can run unmodified on all supported platforms, e.g.
Windows or Linux.
• Object-orientated programming language: Except the primitive data types, all
elements in Java are objects.
• Strongly-typed programming language: Java is strongly-typed, e.g. the types of
the used variables must be pre-defined and conversion to other objects is
relatively strict, e.g. must be done in most cases by the programmer.

________________________________________________________________________
QEdge TECHNOLOGIES: # 204, 2nd Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
Page | 10
nd
QEdge TECHNOLOGIES: # 204, 2 Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 

• Interpreted and compiled language: Java source code is transferred into the
bytecode format which does not depend on the target platform. These
bytecode instructions will be interpreted by the Java Virtual machine (JVM).
• The JVM contains a so called Hotspot-Compiler which translates performance
critical bytecode instructions into native code instructions.
• Automatic memory management: Java manages the memory allocation and de-
allocation for creating new objects. The program does not have direct access
to the memory. The so-called garbage collector deletes automatically objects
to which no active pointer exists.

The Java syntax is similar to C++. Java is case sensitive, e.g. the variables myValue
and myvalue will be treated as different variables.

1.5. Development Process with Java


The programmer writes Java source code in a text editor which supports plain text.
Normally the programmer uses an Integrated Development Environment (IDE) for
programming. An IDE supports the programmer in the task of writing code, e.g. it
provides auto-formating of the source code, highlighting of the important keywords,
etc.

At some point the programmer (or the IDE) calls the Java compiler (javac). The Java
compiler creates the bytecode instructions. . These instructions are stored in .class
files and can be executed by the Java Virtual Machine.

________________________________________________________________________
QEdge TECHNOLOGIES: # 204, 2nd Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
Page | 11
nd
QEdge TECHNOLOGIES: # 204, 2 Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 

1.6. Classpath

The classpath defines where the Java compiler and Java runtime look for .class files
to load. This instructions can be used in the Java program.

For example if you want to use an external Java library you have to add this library to
your classpath to use it in your program.

2. Installation of Java

Java might already be installed on your machine. You can test this by opening a
console (if you are using Windows: Win+R, enter cmd and press Enter) and by typing in
the following command:

java -version

If Java is correctly installed, you should see some information about your Java
installation. If the command line returns the information that the program could not
be found, you have to install Java. The central website for installing Java is the
following URL:

http://java.com

If you have problems installing Java on your system, search via Google for How to
install JDK on YOUR_OS. This should result in helpful links. Replace YOUR_OS with
your operating system, e.g. Windows, Mac OS X, etc.

________________________________________________________________________
QEdge TECHNOLOGIES: # 204, 2nd Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
Page | 12
nd
QEdge TECHNOLOGIES: # 204, 2 Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 

3. Your first Java program


3.1. Write source code
The following Java program is developed under Microsoft Windows. The process on
other operating system should be similar but is not covered in this description.

Select a new directory which will contain your Java code. I will use the c:\temp\java
which will be called javadir in the following description.

Open a text editor which supports plain text, e.g. Notepad under Windows and write
the following source code. You can start Notepad via Start → Run → Notepad and by
pressing enter.

// A small Java program


public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello World");
}
}

________________________________________________________________________
QEdge TECHNOLOGIES: # 204, 2nd Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
Page | 13
nd
QEdge TECHNOLOGIES: # 204, 2 Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 

Save the source code in your javadir directory with the HelloWorld.java filename. The
name of a Java source file must always equals the class name (within the source
code) and end with the .java extension. In this example the filename must be
HelloWorld.java because the class is called HelloWorld. 

3.2. Compile and run your Java program

Switch to the command line, e.g. under Windows Start-> Run -> cmd. Switch to the
javadir directory with the command cd javadir, for example in my case cd
c:\temp\java. Use the command dir to see that the source file is in the directory.

javac testjava.java

Check the content of the directory with the command "dir". The directory contains
now a file "testjava.class". If you see this file you have successfully compiled your first
Java source code into bytecode.

By default, the compiler puts each class file in the same directory as its source file.
You can specify a separate destination directory with the -d compiler flag.
________________________________________________________________________
QEdge TECHNOLOGIES: # 204, 2nd Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
Page | 14
nd
QEdge TECHNOLOGIES: # 204, 2 Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
Run -> cmd. Switch to the directory jardir.

To run your program type in the command line:

java testjava

________________________________________________________________________
QEdge TECHNOLOGIES: # 204, 2nd Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
Page | 15
nd
QEdge TECHNOLOGIES: # 204, 2 Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
The system should write "learning selenium" on the command line.

3.3. Using the classpath

You can use the classpath to run the program from another place in your directory.

Switch to the command line, e.g. under Windows Start-> Run -> cmd. Switch to any
directory you want. Type:

java learning selenium

________________________________________________________________________
QEdge TECHNOLOGIES: # 204, 2nd Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
Page | 16
nd
QEdge TECHNOLOGIES: # 204, 2 Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 

If you are not in the directory in which the compiled class is stored then the system
should result an error message Exception in thread "main"
java.lang.NoClassDefFoundError: test/TestClass

To use the class type the following command. Replace "mydirectory" with the
directory which contains the test directory. You should again see the " learning
selenium " output.

java -classpath "mydirectory" learning selenium

4. Integrated Development Environment


The previous chapter explained how to create and compile a Java program on the
command line. A Java Integrated Development Environment (IDE) provides lots of ease
of use functionality for creating java programs. There are other very powerful IDE's
available, for example the Eclipse IDE. .

In the following I will say "Create a Java project SomeName". This will refer to
creating an Eclipse Java project. If you are using a different IDE please follow the
required steps in this IDE.

4.1. To Install Java: 
1. Go to google and type “download JDK”
2. Now select your OS compatibility (32bit or 64bit)
3. Install in your system.

________________________________________________________________________
QEdge TECHNOLOGIES: # 204, 2nd Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
Page | 17
nd
QEdge TECHNOLOGIES: # 204, 2 Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 

4.2. To Configure Eclipse IDE: 
1. Go to google and type “download Eclipse”  
2. Now select your OS compatibility (32bit or 64bit) 
3. Save in your system and open folder and send shortcut to desktop 

________________________________________________________________________
QEdge TECHNOLOGIES: # 204, 2nd Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
Page | 18
nd
QEdge TECHNOLOGIES: # 204, 2 Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
 

 
  

________________________________________________________________________
QEdge TECHNOLOGIES: # 204, 2nd Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
Page | 19
nd
QEdge TECHNOLOGIES: # 204, 2 Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
 

Click on short cut it displays like below:


Now click on workbench link.

________________________________________________________________________
QEdge TECHNOLOGIES: # 204, 2nd Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
Page | 20
nd
QEdge TECHNOLOGIES: # 204, 2 Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 

5. Your first graphical user interface application (GUI)


Introduction of Eclipse and eclipse GUI.

Now open eclipse short cut from the desktop as above explained. It’ll displays like
below screenshot.

________________________________________________________________________
QEdge TECHNOLOGIES: # 204, 2nd Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
Page | 21
nd
QEdg
ge TECHNOOLOGIES: # 204, 2 Floor, Nagassuri Plaza, Ameerpet, Hyderabad
d.
Email: info@qedge
etech.com,, ph:040-64
4644491/922, 77029444
491.
 

Using Eclipse create


c a new Javva proje
ect :

Step 1:
1. Go to
o file menu ÆNewÆsselect Java
a Project
_______
__________
__________
_________
__________
__________
__________
__________
____
QEdg
ge TECHNOOLOGIES: # 204, 2nd Floor, Nagassuri Plaza, Ameerpet, Hyderabad
d.
Email: info@qedge
etech.com,, ph:040-64
4644491/92 2, 77029444
491.
 
Page | 22
nd
QEdg
ge TECHNOOLOGIES: # 204, 2 Floor, Nagassuri Plaza, Ameerpet, Hyderabad
d.
Email: info@qedge
etech.com,, ph:040-64
4644491/922, 77029444
491.
 

Step 2:
Type Pro
oject Name
e and click on finish button.
b

_______
__________
__________
_________
__________
__________
__________
__________
____
QEdg
ge TECHNOOLOGIES: # 204, 2nd Floor, Nagassuri Plaza, Ameerpet, Hyderabad
d.
Email: info@qedge
etech.com,, ph:040-64
4644491/92 2, 77029444
491.
 
Page | 23
nd
QEdge TECHNOLOGIES: # 204, 2 Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 

Create Package:

________________________________________________________________________
QEdge TECHNOLOGIES: # 204, 2nd Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
Page | 24
nd
QEdg
ge TECHNOOLOGIES: # 204, 2 Floor, Nagassuri Plaza, Ameerpet, Hyderabad
d.
Email: info@qedge
etech.com,, ph:040-64
4644491/922, 77029444
491.
 
Step 3:
• Now click on prroject folde
er and selecct src folde
er
• Go to
o file menu
u or click bu
utton and select
s packkage

_______
__________
__________
_________
__________
__________
__________
__________
____
QEdg
ge TECHNOOLOGIES: # 204, 2nd Floor, Nagassuri Plaza, Ameerpet, Hyderabad
d.
Email: info@qedge
etech.com,, ph:040-64
4644491/92 2, 77029444
491.
 
Page | 25
nd
QEdg
ge TECHNOOLOGIES: # 204, 2 Floor, Nagassuri Plaza, Ameerpet, Hyderabad
d.
Email: info@qedge
etech.com,, ph:040-64
4644491/922, 77029444
491.
 
Step 4:
• Type
e package name
n and click
c on finish button.

_______
__________
__________
_________
__________
__________
__________
__________
____
QEdg
ge TECHNOOLOGIES: # 204, 2nd Floor, Nagassuri Plaza, Ameerpet, Hyderabad
d.
Email: info@qedge
etech.com,, ph:040-64
4644491/92 2, 77029444
491.
 
Page | 26
nd
QEdg
ge TECHNOOLOGIES: # 204, 2 Floor, Nagassuri Plaza, Ameerpet, Hyderabad
d.
Email: info@qedge
etech.com,, ph:040-64
4644491/922, 77029444
491.
 

Creatte Classs:
Step 5:
Select package
p fold
der and go to file men
nu and click on menu button and
d select cla
ass

_______
__________
__________
_________
__________
__________
__________
__________
____
QEdg
ge TECHNOOLOGIES: # 204, 2nd Floor, Nagassuri Plaza, Ameerpet, Hyderabad
d.
Email: info@qedge
etech.com,, ph:040-64
4644491/92 2, 77029444
491.
 
Page | 27
nd
QEdg
ge TECHNOOLOGIES: # 204, 2 Floor, Nagassuri Plaza, Ameerpet, Hyderabad
d.
Email: info@qedge
etech.com,, ph:040-64
4644491/922, 77029444
491.
 

Step 6:
1. Typee class Namme, Ex: BasicPrograms,, spaces it won’t allow
w.
2. Selecct public sttatic void main
m check box
3. Click
k on finish button.
b

_______
__________
__________
_________
__________
__________
__________
__________
____
QEdg
ge TECHNOOLOGIES: # 204, 2nd Floor, Nagassuri Plaza, Ameerpet, Hyderabad
d.
Email: info@qedge
etech.com,, ph:040-64
4644491/92 2, 77029444
491.
 
Page | 28
nd
QEdg
ge TECHNOOLOGIES: # 204, 2 Floor, Nagassuri Plaza, Ameerpet, Hyderabad
d.
Email: info@qedge
etech.com,, ph:040-64
4644491/922, 77029444
491.
 

It disp
plays like belo
ow.

_______
__________
__________
_________
__________
__________
__________
__________
____
QEdg
ge TECHNOOLOGIES: # 204, 2nd Floor, Nagassuri Plaza, Ameerpet, Hyderabad
d.
Email: info@qedge
etech.com,, ph:040-64
4644491/92 2, 77029444
491.
 
Page | 29
nd
QEdge TECHNOLOGIES: # 204, 2 Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 

6. Statements
The following describes certain aspects of the software.

6.1. Boolean Operations


Use == to compare two primitives or to see if two references refers to the same
object. Use the equals() method to see if two different objects are equal.

&& and || are both Short Circuit Methods which means that they terminate once the
result of an evaluation is already clear. Example (true || ....) is always true while
(false && ...) always false is. Usage:

(var !=null && var.method1()..) ensures that var is not null before doing the real
check.

Table 1. Boolean

Operations Description

Is equal, in case of objects the system checks if the reference


==
variable point to the same object, is will not compare the

________________________________________________________________________
QEdge TECHNOLOGIES: # 204, 2nd Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
Page | 30
nd
QEdge TECHNOLOGIES: # 204, 2 Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
Operations Description

content of the objects!

&& And

!= is not equal, similar to the "=="

a.equals(b) Checks if string a equals b

a.equalsIgnoreCase(b) Checks if string a equals b while ignoring lower cases

If (value ? false : true)


Return true if value is not true. Negotiation
{}

6.2. Switch Statement


The switch statement can be used to handle several alternatives if they are based on
the same constant value.

switch (expression) {
case constant1:
command;
break; // Will prevent that the other cases or also executed
case constant2:
command;
break;
...
default:
}
Example:
switch (cat.getLevel()) {
________________________________________________________________________
QEdge TECHNOLOGIES: # 204, 2nd Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
Page | 31
nd
QEdge TECHNOLOGIES: # 204, 2 Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
case 0:
return true;
case 1:
if (cat.getLevel() == 1) {
if (cat.getName().equalsIgnoreCase(req.getCategory())) {
return true;
}
}
case 2:
if (cat.getName().equalsIgnoreCase(req.getSubCategory())) {
return true;
}
}

7. Working with Strings


The following lists the most common string operations Table 2. .

Command Description
return true if text1 is equal to "Testing". The
text1.equals("Testing");
test is case sensitive.
return true if text1 is equal to "Testing". The
text1.equalsIgnoreCase("Testing"); test is not case sensitive. For example it
would also be true for "testing"
StringBuffer str1 = new StringBuffer(); Define a new String with a variable length.
Return the character at position 1. (Strings
str.charat(1);
starting with 0)
str.substring(1); Removes the first characters.
Gets the substring from the second to the
str.substring(1, 5);
fifths character.
Find / Search for String Returns the index of
str.indexOf(String)
the first occurrence of the specified string.
________________________________________________________________________
QEdge TECHNOLOGIES: # 204, 2nd Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
Page | 32
nd
QEdge TECHNOLOGIES: # 204, 2 Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
Command Description
Returns the index of the last occurrence of
the specified string. StringBuffer does not
str.lastIndexOf(String)
support this method. Hence first convert the
StringBuffer to String via method toString.
str.endsWith(String) Returns true if str ends with String
str.startsWith(String) Returns true if str starts with String
str.trim() Removes spaces
str.replace(str1,str2) Replaces all occurrences of str1 by str2
str.concat(str1); Concatenates str1 at the end of str.
str.toLowerCase() str.toUpperCase() Converts string to lower- or uppercase
str1 + str2 Concatenate str1 and str2
Spits myString at / into Strings. Attention: the
split string is a regular expression, so if you
String[] zeug = myString.split("-"); using special characters which have a meaning
String[] zeug = myString.split("\\."); in regular expressions you need to quote
them. In the second example the . is used and
must be quoted by two backslashes.

8. Type Conversion
If you use variables of different types Java requires for certain types an explicit
conversion. The following gives examples for this conversion.

8.1. Conversion to String


Use the following to convert from other types to Strings

// Convert from int to String


String s1 = String.valueOf (10); // "10" String s2 =
// Convert from double to String
String.valueOf (Math.PI); // "3.141592653589793"
________________________________________________________________________
QEdge TECHNOLOGIES: # 204, 2nd Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
Page | 33
nd
QEdge TECHNOLOGIES: # 204, 2 Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
// Convert from boolean to String
String s3 = String.valueOf (1 < 2); // "true"
// Convert from date to String
String s4 = String.valueOf (new Date()); // "Tue Jun 03 14:40:38 CEST 2003"

8.2. Conversion from String to Number


// Conversion from String to int
int i = Integer.parseInt(String);
// Conversion from float to int
float f = Float.parseFloat(String);
// Conversion from double to int
double d = Double.parseDouble(String);

The conversion from string to number is independent from the Locale settings, e.g. it
is always using the English notification for number. In this notification a correct
number format is "8.20". The German number "8,20" would result in an error.

To convert from a German number you have to use the NumberFormat class. The
challenges is that if the value is for example 98.00 then the NumberFormat class
would create a Long which cannot be casted to Double. Hence the following complex
conversion class.

private Double convertStringToDouble(String s) {

Locale l = new Locale("de", "DE");


Locale.setDefault(l);
NumberFormat nf = NumberFormat.getInstance();
Double result = 0.0;
try {
if (Class.forName("java.lang.Long").isInstance(nf.parse(s))) {

________________________________________________________________________
QEdge TECHNOLOGIES: # 204, 2nd Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
Page | 34
nd
QEdge TECHNOLOGIES: # 204, 2 Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
result = Double.parseDouble(String.valueOf(nf.parse(s)));
} else {
result = (Double) nf.parse(new String(s));
}
} catch (ClassNotFoundException e1) {
e1.printStackTrace();
} catch (ParseException e1) {
e1.printStackTrace();
}
return result;
}

8.3. Double to int


int i = (int) double;

9. Cheat Sheets
The following can be used as a reference for certain task which you have to do.

9.1. Working with classes


While programming Java you have to create several classes, methods, instance
variables. The following uses the package test.

Table 3.
What to do How to do it
package test;

Create a new class called MyNewClass. public class MyNewClass {

}
Create a new attribute (instance variable) "var1" in package test;
MyNewClass with type String

________________________________________________________________________
QEdge TECHNOLOGIES: # 204, 2nd Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
Page | 35
nd
QEdge TECHNOLOGIES: # 204, 2 Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
What to do How to do it
public class MyNewClass {
private String var1;
}
package test;

public class MyNewClass {


private String var1;
Create a Constructor for "MyNewClass which has a
String parameter and assigns the value of it to the public MyNewClass(String
"var1" instance variable. para1) {
var1 = para1;
// or this.var1= para1;
}
}
package test;

public class MyNewClass {


private String var1;

public MyNewClass(String
para1) {
Create a new method "doSomeThing" in class which var1 = para1;
do not return a value and has no parameters // or this.var1= para1;
}

public void doSomeThing() {

}
package test;

public class MyNewClass {


private String var1;
Create a new method "doSomeThing2" in class which
do not return a value and has two parameters, a int public MyNewClass(String
and a Person para1) {
var1 = para1;
// or this.var1= para1;
}

________________________________________________________________________
QEdge TECHNOLOGIES: # 204, 2nd Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
Page | 36
nd
QEdge TECHNOLOGIES: # 204, 2 Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
What to do How to do it
public void doSomeThing() {

public void doSomeThing2(int


a, Person person) {

}
package test;

public class MyNewClass {


private String var1;

public MyNewClass(String
para1) {
var1 = para1;
// or this.var1= para1;
}

public void doSomeThing() {


Create a new method "doSomeThing2" in class which
}
do return an int value and has three parameters, two
Strings and a Person
public void doSomeThing2(int
a, Person person) {

public int
doSomeThing3(String a, String
b, Person person) {
return 5; // Any value will
do for this example
}

}
Create a class "MyOtherClass" with two instance package test;
variables. One will store a String, the other will store
a Dog. Create getter and setter for these variables. public class MyOtherClass {
________________________________________________________________________
QEdge TECHNOLOGIES: # 204, 2nd Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
Page | 37
nd
QEdge TECHNOLOGIES: # 204, 2 Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
What to do How to do it
String myvalue;
Dog dog;

public String getMyvalue() {


return myvalue;
}

public void setMyvalue(String


myvalue) {
this.myvalue = myvalue;
}

public Dog getDog() {


return dog;
}

public void setDog(Dog dog) {


this.dog = dog;
}
}

9.2. Working with local variable


A local variable must always be declared in a method.

Table 4.
What to do How to do it

________________________________________________________________________
QEdge TECHNOLOGIES: # 204, 2nd Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
Page | 38
nd
QEdge TECHNOLOGIES: # 204, 2 Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
What to do How to do it

Declare a (local) variable of type string. String variable1;

Declare a (local) variable of type string and assign


String variable2 = "Test";
"Test" to it.

Declare a (local) variable of type Person Person person;

Declare a (local) variable of type Person, create a


Person person = new Person();
new Object and assign the variable to this object.

Declare a array of type String String array[];

Declare a array of type Person and create an array


Person array[]= new Person[5];
for this variable which can hold 5 Persons.

Assign 5 to the int variable var1 (which was


var1 = 5;
already declared);

Assign the existing variable pers2 to the exiting


pers1 = pers2;
variable pers1;

Declare a ArrayList variable which can hold


ArrayList<Person> persons;
objects of type Person

Create a new ArrayList with objects of type


Person and assign it to the existing variable persons = new ArrayList<Person>();
persons

Declare a ArrayList variable which can hold


ArrayList<Person> persons = new
objects of type Person and create a new Object
ArrayList<Person>();
for it.

Java Interview Programs:


________________________________________________________________________
QEdge TECHNOLOGIES: # 204, 2nd Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
Page | 39
nd
QEdge TECHNOLOGIES: # 204, 2 Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
Java basic program- Program-1:
package Pack1; 
 
public class JavaBasic_Commands { 
   
  public static void main(String[]args){ 
   
  System.out.println("learning selenium"); 
   
  int a=10;   //32bit   it can store the numeric values 
   
  int b=11,c=12; 
  long l=67;     //64 bit it can store the numeric values 
     
  double d=45.6;   //it can any decimal values 
   
  double d1=35;  
  System.out.println(a+d); 
   
  char c1='j';   //it can strore a single char 
   
  String str="selenium";   
   
  System.out.println(str); 
   
  } 

 
 
Out put:
learning selenium 
________________________________________________________________________
QEdge TECHNOLOGIES: # 204, 2nd Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
Page | 40
nd
QEdge TECHNOLOGIES: # 204, 2 Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
55.6 
selenium

Program-2:
package Pack1; 
 
public class String_functions { 
   
  public static void main (String[]args){ 
String str="learning";  //it can store no.of chars 
or group of words,  
    String str1="the rain have been started"; 
     
    System.out.println(str+"===="+str1); 
     
      int length=str1.length(); 
      System.out.println(length); 
       
      //String[] test=str1.split(" ");       
       
  } 
}

Out put:
learning====the rain have been started 
26 

For loops Program-3:


package Pack1; 
 
public class For_Loops { 
  public static void main(String[] args) { 
________________________________________________________________________
QEdge TECHNOLOGIES: # 204, 2nd Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
Page | 41
nd
QEdge TECHNOLOGIES: # 204, 2 Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
  //int i=5;   
  for(int i=5;i>=0;i‐‐){        //initialization, 
condition, incremental or decremental 
    System.out.print(i);     
  } 
  } 

Out put: 






 
If conditions programs-4:
package Pack1; 
public class If_Conditions {  
  public static void main (String[]args){ 
    /*int a=120, b=25; 
    if(a>b){ 
      System.out.println("a is the greatest value= 
"+a); 
    }else{ 
      System.out.println("b is the greatest value= 
"+b);  //type syso+contl+spacebar 
    } 
    */ 
    //< > + ‐ / % &  
     
    int a=14, b=13, c=45; 
     
    if(a>b && a>c){ 
    System.out.println("a is the greatest value= "+a);   
    }else if(b>c){ 

________________________________________________________________________
QEdge TECHNOLOGIES: # 204, 2nd Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
Page | 42
nd
QEdge TECHNOLOGIES: # 204, 2 Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
      System.out.println("b is the greatest value= 
"+b); 
       
    }else{ 
      System.out.println("c is the greatest value= 
"+c); 
    } 
  } 

 
Output: c is the greatest value= 45 
While loop - programs-5:
package Pack1; 
public class While_Loop { 
  public static void main(String[] args) { 
  int i=1;  //initializtion 
  while(i<=5){  //condition 
    System.out.println(i); 
    i++; //incremental or decremental 
  } 
  } 

 
Out put: 





 
Simple Date program - programs-6:
 
import java.util.*; 
public class DateDemo { 
   public static void main(String args[]) { 

________________________________________________________________________
QEdge TECHNOLOGIES: # 204, 2nd Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
Page | 43
nd
QEdge TECHNOLOGIES: # 204, 2 Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
     Date dNow = new Date(); 
     System.out.println("Current Date: " + dNow); 
      
   } 

Out put: Current Date: Tue Apr 23 14:15:54 IST 2013

Find Smallest Number and Largest Number in an array:


Program-7:
public class FindLargestSmallestNumber { 
  public static void main(String[] args) { 
    int numbers[] = new 
int[]{32,43,53,54,32,65,63,98,111,23,21}; 
    int smallest = numbers[0]; 
    int largetst = numbers[0]; 
    for(int i=1; i< numbers.length; i++){ 
 
      if(numbers[i] > largetst) 
            largetst = numbers[i]; 
 
      else if (numbers[i] < smallest) 
            smallest = numbers[i]; 
    } 
     
        System.out.println("Largest Number is : " + largetst); 
        System.out.println("Smallest Number is : " + smallest); 
  } 

Out put:
Largest Number is : 111 
Smallest Number is : 21 
 
________________________________________________________________________
QEdge TECHNOLOGIES: # 204, 2nd Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
Page | 44
nd
QEdge TECHNOLOGIES: # 204, 2 Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
 
 
 
 
 
Factorial Print for number - Program-8:
public class Example1 { 
  public static void main(String[] args) { 
    int numbers[]=new int[]{2,3,5,1,8,6,9,25,‐5}; 
    int smallest=numbers[0]; 
    int largest=numbers[0]; 
     
    for(int i=1;i<numbers.length;i++){ 
      if(numbers[i]>largest) 
        largest=numbers[i]; 
      else if(numbers[i]<smallest) 
        smallest=numbers[i]; 
       
    } 
 
 
    System.out.println("largest number= "+largest); 
    System.out.println("smallest number= "+smallest); 
  } 

 
Out put:
Enter a Factorial Number = 
25 
2076180480 
 
Matrix print - Program-9:
public class MatricsPrint { 
 
  public static void main(String[] args) { 
   
    for(int i=1;i<=9;i=i+3){ 
      for(int j=i;j<i+3;j++){ 
        System.out.print(j+" "); 
      } 
      System.out.println(); 
________________________________________________________________________
QEdge TECHNOLOGIES: # 204, 2nd Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
Page | 45
nd
QEdge TECHNOLOGIES: # 204, 2 Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
    } 
  } 

 
Out put:
1 2 3  
4 5 6  
7 8 9 
 
Rev_Num_Print - Program-10:
public class Rev_Num_Print { 
 
  public static void main(String[] args) { 
    int n, reverse=0; 
    System.out.println("Enter a number"); 
    Scanner in= new Scanner(System.in); 
    n= in.nextInt(); 
     
    while (n!=0){ 
      reverse= reverse * 10; 
      reverse= reverse + n%10; 
            n=n/10; 
      //System.out.println(reverse); 
    } 
    System.out.println(reverse); 
 
  } 
 

Out put:
Enter a number 
12345 
54321 
 
Reverse sentence - Program-11:
public class Reverse_sentance { 
  public static void main(String[] args) { 
________________________________________________________________________
QEdge TECHNOLOGIES: # 204, 2nd Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
Page | 46
nd
QEdge TECHNOLOGIES: # 204, 2 Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
  String x="Bittu going to delhi"; 
  String temp[]=x.split(" "); 
   
  for(int i=0;i<temp.length;i++){ 
    String k=temp[i]; 
    for(int j=k.length()‐1;j>=0;j‐‐){ 
      System.out.print(k.charAt(j)); 
    } 
    System.out.print(" "); 
    } 
  } 

Out put:
uttiB gniog ot ihled

SumTotal - Program-11:
public class SumTotal { 
  public static void main(String[] args) { 
    int x[]=new int []{2,3,5,23,25,12}; 
    int sum=0; 
    for(int i=0;i<x.length;i++){ 
      sum=sum+x[i]; 
    } 
    System.out.println(sum); 
  } 

 
Out put:70

________________________________________________________________________
QEdge TECHNOLOGIES: # 204, 2nd Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
Page | 47
nd
QEdge TECHNOLOGIES: # 204, 2 Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 

Java Important Interview Questions:


Q: What is the difference between an Interface and an Abstract class?

A: An abstract class can have instance methods that implement a default behavior. An
Interface can only declare constants and instance methods, but cannot implement
default behavior and all methods are implicitly abstract. An interface has all public
members and no implementation. An abstract class is a class which may have the
usual flavors of class members (private, protected, etc.), but has some abstract
methods.

Q: What is the difference between a constructor and a method?

A: A constructor is a member function of a class that is used to create objects of that


class. It has the same name as the class itself, has no return type, and is invoked
using the new operator.
A method is an ordinary member function of a class. It has its own name, a return
type (which may be void), and is invoked using the dot operator.

Q: What is an Iterator?

A: Some of the collection classes provide traversal of their contents via a


java.util.Iterator interface. This interface allows you to walk through a collection

________________________________________________________________________
QEdge TECHNOLOGIES: # 204, 2nd Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
Page | 48
nd
QEdge TECHNOLOGIES: # 204, 2 Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
of objects, operating on each object in turn. Remember when using Iterators that
they contain a snapshot of the collection at the time the Iterator was obtained;
generally it is not advisable to modify the collection itself while traversing an
Iterator.

Q: State the significance of public, private, protected, default modifiers both


singly and in combination and state the effect of package relationships on
declared items qualified by these modifiers.
A: public : Public class is visible in other packages, field is visible everywhere (class
must be public too)
private : Private variables or methods may be used only by an instance of the same
class that declares the variable or method, A private feature may only be accessed
by the class that owns the feature.
protected : Is available to all classes in the same package and also available to all
subclasses of the class that owns the protected feature.This access is provided
even to subclasses that reside in a different package from the class that owns the
protected feature.
default :What you get by default ie, without any access modifier (ie, public private
or protected).It means that it is visible to all within a particular package.

TOP

Q:What is an abstract class?

A: Abstract class must be extended/subclassed (to be useful). It serves as a template.


A class that is abstract may not be instantiated (ie, you may not call its
constructor), abstract class may contain static data. Any class with an abstract
method is automatically abstract itself, and must be declared as such.

________________________________________________________________________
QEdge TECHNOLOGIES: # 204, 2nd Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
Page | 49
nd
QEdge TECHNOLOGIES: # 204, 2 Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
A class may be declared abstract even if it has no abstract methods. This prevents
it from being instantiated.

Q:What is static in java?

A: Static means one per class, not one for each object no matter how many instance
of a class might exist. This means that you can use them without creating an
instance of a class.Static methods are implicitly final, because overriding is done
based on the type of the object, and static methods are attached to a class, not an
object. A static method in a superclass can be shadowed by another static method
in a subclass, as long as the original method was not declared final. However, you
can't override a static method with a nonstatic method. In other words, you can't
change a static method into an instance method in a subclass.

Q:What is final?

A: A final class can't be extended ie., final class may not be subclassed. A final
method can't be overridden when its class is inherited. You can't change value of a
final variable (is a constant).

Q:What if the main method is declared as private?

A: The program compiles properly but at runtime it will give "Main method not public."
message.

Q:What if the static modifier is removed from the signature of the main method?

A: Program compiles. But at runtime throws an error "NoSuchMethodError".

________________________________________________________________________
QEdge TECHNOLOGIES: # 204, 2nd Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
Page | 50
nd
QEdge TECHNOLOGIES: # 204, 2 Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 

Q:What if I write static public void instead of public static void?

A: Program compiles and runs properly.

Q:What if I do not provide the String array as the argument to the method?

A: Program compiles but throws a runtime error "NoSuchMethodError".

Q:What is the first argument of the String array in main method?

A: The String array is empty. It does not have any element. This is unlike C/C++ where
the first element by default is the program name.

Q:If I do not provide any arguments on the command line, then the String array of
Main method will be empty or null?
A: It is empty. But not null.

Q:How can one prove that the array is not null but empty using one line of code?

A: Print args.length. It will print 0. That means it is empty. But if it would have been
null then it would have thrown a NullPointerException on attempting to print
args.length.

Q:Can an application have multiple classes having main method?

________________________________________________________________________
QEdge TECHNOLOGIES: # 204, 2nd Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
Page | 51
nd
QEdge TECHNOLOGIES: # 204, 2 Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
A: Yes it is possible. While starting the application we mention the class name to be
run. The JVM will look for the Main method only in the class whose name you have
mentioned. Hence there is not conflict amongst the multiple classes having main
method.

Q:Can I have multiple main methods in the same class?

A: No the program fails to compile. The compiler says that the main method is already
defined in the class.

Q:Do I need to import java.lang package any time? Why ?

A: No. It is by default loaded internally by the JVM.

Q:Can I import same package/class twice? Will the JVM load the package twice at
runtime?
A: One can import the same package or same class multiple times. Neither compiler
nor JVM complains abt it. And the JVM will internally load the class only once no
matter how many times you import the same class.

Q:What are Checked and UnChecked Exception?

A: A checked exception is some subclass of Exception (or Exception itself), excluding


class RuntimeException and its subclasses.
Making an exception checked forces client programmers to deal with the possibility
that the exception will be thrown. eg, IOException thrown by

________________________________________________________________________
QEdge TECHNOLOGIES: # 204, 2nd Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
Page | 52
nd
QEdge TECHNOLOGIES: # 204, 2 Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
java.io.FileInputStream's read() method·
Unchecked exceptions are RuntimeException and any of its subclasses. Class Error
and its subclasses also are unchecked. With an unchecked exception, however, the
compiler doesn't force client programmers either to catch the
exception or declare it in a throws clause. In fact, client programmers may not
even know that the exception could be thrown. eg,
StringIndexOutOfBoundsException thrown by String's charAt() method· Checked
exceptions must be caught at compile time. Runtime exceptions do not need to be.
Errors often cannot be.

Q: What is Overriding?

A: When a class defines a method using the same name, return type, and arguments
as a method in its superclass, the method in the class overrides the method in the
superclass.
When the method is invoked for an object of the class, it is the new definition of
the method that is called, and not the method definition from superclass.
Methods may be overridden to be more public, not more private.

Q:What are different types of inner classes?

A: Nested top-level classes, Member classes, Local classes, Anonymous classes

Nested top-level classes- If you declare a class within a class and specify the
static modifier, the compiler treats the class just like any other top-level class.
Any class outside the declaring class accesses the nested class with the declaring
class name acting similarly to a package. eg, outer.inner. Top-level inner classes
implicitly have access only to static variables.There can also be inner interfaces.
All of these are of the nested top-level variety.

________________________________________________________________________
QEdge TECHNOLOGIES: # 204, 2nd Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
Page | 53
nd
QEdge TECHNOLOGIES: # 204, 2 Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 

Member classes - Member inner classes are just like other member methods and
member variables and access to the member class is restricted, just like methods
and variables. This means a public member class acts similarly to a nested top-level
class. The primary difference between member classes and nested top-level classes
is that member classes have access to the specific instance of the enclosing class.

Local classes - Local classes are like local variables, specific to a block of code.
Their visibility is only within the block of their declaration. In order for the class to
be useful beyond the declaration block, it would need to implement a
more publicly available interface.Because local classes are not members, the
modifiers public, protected, private, and static are not usable.

Anonymous classes - Anonymous inner classes extend local inner classes one level
further. As anonymous classes have no name, you cannot provide a constructor.

Q: Are the imports checked for validity at compile time? e.g. will the code
containing an import such as java.lang.ABCD compile?
A: Yes the imports are checked for the semantic validity at compile time. The code
containing above line of import will not compile. It will throw an error saying,can not
resolve symbol
symbol : class ABCD
location: package io
import java.io.ABCD;

Q: Does importing a package imports the subpackages as well? e.g. Does importing
com.MyTest.* also import com.MyTest.UnitTests.*?

________________________________________________________________________
QEdge TECHNOLOGIES: # 204, 2nd Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
Page | 54
nd
QEdge TECHNOLOGIES: # 204, 2 Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
A: No you will have to import the subpackages explicitly. Importing com.MyTest.* will
import classes in the package MyTest only. It will not import any class in any of it's
subpackage.

Q: What is the difference between declaring a variable and defining a variable?


A: In declaration we just mention the type of the variable and it's name. We do not
initialize it. But defining means declaration + initialization.
e.g String s; is just a declaration while String s = new String ("abcd"); Or String s =
"abcd"; are both definitions.

Q:Can a top level class be private or protected?


A: No. A top level class can not be private or protected. It can have either "public" or
no modifier. If it does not have a modifier it is supposed to have a default access.If
a top level class is declared as private the compiler will complain that the
"modifier private is not allowed here". This means that a top level class can not be
private. Same is the case with protected.

Q: What type of parameter passing does Java support?


A: In Java the arguments are always passed by value.

Q: Objects are passed by value or by reference?


A: Java only supports pass by value. With objects, the object reference itself is
passed by value and so both the original reference and parameter copy both refer to
the same object.

Q: What is Externalizable interface?

________________________________________________________________________
QEdge TECHNOLOGIES: # 204, 2nd Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
Page | 55
nd
QEdge TECHNOLOGIES: # 204, 2 Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
A: Externalizable is an interface which contains two methods readExternal and
writeExternal. These methods give you a control over the serialization mechanism.
Thus if your class implements this interface, you can customize the serialization
process by implementing these methods.

Oops Interview Questions:

1. What are the principle concepts of OOPS?


There are four principle concepts upon which object oriented design and
programming rest. They are:

• Abstraction
• Polymorphism
• Inheritance
• Encapsulation

(i.e. easily remembered as A-PIE).

2. What is Abstraction?

Abstraction refers to the act of representing essential features without including the
background details or explanations.

2. What is Encapsulation?

Encapsulation is a technique used for hiding the properties and behaviors of an object
and allowing outside access only as appropriate. It prevents other objects from
directly altering or accessing the properties or methods of the encapsulated object.

3. What is the difference between abstraction and encapsulation?

________________________________________________________________________
QEdge TECHNOLOGIES: # 204, 2nd Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
Page | 56
nd
QEdge TECHNOLOGIES: # 204, 2 Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
• Abstraction focuses on the outside view of an object (i.e. the interface)
Encapsulation (information hiding) prevents clients from seeing it’s inside
view, where the behavior of the abstraction is implemented.
• Abstraction solves the problem in the design side while Encapsulation is the
Implementation.
• Encapsulation is the deliverables of Abstraction. Encapsulation barely talks
about grouping up your abstraction to suit the developer needs.

4. What is Inheritance?

• Inheritance is the process by which objects of one class acquire the properties
of objects of another class.
• A class that is inherited is called a superclass.
• The class that does the inheriting is called a subclass.
• Inheritance is done by using the keyword extends.
• The two most common reasons to use inheritance are:
o To promote code reuse
o To use polymorphism

5. What is Polymorphism?

Polymorphism is briefly described as "one interface, many implementations."


Polymorphism is a characteristic of being able to assign a different meaning or usage
to something in different contexts - specifically, to allow an entity such as a variable,
a function, or an object to have more than one form.

6. How does Java implement polymorphism?

________________________________________________________________________
QEdge TECHNOLOGIES: # 204, 2nd Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
Page | 57
nd
QEdge TECHNOLOGIES: # 204, 2 Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
(Inheritance, Overloading and Overriding are used to achieve Polymorphism in java).
Polymorphism manifests itself in Java in the form of multiple methods having the
same name.

• In some cases, multiple methods have the same name, but different formal
argument lists (overloaded methods).
• In other cases, multiple methods have the same name, same return type, and
same formal argument list (overridden methods).

7. Explain the different forms of Polymorphism.

There are two types of polymorphism one is Compile time polymorphism and the
other is run time polymorphism. Compile time polymorphism is method overloading.
Runtime time polymorphism is done using inheritance and interface.
Note: From a practical programming viewpoint, polymorphism manifests itself in
three distinct forms in Java:

• Method overloading
• Method overriding through inheritance
• Method overriding through the Java interface

8.What is runtime polymorphism or dynamic method dispatch?

In Java, runtime polymorphism or dynamic method dispatch is a process in which a


call to an overridden method is resolved at runtime rather than at compile-time. In
this process, an overridden method is called through the reference variable of a
superclass. The determination of the method to be called is based on the object being
referred to by the reference variable.

________________________________________________________________________
QEdge TECHNOLOGIES: # 204, 2nd Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
Page | 58
nd
QEdge TECHNOLOGIES: # 204, 2 Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 

10.What is Dynamic Binding?

Binding refers to the linking of a procedure call to the code to be executed in


response to the call. Dynamic binding (also known as late binding) means that the
code associated with a given procedure call is not known until the time of the call at
run-time. It is associated with polymorphism and inheritance.

11.What is method overloading?

Method Overloading means to have two or more methods with same name in the same
class with different arguments. The benefit of method overloading is that it allows
you to implement methods that support the same semantic operation but differ by
argument number or type.
Note:

• Overloaded methods MUST change the argument list


• Overloaded methods CAN change the return type
• Overloaded methods CAN change the access modifier
• Overloaded methods CAN declare new or broader checked exceptions
• A method can be overloaded in the same class or in a subclass

12.What is method overriding?

Method overriding occurs when sub class declares a method that has the same type
arguments as a method declared by one of its superclass. The key benefit of
overriding is the ability to define behavior that’s specific to a particular subclass
type.
Note:

________________________________________________________________________
QEdge TECHNOLOGIES: # 204, 2nd Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
Page | 59
nd
QEdge TECHNOLOGIES: # 204, 2 Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
• The overriding method cannot have a more restrictive access modifier than the
method being overridden (Ex: You can’t override a method marked public and
make it protected).
• You cannot override a method marked final
• You cannot override a method marked static

13.What are the differences between method overloading and method overriding?

Overloaded Method Overridden Method

Arguments Must change Must not change

Return type Can change Can’t change except for


covariant returns

Exceptions Can change Can reduce or eliminate. Must


not throw new or broader
checked exceptions

Access Can change Must not make more restrictive


(can be less restrictive)

Invocation Reference type determines which Object type determines which


overloaded version is selected. method is selected. Happens at
Happens at compile time. runtime.

14.Can overloaded methods be override too?

Yes, derived classes still can override the overloaded methods. Polymorphism can still
happen. Compiler will not binding the method calls since it is overloaded, because it
might be overridden now or in the future.
________________________________________________________________________
QEdge TECHNOLOGIES: # 204, 2nd Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
Page | 60
nd
QEdge TECHNOLOGIES: # 204, 2 Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 

15.Is it possible to override the main method?

NO, because main is a static method. A static method can't be overridden in Java.

16.How to invoke a superclass version of an Overridden method?

To invoke a superclass method that has been overridden in a subclass, you must either
call the method directly through a superclass instance, or use the super prefix in the
subclass itself. From the point of the view of the subclass, the super prefix provides
an explicit reference to the superclass' implementation of the method.

// From subclass
super.overriddenMethod();

17.What is super?

super is a keyword which is used to access the method or member variables from the
superclass. If a method hides one of the member variables in its superclass, the
method can refer to the hidden variable through the use of the super keyword. In the
same way, if a method overrides one of the methods in its superclass, the method can
invoke the overridden method through the use of the super keyword.
Note:

• You can only go back one level.


• In the constructor, if you use super(), it must be the very first code, and you
cannot access any this.xxx variables or methods to compute its parameters.

________________________________________________________________________
QEdge TECHNOLOGIES: # 204, 2nd Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
Page | 61
nd
QEdge TECHNOLOGIES: # 204, 2 Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
31.What is Constructor?

• A constructor is a special method whose task is to initialize the object of its


class.
• It is special because its name is the same as the class name.
• They do not have return types, not even void and therefore they cannot return
values.
• They cannot be inherited, though a derived class can call the base class
constructor.
• Constructor is invoked whenever an object of its associated class is created.

32.How does the Java default constructor be provided?

If a class defined by the code does not have any constructor, compiler will
automatically provide one no-parameter-constructor (default-constructor) for the
class in the byte code. The access modifier (public/private/etc.) of the default
constructor is the same as the class itself.

33.Can constructor be inherited?

No, constructor cannot be inherited, though a derived class can call the base class
constructor.

34.What are the differences between Contructors and Methods?

Constructors Methods

Purpose Create an instance of a class Group Java statements

________________________________________________________________________
QEdge TECHNOLOGIES: # 204, 2nd Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
Page | 62
nd
QEdge TECHNOLOGIES: # 204, 2 Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
Modifiers Cannot be abstract, final, native, Can be abstract, final, native,
static, or synchronized static, or synchronized

Return Type No return type, not even void void or a valid return type

Name Same name as the class (first Any name except the class.
letter is capitalized by Method names begin with a
convention) -- usually a noun lowercase letter by convention --
usually the name of an action

this Refers to another constructor in Refers to an instance of the


the same class. If used, it must owning class. Cannot be used by
be the first line of the static methods.
constructor

super Calls the constructor of the Calls an overridden method in the


parent class. If used, must be the parent class
first line of the constructor

Inheritance Constructors are not inherited Methods are inherited

35.How are this() and super() used with constructors?

• Constructors use this to refer to another constructor in the same class with a
different parameter list.
• Constructors use super to invoke the superclass's constructor. If a constructor
uses super, it must use it in the first line; otherwise, the compiler will
complain.

36.What are the differences between Class Methods and Instance Methods?
________________________________________________________________________
QEdge TECHNOLOGIES: # 204, 2nd Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
Page | 63
nd
QEdge TECHNOLOGIES: # 204, 2 Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 

Class Methods Instance Methods

Instance methods on the other hand


require an instance of the class to exist
Class methods are methods which are
before they can be called, so an instance
declared as static. The method can be
of a class needs to be created by using
called without creating an instance of the
the new keyword.
class
Instance methods operate on specific
instances of classes.

Class methods can only operate on class Instance methods of the class can also
members and not on instance members as not be called from within a class method
class methods are unaware of instance unless they are being called on an
members. instance of that class.

Class methods are methods which are


declared as static. The method can be Instance methods are not declared as
called without creating an instance of static.
the class.

37.How are this() and super() used with constructors?

• Constructors use this to refer to another constructor in the same class with a
different parameter list.
• Constructors use super to invoke the superclass's constructor. If a constructor
uses super, it must use it in the first line; otherwise, the compiler will
complain.

38.What are Access Specifiers?

________________________________________________________________________
QEdge TECHNOLOGIES: # 204, 2nd Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
Page | 64
nd
QEdge TECHNOLOGIES: # 204, 2 Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
One of the techniques in object-oriented programming is encapsulation. It concerns
the hiding of data in a class and making this class available only through methods.
Java allows you to control access to classes, methods, and fields via so-called access
specifiers..

39.What are Access Specifiers available in Java?

Java offers four access specifiers, listed below in decreasing accessibility:

• Public- public classes, methods, and fields can be accessed from everywhere.
• Protected- protected methods and fields can only be accessed within the same
class to which the methods and fields belong, within its subclasses, and within
classes of the same package.
• Default(no specifier)- If you do not set access to specific level, then such a
class, method, or field will be accessible from inside the same package to
which the class, method, or field belongs, but not from outside this package.
• Private- private methods and fields can only be accessed within the same class
to which the methods and fields belong. private methods and fields are not
visible within subclasses and are not inherited by subclasses.

Situation public protected default private

Accessible to class
yes yes yes no
from same package?

Accessible to class
yes no, unless it is a subclass no no
from different package?

40.What is final modifier?

________________________________________________________________________
QEdge TECHNOLOGIES: # 204, 2nd Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
Page | 65
nd
QEdge TECHNOLOGIES: # 204, 2 Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
The final modifier keyword makes that the programmer cannot change the value
anymore. The actual meaning depends on whether it is applied to a class, a variable,
or a method.

• final Classes- A final class cannot have subclasses.


• final Variables- A final variable cannot be changed once it is initialized.
• final Methods- A final method cannot be overridden by subclasses.

41.What are the uses of final method?

There are two reasons for marking a method as final:

• Disallowing subclasses to change the meaning of the method.


• Increasing efficiency by allowing the compiler to turn calls to the method into
inline Java code.

42.What is static block?

Static block which exactly executed exactly once when the class is first loaded into
JVM. Before going to the main method the static block will execute.

43.What are static variables?

Variables that have only one copy per class are known as static variables. They are
not attached to a particular instance of a class but rather belong to a class as a
whole. They are declared by using the static keyword as a modifier.

static type varIdentifier;

________________________________________________________________________
QEdge TECHNOLOGIES: # 204, 2nd Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
Page | 66
nd
QEdge TECHNOLOGIES: # 204, 2 Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
where, the name of the variable is varIdentifier and its data type is specified by type.
Note: Static variables that are not explicitly initialized in the code are automatically
initialized with a default value. The default value depends on the data type of the
variables.

44.What is the difference between static and non-static variables?

A static variable is associated with the class as a whole rather than with specific
instances of a class. Non-static variables take on unique values with each object
instance.

45.What are static methods?

Methods declared with the keyword static as modifier are called static methods or
class methods. They are so called because they affect a class as a whole, not a
particular instance of the class. Static methods are always invoked without reference
to a particular instance of a class.
Note:The use of a static method suffers from the following restrictions:

• A static method can only call other static methods.


• A static method must only access static data.
• A static method cannot reference to the current object using keywords super
or this.

________________________________________________________________________
QEdge TECHNOLOGIES: # 204, 2nd Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
Page | 67
nd
QEdge TECHNOLOGIES: # 204, 2 Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 

Selenium

1. Why Testing?

________________________________________________________________________
QEdge TECHNOLOGIES: # 204, 2nd Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
Page | 68
nd
QEdge TECHNOLOGIES: # 204, 2 Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
• To eliminate the errors or defects and improve the quality of application

2. Why defects occur?

¾ Hard coding
¾ While integrating the modules
¾ Lack of documentation
¾ Miscommunication
¾ Time pressure
¾ Dynamically changing requirements

3. What is automation Testing?


It is a process of implementing particular work automatically by using a machine, to
reduce the need of human work in the production of goods and services...

4. What is meant by Automation in software testing?


It is a process of testing an application(executing the tests, comparing expected and
actual results under some controlled conditions and generating the reports)
automatically by using a 'Tool' to reduce the need of human effort. This tool may be
Selenium / QTP / RFT / SilkTest /sahi/watir etc…

5. Why you choose selenium?


¾ Selenium is a open source tool
¾ It can Automate any Web Application
¾ It is a perfect tool for Browser Automation
¾ In the market very demand Automation Tool
¾ Around 60-70% companies are using selenium
¾ In future it may be 90%
¾ Job opportunities are very high
________________________________________________________________________
QEdge TECHNOLOGIES: # 204, 2nd Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
Page | 69
nd
QEdge TECHNOLOGIES: # 204, 2 Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
¾ Once we prepare the code in the windows platform we can run in any OS,
platform independent.
¾ We can integrate with No. of tools and languages

6. Types of Automation Tools


¾ Functional Automation Tools: QTP, Winrunner, Silktest, Selenium, Sahi, watir
etc.
¾ Performance Tools: LoadRunner, RFT, SOAP etc.
¾ Management tools: Test Director, Quality center, Testlink, Rally etc.
¾ Bugtracking tools: Jira, Bagzilla
¾ Build Tools: ANT and Rake

7. What is Selenium?
¾ Selenium is Functional Automation tool
¾ Selenium is Browser or Web based Automation Tool
¾ Selenium is suite of tools, SeleniumIDE, RC, WebDriver, Grid
¾ It can record or automate any web application but it can’t support for client or
desktop application.
¾ It can support many languages java, C#, Ruby, python
¾ Data driven is possible
¾ User can enhance script in any following language JAVA, C#, PHP, Ruby,
Python
¾ Selenium is a Functional Testing Tool can be used for Regression testing of Web
applications in a variety of browsers and platforms
¾ Selenium was developed by ThoughtWorks, now takeover by sauce labs.
¾ It's an Open Source Tool
¾ Selenium supported platforms are Windows, Linux, Mac OS

________________________________________________________________________
QEdge TECHNOLOGIES: # 204, 2nd Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
Page | 70
nd
QEdge TECHNOLOGIES: # 204, 2 Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
1. What to Automate or Not to Automate?
Is automation always advantageous? When should one decide to automate test cases?
It is not always advantageous to automate test cases. There are times when manual
testing may be more appropriate. For instance, if the application’s user interface will
change considerably in the near future, then any automation would need to be
rewritten. Also, sometimes there simply is not enough time to build test automation.
For the short term, manual testing may be more effective. If an application has a very
tight deadline, there is currently no test automation available, and it’s imperative
that the testing get done within that time frame, then manual testing is the best
solution. However, automation has specific advantages for improving the long-term
efficiency of a software team’s testing processes.

Test automation supports:


• Frequent regression testing
• Rapid feedback to developers during the development process
• Virtually unlimited iterations of test case execution
• Customized reporting of application defects
• Support for Agile and eXtreme development methodologies
• Disciplined documentation of test cases
• Finding defects missed by manual testing

________________________________________________________________________
QEdge TECHNOLOGIES: # 204, 2nd Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
Page | 71
nd
QEdge TECHNOLOGIES: # 204, 2 Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 

5. Test Automation for Web Applications?


Many, perhaps most, software applications today are written as web-based
applications to be run in an Internet browser. The effectiveness of testing these
applications varies widely among companies and organizations. In an era of
continuously improving software processes, such as eXtreme programming (XP) and
Agile, it can be argued that disciplined testing and quality assurance practices are
still underdeveloped in many organizations. Software testing is often conducted
manually. At times, this is effective; however there are alternatives to manual testing
that many organizations are unaware of, or lack the skills to perform. Utilizing these
alternatives would in most cases greatly improve the efficiency of their software
development by adding efficiencies to their testing. Test automation is often the
answer. Test automation means using a tool to run repeatable tests against the target
application whenever necessary.

3. Introducing Selenium
Selenium is a robust set of tools that supports rapid development of test automation
for web-based applications. Selenium provides a rich set of testing functions
specifically geared to the needs of testing of a web application. These operations are
highly flexible, allowing many options for locating UI elements and comparing
expected test results against actual application behavior. One of Selenium’s key
features is the support for executing one’s tests on multiple browser platforms.

4. Selenium Components
Selenium is composed of three major tools. Each one has a specific role in aiding the
development of web application test automation.

________________________________________________________________________
QEdge TECHNOLOGIES: # 204, 2nd Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
Page | 72
nd
QEdge TECHNOLOGIES: # 204, 2 Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 

4.1 Selenium-IDE
Selenium-IDE is the Integrated Development Environment for building Selenium test
cases. It operates as a Firefox add-on and provides an easy-to-use interface for
developing and running individual test cases or entire test suites. Selenium-IDE has a
recording feature, which will keep account of user actions as they are performed and
store them as a reusable script to play back. It also has a context menu (right-click)
integrated with the Firefox browser, which allows the user to pick from a list of
assertions and verifications for the selected location. Selenium-IDE also offers full
editing of test cases for more precision and control. Although Selenium-IDE is a
Firefox only add-on, tests created in it can also be run against other browsers by using
Selenium-RC and specifying the name of the test suite on the command line.

4.2 Selenium-RC (Remote Control)


Selenium-RC allows the test automation developer to use a programming language for
maximum flexibility and extensibility in developing test logic. For instance, if the
application under test returns a result set, and if the automated test program needs
to run tests on each element in the result set, the programming language’s iteration
support can be used to iterate through the result set, calling Selenium commands to
run tests on each item.
Selenium-RC provides an API (Application Programming Interface) and library for each
of its supported languages: HTML, Java, C#, Perl, PHP, Python, and Ruby. This ability
to use Selenium-RC with a highlevel programming language to develop test cases also
allows the automated testing to be integrated with a project’s automated build
environment.

________________________________________________________________________
QEdge TECHNOLOGIES: # 204, 2nd Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
Page | 73
nd
QEdge TECHNOLOGIES: # 204, 2 Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 

4.3 Selenium-Grid
Selenium-Grid allows the Selenium-RC solution to scale for large test suites or test
suites that must be run in multiple environments. With Selenium-Grid, multiple
instances of Selenium-RC are running on various operating system and browser
configurations. Each of these when launching register with a hub. When tests are sent
to the hub they are then redirected to an available Selenium-RC, which will launch
the browser and run the test. This allows for running tests in parallel, with the entire
test suite theoretically taking only as long to run as the longest individual test.

Selenium 1.0 and Selenium-RC.


This is the old, support platform for Selenium 1.0. It should still apply to the Selenium
2.0 release of Selenium-RC.

Browser Selenium IDE Selenium 1 (RC) Operating


Systems
Firefox 3 Record and playback tests Start browser, run Windows, Linux,
tests Mac
Firefox 2 Record and playback tests Start browser, run Windows, Linux,
tests Mac
IE 8 Test execution only via Start browser, run Windows, Linux,
Selenium RC* tests Mac
IE 7 Test execution only via Start browser, run Windows
Selenium RC* tests
IE 6 Test execution only via Start browser, run Windows
Selenium RC* tests

________________________________________________________________________
QEdge TECHNOLOGIES: # 204, 2nd Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
Page | 74
nd
QEdge TECHNOLOGIES: # 204, 2 Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
Safari 4 Test execution only via Start browser, run Windows
Selenium RC* tests
Safari 3 Test execution only via Start browser, run Windows, Mac
Selenium RC* tests
Safari 2 Test execution only via Start browser, run Windows, Mac
Selenium RC* tests
Opera 10 Test execution only via Start browser, run Windows, Mac
Selenium RC* tests
Opera 9 Test execution only via Start browser, run Windows, Linux,
Selenium RC* tests Mac
Opera 8 Test execution only via Start browser, run Windows, Linux,
Selenium RC* tests Mac
Google Test execution only via Start browser, run Windows, Linux,
Chrome Selenium RC* tests Mac
Others Test execution only via Partial support As applicable
Selenium RC* possible**

________________________________________________________________________
QEdge TECHNOLOGIES: # 204, 2nd Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
Page | 75
nd
QEdge TECHNOLOGIES: # 204, 2 Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 

Selenium IDE

4.1 Introduction
The Selenium-IDE (Integrated Development Environment) is the tool you use to
develop your Selenium test cases. It’s an easy-to-use Firefox plug-in and is generally
the most efficient way to develop test cases. It also contains a context menu that
allows you to first select a UI element from the browser’s currently displayed page
and then select from a list of Selenium commands with parameters pre-defined
according to the context of the selected UI element. This is not only a time-saver, but
also an excellent way of learning Selenium script syntax. This chapter is all about the
Selenium IDE and how to use it effectively.

________________________________________________________________________
QEdge TECHNOLOGIES: # 204, 2nd Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
Page | 76
nd
QEdge TECHNOLOGIES: # 204, 2 Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 

4.2 Installing the IDE


Using Firefox, first, download the IDE from the Seleniumhq.org downloads page
When downloading from Firefox, you’ll be presented with the following window.

After Installing Selenium IDE will display like below:

________________________________________________________________________
QEdge TECHNOLOGIES: # 204, 2nd Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
Page | 77
nd
QEdge TECHNOLOGIES: # 204, 2 Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 

________________________________________________________________________
QEdge TECHNOLOGIES: # 204, 2nd Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
Page | 78
nd
QEdg
ge TECHNOOLOGIES: # 204, 2 Floor, Nagassuri Plaza, Ameerpet, Hyderabad
d.
Email: info@qedge
etech.com,, ph:040-64
4644491/922, 77029444
491.
 

_______
__________
__________
_________
__________
__________
__________
__________
____
QEdg
ge TECHNOOLOGIES: # 204, 2nd Floor, Nagassuri Plaza, Ameerpet, Hyderabad
d.
Email: info@qedge
etech.com,, ph:040-64
4644491/92 2, 77029444
491.
 
Page | 79
nd
QEdge TECHNOLOGIES: # 204, 2 Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 

1. IDE Features
1.1 Menu Bar
The File menu allows you to create, open and save test case and test suite files. The
Edit menu allows copy, paste, delete, undo and select all operations for editing the
commands in your test case. The Options menu allows the changing of settings. You
can set the timeout value for certain commands, add user-defined user extensions to
the base set of Selenium commands, and specify the format (language) used when
saving your test cases. The Help menu is the standard Firefox Help menu; only one
item on this menu–UI-Element Documentation–pertains to Selenium-IDE.

1.2 Toolbar
The toolbar contains buttons for controlling the execution of your test cases,
including a step feature for debugging your test cases. The right-most button, the one
with the red-dot, is the record button.

Speed Control: controls how fast your test case runs.

Run All: Runs the entire test suite when a test suite with multiple test cases
is loaded.

________________________________________________________________________
QEdge TECHNOLOGIES: # 204, 2nd Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
Page | 80
nd
QEdge TECHNOLOGIES: # 204, 2 Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
Run: Runs the currently selected test. When only a single test is loaded this
button and the Run All button have the same effect.

Pause/Resume: Allows stopping and re-starting of a running test case.

Step: Allows one to “step” through a test case by running it one command at a
time. Use for debugging test cases.

Record: Records the user’s browser actions.

1.3 Test Case Pane


Your script is displayed in the test case pane. It has two tabs, one for displaying the
command and their parameters in a readable “table” format.

________________________________________________________________________
QEdge TECHNOLOGIES: # 204, 2nd Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
Page | 81
nd
QEdge TECHNOLOGIES: # 204, 2 Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 

1.4 Editing

Insert Command
Table View
Select the point in your test case where you want to insert the command. Right-click
and select Insert Command. Now use the command editing text fields to enter your
new command and its parameters.

Source View
Select the point in your test case where you want to insert the command, and enter
the HTML tags needed to create a 3-column row containing the Command, first
parameter (if one is required by the Command), and second parameter (again, if one
is required). Be sure to save your test before switching back to Table view.

Insert Comment
Comments may be added to make your test case more readable. These comments are
ignored when the test case is run.In order to add vertical white space (one or more
blank lines) in your tests, you must create empty comments. An empty command will
cause an error during execution.

Table View
Select the point in your test case where you want to insert the comment. Right-click
and select Insert Comment. Now use the Command field to enter the comment. Your
comment will appear in purple font.

________________________________________________________________________
QEdge TECHNOLOGIES: # 204, 2nd Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
Page | 82
nd
QEdge TECHNOLOGIES: # 204, 2 Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 

Source View:
Select the point in your test case where you want to insert the comment. Add an
HTML-style comment, i.e., <!– your comment here –>.

Edit a Command or Comment


Table View
Simply select the line to be changed and edit it using the Command, Target, and
Value fields.

Source View
Since Source view provides the equivalent of a WYSIWYG editor, simply modify which
line you wish– command, parameter, or comment.

1.5 Opening and Saving a Test Case


The File=>Open, Save and Save As menu commands behave similarly to opening and
saving files in most other programs. When you open an existing test case, Selenium-
IDE displays its Selenium commands in the test case pane.

Test suite files can also be opened and saved via the File menu. However, such
operations have their own menu entries near the bottom; the Open, Save, and Save As
items are only for files.
Note: At the time of this writing, there’s a bug, where at times, when the IDE is first
opened and then you select File=>Open, nothing happens. If you see this, close down

________________________________________________________________________
QEdge TECHNOLOGIES: # 204, 2nd Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
Page | 83
nd
QEdge TECHNOLOGIES: # 204, 2 Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
the IDE and restart it (you don’t need to close the browser itself). This will fix the
problem.

1.6 Running Test Cases


The IDE allows many options for running your test case. You can run a test case all at
once, stop and start it, run it one line at a time, run a single command you are
currently developing, and you can do a batch run of an entire test suite. Execution of
test cases is very flexible in the IDE.

Run a Test Case Click the Run button to run the currently displayed test case.

Run a Test Suite Click the Run All button to run all the test cases in the currently
loaded test suite.

Stop and Start The Pause button can be used to stop the test case while it is running.
The icon of this button then changes to indicate the Resume button. To continue click
Resume.

Stop in the Middle You can set a breakpoint in the test case to cause it to stop on a
particular command. This is useful for debugging your test case. To set a breakpoint,
select a command, right-click, and from the context menu select Toggle Breakpoint.

Start from the Middle You can tell the IDE to begin running from a specific command
in the middle of the test case. This also is used for debugging. To set a startpoint,
select a command, right-click, and from the context menu select Set/Clear Start
Point.

________________________________________________________________________
QEdge TECHNOLOGIES: # 204, 2nd Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
Page | 84
nd
QEdge TECHNOLOGIES: # 204, 2 Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
Run Any Single Command Double-click any single command to run it by itself. This is
useful when writing a single command. It lets you immediately test a command you
are constructing, when you are not sure if it is correct. You can double-click it to see
if it runs correctly. This is also available from the context menu.

SELENIUM-RC

________________________________________________________________________
QEdge TECHNOLOGIES: # 204, 2nd Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
Page | 85
nd
QEdge TECHNOLOGIES: # 204, 2 Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 

1. Introduction
Selenium-RC is the solution for tests that need more than simple browser actions and
linear execution. Selenium-RC uses the full power of programming languages to create
more complex tests like reading and writing files, querying a database, emailing test
results.

You’ll want to use Selenium-RC whenever your test requires logic not supported by
Selenium-IDE. What logic could this be? For example, Selenium-IDE does not directly
support:

¾ condition statements

¾ iteration

¾ logging and reporting of test results

¾ error handling, particularly unexpected errors

¾ database testing

¾ test case grouping

¾ re-execution of failed tests

¾ test case dependency

¾ screenshot capture of test failures


________________________________________________________________________
QEdge TECHNOLOGIES: # 204, 2nd Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
Page | 86
nd
QEdge TECHNOLOGIES: # 204, 2 Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 

Although these tasks are not supported by Selenium directly, all of them can be
achieved by using programming techniques with a language-specific Selenium-RC
client library.

In the Adding Some Spice to Your Tests section, you’ll find examples that demonstrate
the advantages of using a programming language for your tests.

2. How Selenium-RC Works


First, we will describe how the components of Selenium-RC operate and the role each
plays in running your test scripts.

5.1 RC Components

Selenium-RC components are:

¾ The Selenium Server which launches and kills browsers, interprets and runs the
Selenese commands passed from the test program, and acts as an HTTP proxy,
intercepting and verifying HTTP messages passed between the browser and the
AUT.

¾ Client libraries which provide the interface between each programming


language and the Selenium-RC Server.

Here is a simplified architecture diagram....

________________________________________________________________________
QEdge TECHNOLOGIES: # 204, 2nd Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
Page | 87
nd
QEdge TECHNOLOGIES: # 204, 2 Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 

The diagram shows the client libraries communicate with the Server passing each
Selenium command for execution. Then the server passes the Selenium command to
the browser using Selenium-Core JavaScript commands. The browser, using its
JavaScript interpreter, executes the Selenium command. This runs the Selenese
action or verification you specified in your test script.

2.2 Selenium Server

________________________________________________________________________
QEdge TECHNOLOGIES: # 204, 2nd Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
Page | 88
nd
QEdge TECHNOLOGIES: # 204, 2 Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
Selenium Server receives Selenium commands from your test program, interprets
them, and reports back to your program the results of running those tests.

The RC server bundles Selenium Core and automatically injects it into the browser.
This occurs when your test program opens the browser (using a client library API
function). Selenium-Core is a JavaScript program, actually a set of JavaScript
functions which interprets and executes Selenese commands using the browser’s
built-in JavaScript interpreter.

The Server receives the Selenese commands from your test program using simple
HTTP GET/POST requests. This means you can use any programming language that can
send HTTP requests to automate Selenium tests on the browser.

2.3 Client Libraries


The client libraries provide the programming support that allows you to run Selenium
commands from a program of your own design. There is a different client library for
each supported language. A Selenium client library provides a programming interface
(API), i.e., a set of functions, which run Selenium commands from your own program.
Within each interface, there is a programming function that supports each Selenese
command.

The client library takes a Selenese command and passes it to the Selenium Server for
processing a specific action or test against the application under test (AUT). The
client library also receives the result of that command and passes it back to your
program. Your program can receive the result and store it into a program variable and
reporting it as a success or failure, or possibly taking corrective action if it was an
unexpected error.

So to create a test program, you simply write a program that runs a set of Selenium
commands using a client library API. And, optionally, if you already have a Selenese
________________________________________________________________________
QEdge TECHNOLOGIES: # 204, 2nd Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
Page | 89
nd
QEdge TECHNOLOGIES: # 204, 2 Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
test script created in the Selenium-IDE, you can generate the Selenium-RC code. The
Selenium-IDE can translate (using its Export menu item) its Selenium commands into a
client-driver’s API function calls. See the Selenium-IDE chapter for specifics on
exporting RC code from Selenium-IDE.

2.3 Installation
After downloading the Selenium-RC zip file from the downloads page, you’ll notice it
has several subfolders. These folders have all the components you need for using
Selenium-RC with the programming language of your choice.

Once you’ve chosen a language to work with, you simply need to:

¾ Install the Selenium-RC Server.


¾ Set up a programming project using a language specific client driver.

5.2 Installing Selenium Server

The Selenium-RC server is simply a Java jar file (selenium-server.jar), which doesn’t
require any special installation. Just downloading the zip file and extracting the
server in the desired directory is sufficient.

3.2 Running Selenium Server


Before starting any tests you must start the server. Go to the directory where
Selenium-RC’s server is located and run the following from a command-line console.

java -jar selenium-server.jar

________________________________________________________________________
QEdge TECHNOLOGIES: # 204, 2nd Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
Page | 90
nd
QEdge TECHNOLOGIES: # 204, 2 Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
This can be simplified by creating a batch or shell executable file (.bat on Windows
and .sh on Linux) containing the command above. Then make a shortcut to that
executable on your desktop and simply double-click the icon to start the server.

For the server to run you’ll need Java installed and the PATH environment variable
correctly configured to run it from the console. You can check that you have Java
correctly installed by running the following on a console:

java –version

If you get a version number (which needs to be 1.5 or later), you’re ready to start
using Selenium-RC.

3.3 Using the Java Client Driver

¾ Download Selenium-RC from the SeleniumHQ downloads page.


¾ Extract the file selenium-java-client-driver.jar.
¾ Open your desired Java IDE (Eclipse, NetBeans, IntelliJ, Netweaver, etc.)
¾ Create a new project.
¾ Add the selenium-java-client-driver.jar files to your project as references.
¾ Add to your project classpath the file selenium-java-client-driver.jar.
¾ From Selenium-IDE, export a script to a Java file and include it in your Java.
project, or write your Selenium test in Java using the selenium-java-client API.
The API is presented later in this chapter. You can either use JUnit, or TestNg
to run your test, or you can write your own simple main() program. These
concepts are explained later in this section.

¾ Run Selenium server from the console.

________________________________________________________________________
QEdge TECHNOLOGIES: # 204, 2nd Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
Page | 91
nd
QEdge TECHNOLOGIES: # 204, 2 Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
¾ Execute your test from the Java IDE or from the command-line.

Programs:
Selenium RC Basic Program-1:
package SeleniumRC1; 
import com.thoughtworks.selenium.DefaultSelenium; 
import com.thoughtworks.selenium.Selenium; 
public class RCBasic_Prog { 
  public static void main(String[] args) throws Exception 

    Selenium selenium=new DefaultSelenium("localhost", 
4444, "*firefox", "http://google.com"); 
     
    selenium.start();  //it'll start the selenium 
server   
    selenium.open("/"); //open url 
    selenium.windowMaximize();   //window maximize 
    Thread.sleep(3000); 
    //selenium.close();   close 
    selenium.stop();     
________________________________________________________________________
QEdge TECHNOLOGIES: # 204, 2nd Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
Page | 92
nd
QEdge TECHNOLOGIES: # 204, 2 Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
    selenium.setSpeed("3000");     
     
    //Synchronization points or wait points 
    /** 
     * 1.Thread.sleep(3000);  
     * selenium.waitForPageToLoad("3000"); 
     * selenium.waitForPopUp("", "3000") 
     *  
     */         
  }   

 
 
Selenium RC Basic Program-2:

package SeleniumRC1; 
import com.thoughtworks.selenium.DefaultSelenium; 
import com.thoughtworks.selenium.Selenium; 
 
public class getHtmlSource { 
  public static void main(String[] args) { 
    Selenium selenium=new DefaultSelenium("localhost", 
4444, "*firefox", "http://google.com"); 
    selenium.start();     
    selenium.open("/"); 
    selenium.setSpeed("3000"); 
    selenium.windowMaximize(); 
    System.out.println("*********page view 
source******"); 
________________________________________________________________________
QEdge TECHNOLOGIES: # 204, 2nd Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
Page | 93
nd
QEdge TECHNOLOGIES: # 204, 2 Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
    System.out.println(selenium.getHtmlSource()); 
     
  } 

Selenium RC Basic Program-3:


package Selenium_RC; 
import org.junit.Test; 
public class Methodcall { 
   
  @Test 
  public void testcall(){ 
    Junit_Annotations ja=new Junit_Annotations(); 
//Object creating 
    ja.CloseBrowser(); //using the object calling 
methods 
    ja.OpenBrowser(); 
    ja.test1(); 
    ja.test2(); 
  } 

 
Gmail Test Using JUnit Program-4:
package Selenium_RC; 
 
import org.junit.Ignore; 
________________________________________________________________________
QEdge TECHNOLOGIES: # 204, 2nd Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
Page | 94
nd
QEdge TECHNOLOGIES: # 204, 2 Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
import org.junit.Test; 
import com.thoughtworks.selenium.DefaultSelenium; 
import com.thoughtworks.selenium.Selenium; 
 
public class Junit_class { 
  @Test 
  public void gmailtest(){ 
    System.out.println("gmail test"); 
    Selenium selenium=new DefaultSelenium("localhost", 
4444, "*firefox", "http://google.com"); 
    selenium.start();     
    selenium.open("/"); 
    selenium.setSpeed("3000"); 
    selenium.windowMaximize(); 
    System.out.println(selenium.getTitle()); 
    selenium.click("id=gb_23dg"); 
    System.out.println(selenium.getTitle()); 
    selenium.highlight("//*[@id='Email']"); 
    selenium.type("//*[@id='Email']", "sleniummm"); 
    selenium.highlight("//*[@id='Passwd']"); 
    selenium.type("//*[@id='Passwd']", "testing"); 
    selenium.highlight("//*[@id='signIn']"); 
    selenium.click("//*[@id='signIn']"); 
   
  } 
   
  @Test 
  public void test1(){ 
    System.out.println(" test1"); //this test will 
execute 
  } 
   
________________________________________________________________________
QEdge TECHNOLOGIES: # 204, 2nd Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
Page | 95
nd
QEdge TECHNOLOGIES: # 204, 2 Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
  @Ignore 
  public void test2(){ 
    System.out.println("test2");//this test will skip 
  }   

Handle Check boxes Program-5:


package Selenium_RC;
import com.thoughtworks.selenium.DefaultSelenium;
import com.thoughtworks.selenium.Selenium;
public class Handle_Checkboxes {
public static void main(String[] args) throws Exception {
Selenium selenium=new DefaultSelenium("localhost", 4444,
"*firefox", "http://google.com");
selenium.start();
selenium.windowMaximize();

selenium.open("http://www.tizag.com/htmlT/htmlcheckboxes.php"
);
Thread.sleep(2000);
selenium.uncheck("//html/body/table[3]/tbody/tr[1]/td[2]/table/t
body/tr/td/div[6]/input[1]");
Thread.sleep(2000);
selenium.check("//html/body/table[3]/tbody/tr[1]/td[2]/table/tbo
dy/tr/td/div[6]/input[2]");

________________________________________________________________________
QEdge TECHNOLOGIES: # 204, 2nd Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
Page | 96
nd
QEdge TECHNOLOGIES: # 204, 2 Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
Thread.sleep(2000);
}
}
Handle Radio Buttons Program-6:
package Selenium_RC; 
import com.thoughtworks.selenium.DefaultSelenium; 
import com.thoughtworks.selenium.Selenium; 
 
public class Handle_RadioButtons { 
 
  public static void main(String[] args) throws Exception 

    Selenium selenium=new DefaultSelenium("localhost", 
4444, "*firefox", "http://www.tizag.com"); 
    selenium.start(); 
    selenium.windowMaximize(); 
    selenium.open("/htmlT/htmlradio.php"); 
    Thread.sleep(2000); 
   
 
  selenium.click("//html/body/table[3]/tbody/tr[1]/td[2]/t
able/tbody/tr/td/div[4]/input[1]"); 
 
  } 
 
________________________________________________________________________
QEdge TECHNOLOGIES: # 204, 2nd Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
Page | 97
nd
QEdge TECHNOLOGIES: # 204, 2 Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
}
Gmail Get Title using If condition Program-7:
package ExceptionHandling; 
import org.testng.annotations.Test; 
import com.thoughtworks.selenium.DefaultSelenium; 
import com.thoughtworks.selenium.Selenium; 
 
public class IFCondition { 
  @Test 
  public void gmail() throws Exception { 
    Selenium selenium=new DefaultSelenium("localhost", 
4444, "*firefox", "http://google.com"); 
    selenium.start(); 
    selenium.setSpeed("2000"); 
    selenium.windowMaximize(); 
    selenium.open("http://google.com");     
    Thread.sleep(2000); 
    String title=selenium.getTitle(); 
    if(title.equalsIgnoreCase("gmail")){ 
      System.out.println("displaying right title= 
"+title); 
    }else{ 
      System.out.println("it is displaying wrong 
title= "+title); 
    } 
________________________________________________________________________
QEdge TECHNOLOGIES: # 204, 2nd Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
Page | 98
nd
QEdge TECHNOLOGIES: # 204, 2 Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
  } 
 
}

Screenshot Capture and Try catch block Program-8:


package ExceptionHandling; 
 
import org.testng.annotations.Test; 
import com.thoughtworks.selenium.DefaultSelenium; 
import com.thoughtworks.selenium.Selenium; 
 
public class CaptureScreenshot { 
  @Test 
  public void gmail() throws Exception { 
    Selenium selenium=new DefaultSelenium("localhost", 
4444, "*firefox", "http://google.com"); 
    selenium.start(); 
    selenium.setSpeed("2000"); 
    selenium.windowMaximize(); 
    selenium.open("http://gmail.com");     
    Thread.sleep(2000); 
    try{ 

________________________________________________________________________
QEdge TECHNOLOGIES: # 204, 2nd Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
Page | 99
nd
QEdge TECHNOLOGIES: # 204, 2 Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
//    boolean 
exists=selenium.isElementPresent("id=Email888"); 
//    System.out.println(exists);  
    selenium.type("id=Email888", "selenium");    
    selenium.type("id=Passwd", "selenium"); 
    selenium.click("id=signIn"); 
   
    }catch(Throwable t){ 
   
  selenium.captureScreenshot("E:/SeleniumTech/screenshots/
gmail.jpg"); 
      System.out.println("it thown error :taken 
screenshot"); 
    } 
  } 

WebTable Handling using forloop Program-9:


package WebTable;
import org.testng.annotations.Test;
import com.thoughtworks.selenium.DefaultSelenium;
import com.thoughtworks.selenium.Selenium;

public class webtable_forloop {

________________________________________________________________________
QEdge TECHNOLOGIES: # 204, 2nd Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
Page | 100
nd
QEdge TECHNOLOGIES: # 204, 2 Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
@Test
public void gmail() throws Exception {
Selenium selenium=new DefaultSelenium("localhost", 4444,
"*firefox", "http://google.com");
selenium.start();
//selenium.setSpeed("2000");
selenium.windowMaximize();
selenium.open("http://www.timeanddate.com/worldclock/");
Thread.sleep(3000);

//System.out.println(selenium.getText("//html/body/div[11]/table
/tbody/tr[1]/td[2]"));
/*//selenium.click("link=Gmail");
Thread.sleep(5000);
String
text=selenium.getText("//*[@id='main']/table[1]/tbody/tr[2]/td[3]");
System.out.println(text);*/
for(int i=1;i<=36;i++){
for(int j=1;j<=8;j++){

System.out.print((selenium.getText("//html/body/div[9]/table/tbo
dy/tr["+i+"]/td["+j+"]"))+"---");

}
System.out.println();
________________________________________________________________________
QEdge TECHNOLOGIES: # 204, 2nd Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
Page | 101
nd
QEdge TECHNOLOGIES: # 204, 2 Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
}
}
}

Alerts Handling Program-10:
package WebTable; 
 
import org.testng.annotations.Test; 
import com.thoughtworks.selenium.DefaultSelenium; 
import com.thoughtworks.selenium.Selenium; 
 
public class alert { 
  @Test 
  public void gmail() throws Exception { 
    Selenium selenium=new DefaultSelenium("localhost", 
4445, "*firefox", "http://google.com"); 
    selenium.start(); 
    selenium.setSpeed("2000"); 
    selenium.windowMaximize(); 
    selenium.open("http://irctc.co.in"); 
    selenium.click("//*[@id='button']"); 
    selenium.chooseOkOnNextConfirmation(); 
  } 
}

________________________________________________________________________
QEdge TECHNOLOGIES: # 204, 2nd Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
Page | 102
nd
QEdge TECHNOLOGIES: # 204, 2 Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 

Extract Links Program-11:
import com.thoughtworks.selenium.DefaultSelenium; 
import com.thoughtworks.selenium.Selenium; 
public class Links_SeleniumRC { 
  public static void main(String[] args) { 
  Selenium selenium=new 
DefaultSelenium("localhost",4444,"*firefox","http://ebay.com"); 
  selenium.start(); 
  selenium.windowMaximize(); 
  selenium.setSpeed("2000"); 
  selenium.open("http://quikr.com");   
   
  String links[]=selenium.getAllLinks(); 
  System.out.println(links.length); 
  for(int i=0;i<links.length;i++){ 
    System.out.println(links[i]);     
     
  } 
  } 

 
 
 
 
 
 
 
 
 
 

________________________________________________________________________
QEdge TECHNOLOGIES: # 204, 2nd Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
Page | 103
nd
QEdge TECHNOLOGIES: # 204, 2 Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
 
 
 
 
 
 
 
 
 

JUnit Vs TestNG
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

JUnit 4 Vs TestNG

________________________________________________________________________
QEdge TECHNOLOGIES: # 204, 2nd Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
Page | 104
nd
QEdge TECHNOLOGIES: # 204, 2 Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
JUnit 4 and TestNG are both very popular unit test framework in Java. Both
frameworks look very similar in functionality. Which one is better? Which unit test
framework should i use in Java project?

Defference between JUnit 4 and TestNG.

 
 

1. Annotation Support
The annotation supports are implemented in both JUnit 4 and TestNG look similar.

Feature JUnit 4 TestNG

test annotation @Test @Test

run before all tests in


– @BeforeSuite
this suite have run

run after all tests in


– @AfterSuite
this suite have run

run before the test – @BeforeTest

run after the test – @AfterTest

run before the first


test method that – @BeforeGroups
belongs to any of
these groups is

________________________________________________________________________
QEdge TECHNOLOGIES: # 204, 2nd Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
Page | 105
nd
QEdge TECHNOLOGIES: # 204, 2 Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
invoked

run after the last test


method that belongs
– @AfterGroups
to any of these groups
is invoked

run before the first


test method in the
@BeforeClass @BeforeClass
current class is
invoked

run after all the test


methods in the current @AfterClass @AfterClass
class have been run

run before each test


@Before @BeforeMethod
method

run after each test


@After @AfterMethod
method

ignore test @ignore @Test(enbale=false)

@Test(expected = @Test(expectedExceptions =
expected exception
ArithmeticException.class) ArithmeticException.class)

timeout @Test(timeout = 1000) @Test(timeout = 1000)

________________________________________________________________________
QEdge TECHNOLOGIES: # 204, 2nd Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
Page | 106
nd
QEdge TECHNOLOGIES: # 204, 2 Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 

1. In JUnit 4, we have to declare “@BeforeClass” and “@AfterClass” method as


static method. TestNG is more flexible in method declaration, it does not have this
constraints.

2. 3 additional setUp/tearDown level: suite and group (@Before/AfterSuite,


@Before/AfterTest, @Before/AfterGroup).

JUnit 4

@BeforeClass
public static void oneTimeSetUp() {
// one-time initialization code
System.out.println("@BeforeClass - oneTimeSetUp");
}

TestNG

@BeforeClass
public void oneTimeSetUp() {
// one-time initialization code
System.out.println("@BeforeClass - oneTimeSetUp");
}

In JUnit 4, the annotation naming convention is a bit confusing, e.g “Before”, “After”
and “Expected”, we do not really understand what is “Before” and “After” do, and
what we “Expected” from test method? TestNG is easier to understand, it using
“BeforeMethod”, “AfterMethod” and “ExpectedException” instead.

________________________________________________________________________
QEdge TECHNOLOGIES: # 204, 2nd Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
Page | 107
nd
QEdge TECHNOLOGIES: # 204, 2 Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
2. Exception Test

The “exception testing” means what exception throw from the unit test, this feature
are implemented in both JUnit 4 and TestNG.

JUnit 4

@Test(expected = ArithmeticException.class)
public void divisionWithException() {
int i = 1/0;
}

TestNG

@Test(expectedExceptions = ArithmeticException.class)
public void divisionWithException() {
int i = 1/0;
}

3. Ignore Test

The “Ignored” means whether it should ignore the unit test, this feature are
implemented in both JUnit 4 and TestNG .

JUnit 4

@Ignore("Not Ready to Run")


@Test
public void divisionWithException() {
System.out.println("Method is not ready yet");
}

________________________________________________________________________
QEdge TECHNOLOGIES: # 204, 2nd Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
Page | 108
nd
QEdge TECHNOLOGIES: # 204, 2 Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
TestNG

@Test(enabled=false)
public void divisionWithException() {
System.out.println("Method is not ready yet");
}

4. Time Test

The “Time Test” means if an unit test takes longer than the specified number of
milliseconds to run, the test will terminated and mark as fails, this feature is
implemented in both JUnit 4 and TestNG .

JUnit 4

@Test(timeout = 1000)
public void infinity() {
while (true);
}

TestNG

@Test(timeOut = 1000)
public void infinity() {
while (true);
}

5. Suite Test

The “Suite Test” means bundle a few unit test and run it together. This feature is
implemented in both JUnit 4 and TestNG. However both are using very different
method to implement it.
________________________________________________________________________
QEdge TECHNOLOGIES: # 204, 2nd Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
Page | 109
nd
QEdge TECHNOLOGIES: # 204, 2 Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
JUnit 4

The “@RunWith” and “@Suite” are use to run the suite test. The below class means
both unit test “JunitTest1” and “JunitTest2” run together after JunitTest5 executed.
All the declaration is define inside the class.

@RunWith(Suite.class)
@Suite.SuiteClasses({
JunitTest1.class,
JunitTest2.class
})
public class JunitTest5 {
}

TestNG

XML file is use to run the suite test. The below XML file means both unit test
“TestNGTest1” and “TestNGTest2” will run it together.

<suite name="My test suite">


<test name="testing">
<classes>
<class name="com.framework.TestCase_A1" />
<class name="com.framework.TestCase_A2" />
</classes>
</test>
</suite>

TestNG can do more than bundle class testing, it can bundle method testing as well.
With TestNG unique “Grouping” concept, every method is tie to a group, it can
categorize tests according to features. For example,

________________________________________________________________________
QEdge TECHNOLOGIES: # 204, 2nd Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
Page | 110
nd
QEdge TECHNOLOGIES: # 204, 2 Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
Here is a class with four methods, three groups (method1, method2 and method3)

@Test(groups="method1")
public void testingMethod1() {
System.out.println("Method - testingMethod1()");
}

@Test(groups="method2")
public void testingMethod2() {
System.out.println("Method - testingMethod2()");
}

@Test(groups="method1")
public void testingMethod1_1() {
System.out.println("Method - testingMethod1_1()");
}

@Test(groups="method4")
public void testingMethod4() {
System.out.println("Method - testingMethod4()");
}

With the following XML file, we can execute the unit test with group “method1” only.

<suite name="My test suite">


<test name="testing">
<groups>
<run>
<include name="method1"/>
</run>

________________________________________________________________________
QEdge TECHNOLOGIES: # 204, 2nd Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
Page | 111
nd
QEdge TECHNOLOGIES: # 204, 2 Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
</groups>
<classes>
<class name="com.framework.SuiteA.TestCase_A1" />
</classes>
</test>
</suite>

With “Grouping” test concept, the integration test possibility is unlimited. For
example, we can only test the “DatabaseFuntion” group from all of the unit test
classes.

6. Parameterized Test

The “Parameterized Test” means vary parameter value for unit test. This feature is
implemented in both JUnit 4 and TestNG. However both are using very different
method to implement it.

JUnit 4

The “@RunWith” and “@Parameter” is use to provide parameter value for unit test,
@Parameters have to return List[], and the parameter will pass into class constructor
as argument.

@RunWith(value = Parameterized.class)
public class JunitTest6 {

private int number;

public JunitTest6(int number) {


this.number = number;
}
________________________________________________________________________
QEdge TECHNOLOGIES: # 204, 2nd Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
Page | 112
nd
QEdge TECHNOLOGIES: # 204, 2 Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 

@Parameters
public static Collection<Object[]> data() {
Object[][] data = new Object[][] { { 1 }, { 2 }, { 3 }, { 4 } };
return Arrays.asList(data);
}

@Test
public void pushTest() {
System.out.println("Parameterized Number is : " + number);
}
}

It has many limitations here; we have to follow the “JUnit” way to declare the
parameter, and the parameter has to pass into constructor in order to initialize the
class member as parameter value for testing. The return type of parameter class is
“List []”, data has been limited to String or a primitive value for testing.

TestNG

XML file or “@DataProvider” is use to provide vary parameter for testing.

XML file for parameterized test.


Only “@Parameters” declares in method which needs parameter for testing, the
parametric data will provide in TestNG’s XML configuration files. By doing this, we
can reuse a single test case with different data sets and even get different results. In
addition, even end user, QA or QE can provide their own data in XML file for testing.

Unit Test

public class TestNGTest6_1_0 {

________________________________________________________________________
QEdge TECHNOLOGIES: # 204, 2nd Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
Page | 113
nd
QEdge TECHNOLOGIES: # 204, 2 Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 

@Test
@Parameters(value="number")
public void parameterIntTest(int number) {
System.out.println("Parameterized Number is : " + number);
}

XML File

<suite name="My test suite">


<test name="testing">

<parameter name="number" value="2"/>

<classes>
<class name="com.framework.TestCase_A1" />
</classes>
</test>
</suite>

@DataProvider for parameterized test.

While pulling data values into an XML file can be quite handy, tests occasionally
require complex types, which can’t be represented as a String or a primitive value.
TestNG handles this scenario with its @DataProvider annotation, which facilitates the
mapping of complex parameter types to a test method.

@DataProvider for Vector, String or Integer as parameter

________________________________________________________________________
QEdge TECHNOLOGIES: # 204, 2nd Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
Page | 114
nd
QEdge TECHNOLOGIES: # 204, 2 Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
@DataProvider 
  public Object[][] login(){ 
    Object[][] data=new Object[2][2]; 
     
    data[0][0]="uname"; 
    data[0][1]=343453; 
     
    data[1][0]="uname1"; 
    data[1][1]=345645; 
     
    return data; 
     

  } 

@DataProvider for object as parameter


P.S “TestNGTest6_3_0” is an simple object with just get set method for demo.

@Test(dataProvider = "Data-Provider-Function")
public void parameterIntTest(TestNGTest6_3_0 clzz) {
System.out.println("Parameterized Number is : " + clzz.getMsg());
System.out.println("Parameterized Number is : " + clzz.getNumber());
}

//This function will provide the patameter data


@DataProvider(name = "Data-Provider-Function")
public Object[][] parameterIntTestProvider() {

________________________________________________________________________
QEdge TECHNOLOGIES: # 204, 2nd Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
Page | 115
nd
QEdge TECHNOLOGIES: # 204, 2 Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
TestNGTest6_3_0 obj = new TestNGTest6_3_0();
obj.setMsg("Hello");
obj.setNumber(123);

return new Object[][]{


{obj}
};
}

TestNG’s parameterized test is very user friendly and flexible (either in XML file or
inside the class). It can support many complex data type as parameter value and the
possibility is unlimited. As example above, we even can pass in our own object
(TestNGTest6_3_0) for parameterized test

7. Dependency Test
The “Parameterized Test” means methods are test base on dependency, which will
execute before a desired method. If the dependent method fails, then all subsequent
tests will be skipped, not marked as failed.

JUnit 4

JUnit framework is focus on test isolation; it did not support this feature at the
moment.

TestNG

It use “dependOnMethods “ to implement the dependency testing as following

@Test
public void method1() {
System.out.println("This is method 1");
}
________________________________________________________________________
QEdge TECHNOLOGIES: # 204, 2nd Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
Page | 116
nd
QEdge TECHNOLOGIES: # 204, 2 Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 

@Test(dependsOnMethods={"method1"})
public void method2() {
System.out.println("This is method 2");
}

The “method2()” will execute only if “method1()” is run successfully, else


“method2()” will skip the test.

WebDriver
________________________________________________________________________
QEdge TECHNOLOGIES: # 204, 2nd Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
Page | 117
nd
QEdge TECHNOLOGIES: # 204, 2 Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 

1. What is WebDriver?
WebDriver uses a different underlying framework from Selenium’s javascript
Selenium-Core. It also provides an alternative API with functionality not supported in
Selenium-RC. WebDriver does not depend on a javascript core embedded within the
browser, therefore it is able to avoid some long-running Selenium limitations.

WebDriver’s goal is to provide an API that establishes

¾ A well-designed standard programming interface for web-app testing.


¾ Improved consistency between browsers.
¾ Additional functionality addressing testing problems not well-supported in
Selenium 1.0.
The Selenium developers strive to continuously improve Selenium. Integrating
WebDriver is another step in that process. The developers of Selenium and of
WebDriver felt they could make significant gains for the Open Source test automation

________________________________________________________________________
QEdge TECHNOLOGIES: # 204, 2nd Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
Page | 118
nd
QEdge TECHNOLOGIES: # 204, 2 Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
community be combining forces and merging their ideas and technologies. Integrating
WebDriver into Selenium is the current result of those efforts.

2. When to Use WebDriver?


One should use WebDriver when requiring improved support for
¾ Mult-browser testing including improved functionality for browsers not well-
supported by
¾ Selenium-1.0.
¾ Handling multiple frames, multiple browser windows, popups, and alerts.
¾ Page navigation.
¾ Drag-and-drop.
¾ AJAX-based UI elements.

3. About WebDriver:
WebDriver is a tool for automating testing web applications, and in particular to
verify that they work as expected. It aims to provide a friendly API that’s easy to
explore and understand, which will help make your tests easier to read and maintain.
It’s not tied to any particular test framework, so it can be used equally well with
JUnit, TestNG or from a plain old “main” method. This “Getting Started” guide
introduces you to WebDriver’s Java API and helps get you started becoming familiar
with it. Start by Downloading the latest binaries and unpack them into a directory.
From now on, we’ll refer to that as $WEBDRIVER_HOME. Now, open your favourite IDE
and:
¾ Start a new Java project in your favourite IDE
¾ Add all the JAR files under $WEBDRIVER_HOME to the CLASSPATH

________________________________________________________________________
QEdge TECHNOLOGIES: # 204, 2nd Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
Page | 119
nd
QEdge TECHNOLOGIES: # 204, 2 Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
You can see that WebDriver acts just as a normal Java library does: it’s entirely self-
contained, and you don’t need to remember to start any additional processes or run
any installers before using it.
You’re now ready to write some code. An easy way to get started is this example,
which searches for the term “Cheese” on Google and then outputs the result page’s
title to the console. You’ll start by using the HtmlUnit Driver. This is a pure Java
driver that runs entirely in-memory. Because of this, you won’t see a new browser
window open.

4.Which Implementation of WebDriver Should I Use?


WebDriver is the name of the key interface against which tests should be written, but
there are several implementations. These are:
Name of driver Operating Class to instantiate
System
HtmlUnit Driver All org.openqa.selenium.htmlunit.Ht
Firefox Driver All mlUnitDriver
Internet Explorer Driver Windows Windows org.openqa.selenium.firefox.Firef
Chrome Driver All All oxDriver
org.openqa.selenium.ie.InternetEx
plorerDriver
org.openqa.selenium.chrome.Chro
meDriver

You can find out more information about each of these by following the links in the
table. Which you use depends on what you want to do. For sheer speed, the HtmlUnit
Driver is great, but it’s not graphical, which means that you can’t watch what’s
happening. As a developer you may be comfortable with this, but sometimes it’s good
to be able to test using a real browser, especially when you’re showing a demo of
________________________________________________________________________
QEdge TECHNOLOGIES: # 204, 2nd Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
Page | 120
nd
QEdge TECHNOLOGIES: # 204, 2 Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
your application (or running the tests) for an audience. Often, this idea is referred to
as “safety”, and it falls into two parts. Firstly, there’s “actual safety”, which refers
to whether or not the tests works as they should. This can be measured and
quantified. Secondly, there’s “perceived safety”, which refers to whether or not an
observer believes the tests work as they should. This varies from person to person,
and will depend on their familiarity with the application under test, WebDriver, and
your testing framework.

To support higher “perceived safety”, you may wish to choose a driver such as the
Firefox Driver. This has the added advantage that this driver actually renders content
to a screen, and so can be used to detect information such as the position of an
element on a page, or the CSS properties that apply to
it. However, this additional flexibility comes at the cost of slower overall speed. By
writing your tests against the WebDriver interface, it is possible to pick the most
appropriate driver for a given test. To keep things simple, let’s start with the

4.1 HtmlUnit Driver:

WebDriver driver = new HtmlUnitDriver();

4.2 Navigating
The first thing you’ll want to do with WebDriver is navigate to a page. The normal
way to do this is bycalling “get”:

driver.get( "http://www.google.com" );

WebDriver will wait until the page has fully loaded (that is, the “onload” event has
fired) before returning control to your test or script. It’s worth noting that if your

________________________________________________________________________
QEdge TECHNOLOGIES: # 204, 2nd Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
Page | 121
nd
QEdge TECHNOLOGIES: # 204, 2 Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
page uses a lot of AJAX on load then WebDriver may not know when it has completely
loaded. If you need to ensure such pages are fully loaded then you can use “waits”.

4.3 Interacting With the Page


Just being able to go to places isn’t terribly useful. What we’d really like to do is to
interact with the pages, or, more specifically, the HTML elements within a page. First
of all, we need to find one.
WebDriver offers a number of ways of finding elements. For example, given an
element defined as:

<input type= "text" name= "passwd" id= "passwd-id" />

you could find it using any of:

WebElement element;
element = driver.findElement(By.id( "passwd-id" ));
element = driver.findElement(By.name( "passwd" ));
element = driver.findElement(By.xpath( "//input[@id=’passwd-id’]" ));

You can also look for a link by its text, but be careful! The text must be an exact
match! You should also be careful when using XPATH in WebDriver. If there’s more
than one element that matches the query, then only the first will be returned. If
nothing can be found, a NoSuchElementException will be thrown. WebDriver has an
“Object-based” API; we represent all types of elements using the same interface:
Web Element. This means that although you may see a lot of possible methods you
could invoke when you hit your IDE’s auto-complete key combination, not all of them
will make sense or be valid. Don’t worry! WebDriver will attempt to do the Right
Thing, and if you call a method that makes no sense (“setSelected()” on a “meta”
tag, for example) an exception will be thrown.
________________________________________________________________________
QEdge TECHNOLOGIES: # 204, 2nd Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
Page | 122
nd
QEdge TECHNOLOGIES: # 204, 2 Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 

So, you’ve got an element. What can you do with it? First of all, you may want to
enter some text into a

text field:
element.sendKeys( "some text" );
You can simulate pressing the arrow keys by using the “Keys” class:
element.sendKeys( " and some" , Keys.ARROW_DOWN);

It is possible to call sendKeys on any element, which makes it possible to test


keyboard shortcuts such as those used on GMail. A side-effect of this is that typing
something into a text field won’t automatically clear it. Instead, what you type will
be appended to what’s already there. You can easily clear the contents of a text field
or textarea:

element.clear();

Filling In Forms -~~~~~~~~~~~~~~~

We’ve already seen how to enter text into a textarea or text field, but what about
the other elements? You can “toggle” the state of checkboxes, and you can use
“setSelected” to set something like an OPTION tag selected. Dealing with SELECT tags
isn’t too bad:

WebElement select = driver.findElement(By.xpath( "//select" ));

List<WebElement> allOptions = select.findElements(By.tagName( "option" ));


for (WebElement option : allOptions) {
System.out.println(String.format( "Value is: %s" , option.getValue()));

________________________________________________________________________
QEdge TECHNOLOGIES: # 204, 2nd Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
Page | 123
nd
QEdge TECHNOLOGIES: # 204, 2 Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
option.setSelected();
}

This will find the first “SELECT” element on the page, and cycle through each of it’s
OPTIONs in turn, printing out their values, and selecting each in turn. As you can see,
this isn’t the most efficient way of dealing with SELECT elements. WebDriver’s
support classes include one called “Select”, which provides useful methods for
interacting with these.

Select select = new Select(driver.findElement(By.xpath( "//select" )));


select.deselectAll();
select.selectByVisibleText( "Edam" );

This will deselect all OPTIONs from the first SELECT on the page, and then select the
OPTION with the displayed text of “Edam”. Once you’ve finished filling out the form,
you probably want to submit it. One way to do this would be to find the “submit”
button and click it:

driver.findElement(By.id( "submit" )).click();


// Assume the button has the ID "submit" :)

Alternatively, WebDriver has the convenience method “submit” on every element. If


you call this on an element within a form, WebDriver will walk up the DOM until it
finds the enclosing form and then calls submit on that. If the element isn’t in a form,
then the NoSuchElementException will be thrown:
element.submit();

4.4 Getting Visual Information And Drag And Drop


________________________________________________________________________
QEdge TECHNOLOGIES: # 204, 2nd Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
Page | 124
nd
QEdge TECHNOLOGIES: # 204, 2 Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
Sometimes you want to extract some visual information out of an element, perhaps to
see if it’s visible or where it is on screen. You can find out this information by casting
the element to a RenderedWebElement:

WebElement plain = driver.findElement(By.name( "q" ));


RenderedWebElement element = (RenderedWebElement) element;

Not all drivers render their content to the screen (such as the HtmlUnit Driver), so it’s
not safe to assume that the cast will work, but if it does you can gather additional
information such as the size and location

4.5 Moving Between Windows and Frames

It’s rare for a modern web application not to have any frames or to be constrained to
a single window. WebDriver supports moving between named windows using the

“switchTo” method:
driver.switchTo().window( "windowName" );

All calls to driver will now be interpreted as being directed to the particular window.
But how do you know the window’s name? Take a look at the javascript or link that
opened it:

<a href= "somewhere.html" target= "windowName" >Click here to open a new


window</a>

Alternatively, you can pass a “window handle” to the “switchTo().window()” method.


Knowing this, it’s possible to iterate over every open window like so:

________________________________________________________________________
QEdge TECHNOLOGIES: # 204, 2nd Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
Page | 125
nd
QEdge TECHNOLOGIES: # 204, 2 Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 

for (String handle : driver.getWindowHandles()) {


driver.switchTo().window(handle);
}

You can also swing from frame to frame (or into iframes):

driver.switchTo().frame( "frameName" );
It’s possible to access subframes by separating the path with a dot, and you can
specify the frame by its index too. That is:

driver.switchTo().frame( "frameName.0.child" );

would go to the frame named “child” of the first subframe of the frame called
“frameName”. All frames are evaluated as if from *top*.

4.6 Navigation: History and Location

Earlier, we covered navigating to a page using the “get” command


(driver.get("http://www.example.com"))

As you’ve seen, WebDriver has a number


of smaller, task-focused interfaces, and navigation is a useful task. Because loading a
page is such a fundamental requirement, the method to do this lives on the main
WebDriver interface, but it’s simply a synonym to:

driver.navigate().to( "http://www.example.com" );

________________________________________________________________________
QEdge TECHNOLOGIES: # 204, 2nd Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
Page | 126
nd
QEdge TECHNOLOGIES: # 204, 2 Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
To reiterate: “navigate().to()” and “get()” do exactly the same thing. One’s just a lot
easier to type than the other! The “navigate” interface also exposes the ability to
move backwards and forwards in your browser’s history:

driver.navigate().forward();
driver.navigate().back();

Please be aware that this functionality depends entirely on the underlying browser.
It’s just possible that something unexpected may happen when you call these
methods if you’re used to the behaviour of one browser over another.

4.7 Cookies
Before we leave these next steps, you may be interested in understanding how to use
cookies. First of all, you need to be on the domain that the cookie will be valid for:

// Go to the correct domain


driver.get( "http://www.example.com" );

// Now set the cookie. This one’s valid for the entire domain
Cookie cookie = new Cookie( "key" , "value" );
driver.manage().addCookie(cookie);

// And now output all the available cookies for the current URL
Set<Cookie> allCookies = driver.manage().getCookies();
for (Cookie loadedCookie : allCookies) {
System.out.println(String.format( "%s -> %s" , loadedCookie.getName(),
loadedCookie.getValue()));

________________________________________________________________________
QEdge TECHNOLOGIES: # 204, 2nd Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
Page | 127
nd
QEdge TECHNOLOGIES: # 204, 2 Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
}

6. WebDriver Implementations
5.1 HtmlUnit Driver
This is currently the fastest and most lightweight implementation of WebDriver. As
the name suggests, this is based on HtmlUnit.

¾ Fastest implementation of WebDriver


¾ A pure Java solution and so it is platform independent.
¾ Supports JavaScript
¾ Emulates other browser’s JavaScript behavior

JavaScript in the HtmlUnit Driver


None of the popular browsers uses the JavaScript engine used by HtmlUnit (Rhino). If
you test JavaScript using HtmlUnit the results may differ significantly from those
browsers.

When we say “JavaScript” we actually mean “JavaScript and the DOM”. Although the
DOM is defined by the W3C each browser out there has its own quirks and differences
in their implementation of the DOM and in how JavaScript interacts with it. HtmlUnit
has an impressively complete implementation of the DOM and has good support for
using JavaScript, but it is no different from any other browser: it has its own quirks
and differences from both the W3C standard and the DOM implementations of the
major browsers, despite its ability to mimic other browsers.

With WebDriver, we had to make a choice; do we enable HtmlUnit’s JavaScript


capabilities and run the risk of teams running into problems that only manifest
themselves there, or do we leave JavaScript disabled, knowing that there are more
________________________________________________________________________
QEdge TECHNOLOGIES: # 204, 2nd Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
Page | 128
nd
QEdge TECHNOLOGIES: # 204, 2 Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
and more sites that rely on JavaScript? We took the conservative approach, and by
default have disabled support when we use HtmlUnit. With each release of both
WebDriver and HtmlUnit, we reassess this decision: we hope to enable JavaScript by
default on the HtmlUnit at some point.

5.2 Declaring Browsers in WebDriver


WebDriver Run with Firefox Browser:

WebDriver driver = new FirefoxDriver();

WebDriver Run with InternetExplorer Browser:

WebDriver driver = new InternetExplorerDriver();

Convert Selenium-RC code to WebDriver code:

//First Declare WebDriver:


WebDriver driver = new FirefoxDriver();

// Create the Selenium implementation


Selenium selenium = new WebDriverBackedSelenium(driver, baseUrl);
// Perform actions with selenium
selenium.open( "http://www.google.com" );
selenium.type( "name=q" , "cheese" );
selenium.click( "name=btnG" );
//Now you can Execute

5.3 Firefox profile Handling in WebDriver

________________________________________________________________________
QEdge TECHNOLOGIES: # 204, 2nd Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
Page | 129
nd
QEdge TECHNOLOGIES: # 204, 2 Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
Suppose that you wanted to modify the user agent string (as above), but you’ve got a
tricked out Firefox profile that contains dozens of useful extensions. There are two
ways to obtain this profile. Assuming that the profile has been created using Firefox’s
profile manager (firefox -ProfileManager):

ProfileIni allProfiles = new ProfilesIni();

FirefoxProfile profile = allProfiles.getProfile( "WebDriver" );


profile.setPreferences( "foo.bar" , 23);
WebDriver driver = new FirefoxDriver(profile);

Alternatively, if the profile isn’t already registered with Firefox:


File profileDir = new File( "path/to/top/level/of/profile" );
FirefoxProfile profile = new FirefoxProfile(profileDir);
profile.addAdditionalPreferences(extraPrefs);

WebDriver driver = new FirefoxDriver(profile);

Enabling features that might not be wise to use in Firefox

As we develop features in the Firefox Driver, we expose the ability to use them. For
example, until we feel native events are stable on Firefox for Linux, they are disabled
by default. To enable them:
FirefoxProfile profile = new FirefoxProfile();
profile.setEnableNativeEvents(true);
WebDriver driver = new FirefoxDriver(profile);

7. Locators or Properties
________________________________________________________________________
QEdge TECHNOLOGIES: # 204, 2nd Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
Page | 130
nd
QEdge TECHNOLOGIES: # 204, 2 Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 

1. Id
2. Name
3. Class or classname
4. Linktext
5. Partial link text
6. Normal xpath
7. Absolute xpath

Other methods: we can create our own xpath

1. //input[@id=’give id’]
2. //button[@class=’give class name’ ]
3. //a[@href=’give the link’ ]
4. //div[starts-with(@id, ‘give id starts’) ]
5. //div[ends-with(@class, ‘give id give ends of class’) ]
6. //div[contains(@id, ‘give id starts’) ]

________________________________________________________________________
QEdge TECHNOLOGIES: # 204, 2nd Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
Page | 131
nd
QEdge TECHNOLOGIES: # 204, 2 Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 

Important Interview Questions for


Selenium RC & WebDriver

________________________________________________________________________
QEdge TECHNOLOGIES: # 204, 2nd Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
Page | 132
nd
QEdge TECHNOLOGIES: # 204, 2 Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 

1. What are the few Challenges that you faced with Selenium
Automation in your company?

¾ Very difficult to find good documentation.

Hardcore programming.

¾ Less inbuilt features for reporting/test case management.

¾ Finding locators/xpaths.

¾ Sometimes selenium is not able to recognize elements. We have to use

JavaScript. in that case - especially in Selenium RC.

¾ We can’t run scripts from step as we can do in QTP. SO script generation

takes a lot of time.

¾ Difficult to generate reports.

¾ Password encryption is not possible.

¾ Bitmap comparison is not supported by Selenium.

¾ You need to learn any one of the native language like (.Net, Java, Perl,

Python, PHP, Ruby) to work efficiently with the scripting side of selenium.

¾ Sometimes stopping the selenium server it shows error, selenium server is

running but actually it won’t run.

¾ Since Selenium is a freeware tool, there is no direct support if one is in

trouble with the support of applications.

¾ There is no object repository concept in Selenium, so maintainability of the

objects is very high.

________________________________________________________________________
QEdge TECHNOLOGIES: # 204, 2nd Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
Page | 133
nd
QEdge TECHNOLOGIES: # 204, 2 Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
¾ There are many challenges if one have to interact with Win 32 windows

even when.

¾ you are working with Web based applications.

¾ Bitmap comparison is not supported by Selenium.

¾ Any reporting related capabilities, you need to depend on third party tools.

3. Advantages of Selenium?

¾ Selenium is a open source tool

¾ It can Automate any Web Application

¾ It is a perfect tool for Browser Automation

¾ In the market very demand Automation Tool

¾ It can support no.of languages

¾ Once we prepare the code in the windows platform we can run in any

OS, platform independent.

¾ We can integrate with No. of tools

4. Disadvantages of Selenium?
¾ Selenium Can’t record the Desktop application

¾ Selenium IDE can’t Record on IE Browser

¾ Bitmap comparison is not possible in selenium

¾ Handle dynamic Objects little bit tricky

________________________________________________________________________
QEdge TECHNOLOGIES: # 204, 2nd Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
Page | 134
nd
QEdge TECHNOLOGIES: # 204, 2 Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
¾ Less inbuilt features

¾ Generating reports bit difficult.

5. What do you know about Selenium?


6.

Selenium is a suite of tools for web automation testing.


Selenium first came to life in 2004 when Jason Huggins was testing an internal
application at ThoughtWorks.
Selenium was a tremendous tool, it wasn’t without it’s drawbacks. Because of its
Javascript based automation engine and the security limitations browsers apply to
Javascript, different things became impossible to do.

Selenium Suite of projects include:

Selenium IDE
Selenium Core
Selenium 1 (known as. Selenium RC or Remote Control)
Selenium 2 (known as. Selenium Webdriver)
Selenium-Grid

7. What are the technical challenges with selenium?

As you know Selenium is a free ware open source testing tool. There are many
challenges with Selenium.

1. Selenium Supports only web based applications


2. It doesn’t support any non web based (Like Win 32, Java Applet, Java Swing,
.Net Client Server etc) applications
3. When you compare selenium with QTP, Silk Test, Test Partner and RFT, there

________________________________________________________________________
QEdge TECHNOLOGIES: # 204, 2nd Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
Page | 135
nd
QEdge TECHNOLOGIES: # 204, 2 Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
are many challenges in terms of maintainability of the test cases
4. Since Selenium is a freeware tool, there is no direct support if one is in trouble
with the support of applications
5. There is no object repository concept in Selenium, so maintainability of the
objects is very high
6. There are many challenges if one have to interact with Win 32 windows even
when you are working with Web based applications
7. Bitmap comparison is not supported by Selenium
8. Any reporting related capabilities, you need to depend on third party tools
9. You need to learn any one of the native language like (.Net, Java, Perl, Python,
PHP, Ruby) to work efficiently with the scripting side of selenium

8. What are the capabilities of Selenium IDE?

Selenium IDE (Integrated Development Environment) works similar to commercial


tools like QTP, Silk Test and Test Partner etc. The below mentioned points
describes well about Selenium IDE.

1. Selenium IDE is a Firefox add-on.


2. Selenium IDE can support recording the clicks, typing, and other actions to
make a test cases.
3. Using Selenium IDE A Tester can play back the test cases in the Firefox browser
4. Selenium IDE supports exporting the test cases and suites to Selenium RC.
5. Debugging of the test cases with step-by-step can be done
6. breakpoint insertion is possible
7. Page abstraction functionality is supported by Selenium IDE
8. Selenium IDE can supports an extensibility capability allowing the use of add-
ons or user extensions that expand the functionality of Selenium IDE

9. What are the challenges with Selenium IDE?


________________________________________________________________________
QEdge TECHNOLOGIES: # 204, 2nd Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
Page | 136
nd
QEdge TECHNOLOGIES: # 204, 2 Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 

Selenium-IDE does not directly support:

1. condition statements
2. iteration or looping
3. logging and reporting of test results
4. error handling, particularly unexpected errors
5. database testing
6. test case grouping
7. re-execution of failed tests
8. test case dependency
9. capture screenshots on test failures
10. Results Report generations

10. Which are the browsers supported by Selenium IDE?

1. Selenium can record only on firefox and It can support or run only on firefox

11. How to execute a single line command from Selenium IDE?

Single line command from Selenium IDE can be executed in two ways

1.Right click on the command in Selenium IDE and select "Execute This Command"
2.Select the command in Selenium IDE and press "X" key on the keyboard

12. How to insert a start point in Selenium IDE?

Start point Selenium IDE can be set in two ways

1. Right click on the command in Selenium IDE and select "Set / Clear Start Point"
2. Select the command in Selenium IDE and press "S" key on the keyboard

________________________________________________________________________
QEdge TECHNOLOGIES: # 204, 2nd Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
Page | 137
nd
QEdge TECHNOLOGIES: # 204, 2 Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
3. You can have only one start point
4. If you have already set one start point and you selected other command as start
point. Then the first start point will be removed and the new start point will be set

13. How to insert a break point in Selenium IDE?

Break point can be set in two ways in Selenium IDE

1. Right click on the command in Selenium IDE and select "Toggle Break Point"
2. Select the command in Selenium IDE and press "B" key on the keyboard
3. If you want to clear the break point once again Spress "B" key on the keyboard
4. You can set multiple break points in Selenium IDE

14. How to debug the tests in Selenium IDE?

To debug or execute the test cases line by line. Follow the below mentioned steps

1. Insert a break point (see the question to know more How to insert a break point in
Selenium IDE? )from the location where you want to execute step by step
2. Run the test case
3. execution will be paused at the given break point
4. Click on the step (Blue) button to continue with the next statement
5. Click on Run button, to continue executing all the commands at a time

________________________________________________________________________
QEdge TECHNOLOGIES: # 204, 2nd Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
Page | 138
nd
QEdge TECHNOLOGIES: # 204, 2 Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
15. How to export the tests from Selenium IDE to Selenium RC in
different languages?

From selenium IDE the test cases can be exported into the languages

1. .Net,
2. Java,
3. Perl,
4. Python,
5. PHP,
6. Ruby

The below mentioned steps can explain how to export the test cases

1. Open the test case from Selenium IDE


2. Select File -> Export Test Case As

16. Which is the command used for displaying the values of a


variable into the output console or log?

1. The command used for displaying the values of a variable into the output console
or log - echo
2. If you want to display a constant string. The below mentioned command can be
used
echo <constant string>
ex: echo "The sample message"
3. If you want to display the value of a variable it can be written like below
echo ${<variable name>>
4. ex: echo ${var1}
5. Note: Here var1 is the variable

________________________________________________________________________
QEdge TECHNOLOGIES: # 204, 2nd Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
Page | 139
nd
QEdge TECHNOLOGIES: # 204, 2 Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
17. Which are the browsers supported by Selenium RC?

1. Supported browsers for Selenium RC include:


2. 1. *firefox
2. *mock
3. *firefoxproxy
4. *pifirefox
5. *chrome
6. *iexploreproxy
7. *iexplore
8. *firefox3
9. *safariproxy
10. *googlechrome
11. *konqueror
12. *firefox2
13. *safari
14. *piiexplore
15. *firefoxchrome
16. *opera
17. *iehta
18. *custom
3. Note: Any third party browser is supported with *custom followed by the complete
path of the browser with executable

18. Which are the Operating Systems supported by Selenium?

________________________________________________________________________
QEdge TECHNOLOGIES: # 204, 2nd Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
Page | 140
nd
QEdge TECHNOLOGIES: # 204, 2 Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
1. Selenium IDE
Works in Firefox 2+ Start browser, run tests Run tests
Operating Systems Supported:
2. 1. Windows,
2. OS X
3. Linux
4. Solaris
5. Others whichever supports Firefox 2+
3. Selenium Remote Control
Used for starting browser and run tests
Operating Systems Supported:
4. 1. Windows,
2. OS X
3. Linux
4. Solaris
5. Others
5. Selenium Core
Used for running tests
Operating Systems Supported:
6. 1. Windows,
2. OS X
3. Linux
4. Solaris
5. Others

19. What is Selenium RC?

________________________________________________________________________
QEdge TECHNOLOGIES: # 204, 2nd Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
Page | 141
nd
QEdge TECHNOLOGIES: # 204, 2 Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
1. Selenium-RC is the solution for tests that need a little more than just simple
browser actions and a linear execution. Selenium-RC leverages the full power of
programming languages, creating tests that can do things like read and write
external files, make queries to a database, send emails with test reports, and
practically anything else a user can do with a normal application.
2. You will want to use Selenium-RC whenever your test requires logic not supported
by running a script from Selenium-IDE

20. Why Selenium RC is used?

1. Selenium-IDE does not directly support:


2. 1. condition statements
2. iteration
3. logging and reporting of test results
4. error handling, particularly unexpected errors
5. database testing
6. test case grouping
7. re-execution of failed tests
8. test case dependency
9. capture screenshots on test failures
3. The reason behind why Selenium-IDE does not support the above mentioned
requirements is IDE supports only HTML language. Using HTML language we cannot
achieve the above mentioned requirements. Because HTML does not support
conditional, looping and external source connectives.
4. To overcome the above mentioned problems Selenium RC is used.
5. Since Selenium RC supports the languages .Net, Java, Perl, Python, PHP, and
Ruby. In these languages we can write the programme to achieve the IDE issues
________________________________________________________________________
QEdge TECHNOLOGIES: # 204, 2nd Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
Page | 142
nd
QEdge TECHNOLOGIES: # 204, 2 Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 

21. Which are the languages supported by Selenium RC?

The languages supported by Selenium RC

1. .Net,
2. Java (Junt 3, Junt 4, TestNG, Groovy)
3. Perl,
4. Python,
5. PHP,
6. Ruby

22. What is Selenium Grid?

Selenium Grid is part of Selenium suite of projects. Selenium Grid transparently


distribute your tests on multiple machines so that you can run your tests in parallel,
cutting down the time required for running in-browser test suites. This will
dramatically speeds up in-browser web testing, giving you quick and accurate
feedback you can rely on to improve your web application.

23. What is Selenium WebDriver or Google WebDriver or Selenium


2.0?
________________________________________________________________________
QEdge TECHNOLOGIES: # 204, 2nd Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
Page | 143
nd
QEdge TECHNOLOGIES: # 204, 2 Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
1. WebDriver uses a different underlying framework from Selenium’s javascript
Selenium-Core. It also provides an alternative API with functionality not supported
in Selenium-RC. WebDriver does not depend on a javascript core embedded within
the browser, therefore it is able to avoid some long-running Selenium limitations.
2. WebDriver’s goal is to provide an API that establishes
• A well-designed standard programming interface for web-app testing.
• Improved consistency between browsers.
• Additional functionality addressing testing problems not well-supported in
Selenium 1.0.
3. The Selenium developers strive to continuously improve Selenium. Integrating
WebDriver is another step in that process. The developers of Selenium and of
WebDriver felt they could make significant gains for the Open Source test
automation community be combining forces and merging their ideas and
technologies. Integrating WebDriver into Selenium is the current result of those
efforts.

24. What are the capabilities of Selenium WebDriver or Google


WebDriver or Selenium 2.0?

One should use WebDriver when requiring improved support for

Mult-browser testing including improved functionality for browsers not well-


supported by Selenium-1.0.
• Handling multiple frames, multiple browser windows, popups, and alerts.
• Page navigation.
• Drag-and-drop.
• AJAX-based UI elements.
________________________________________________________________________
QEdge TECHNOLOGIES: # 204, 2nd Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
Page | 144
nd
QEdge TECHNOLOGIES: # 204, 2 Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
25. What is the architecture of Selenium RC?

1. The Selenium Server which launches and kills browsers, and acts as an HTTP proxy
for browser requests.
2. Client libraries for various programming languages, each of which instructs the
Selenium Server in how to test the AUT by passing it your test script’s Selenium
commands.
3. The diagram shows the client libraries communicate with the Server passing each
Selenium command for execution. Then the server passes the Selenium command
to the browser using Selenium-Core JavaScript commands. The browser, using its
JavaScript interpreter, executes the Selenium command, which effectively, runs
the check you specified in your Selenese test script.

26. What is the architecture of Selenium Grid?

The below mentioned theory explains about the setup of Selenium Grid with
architecture and how it works.

1. Selenium Grid builds on the traditional Selenium setup, taking advantage of the
following properties:
2. * The Selenium test, the application under test, and the remote control/browser
pair do not have to be co-located. They communicate through HTTP, so they can
all live on different machines.
* The Selenium tests and the web application under test are obviously specific to a
________________________________________________________________________
QEdge TECHNOLOGIES: # 204, 2nd Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
Page | 145
nd
QEdge TECHNOLOGIES: # 204, 2 Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
particular project. Nevertheless, neither the Selenium remote control nor the
browser is tied to a specific application. As a matter of fact, they provide a
capacity that can easily be shared by multiple applications and multiple projects.
3. Consequently, if only we could build a distributed grid of Selenium Remote
Controls, we could easily share it across builds, applications, projects - even
potentially across organizations. Of course we would also need to address the
scalability issues as described earlier when covering the traditional Selenium
setup. This is why we need a component in charge of:
4. * Allocating a Selenium Remote Control to a specific test (transparently)
* Limiting the number of concurrent test runs on each Remote Control
* Shielding the tests from the actual grid infrastructure
5. Selenium Grid calls this component the Selenium Hub.
6. * The Hub exposes an external interface that is exactly the same as the one of a
traditional Remote Control. This means that a test suite can transparently target a
regular Remote Control or a Selenium Hub with no code change. It just needs to
target a different IP address. This is important as it shields the tests from the grid
infrastructure (which you can scale transparently). This also makes the developer’s
life easier. The same test can be run locally on a developer machine, or run on a
heavy duty distributed grid as part of a build – without ever changing a line of
code.
* The Hub allocates Selenium Remote Controls to each test. The Hub is also in
charge of routing the Selenese requests from the tests to the appropriate Remote
Control as well as keeping track of testing sessions.
* When a new test starts, the Hub puts its first request on hold if there is no
available Remote Control in the grid providing the appropriate capabilities. As
soon as a suitable Remote Control becomes available, the Hub will serve the
request. For the whole time, the tests do not have to be aware of what is
happening within the grid; it is just waiting for an HTTP response to come back.

________________________________________________________________________
QEdge TECHNOLOGIES: # 204, 2nd Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
Page | 146
nd
QEdge TECHNOLOGIES: # 204, 2 Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 

27. Does Selenium support mobile internet testing?

Selenium supports Opera. And opera is used in most of the Smart phones. So
whichever Smart phone supports opera, selenium can be used to test. So, one can
use Selenium RC to run the tests on mobiles.

28. Does Selenium support Google Android Operating System?

Yes, Selenium Web Driver or Google Web Driver or Selenium 2.0 supports Android
Operating System. There are several libraries written to support Android Operating
System.

29. What are the types of text patterns available in Selenium?

There are three types of patterns available in Selenium


1. globbing
2. regular expressions
3. Exact

30. How to use regular expressions in Selenium?


________________________________________________________________________
QEdge TECHNOLOGIES: # 204, 2nd Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
Page | 147
nd
QEdge TECHNOLOGIES: # 204, 2 Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 

1. Regular expressions in Selenium IDE can be used with the keyword - regexp:
as a prefix to the value and patterns needs to be included for the expected
values.
2. For example if you want to use the regular expression for a command
Command: verifyText
Target: //font/font/b/font[1]
Value: Flight Confirmation # 2011-05-02451
3. in the above example Flight Confirmation is continuously changing each
time you run the test case. So this can be written with a regular expression
as mentioned below
4. Command: verifyText
Target: //font/font/b/font[1]
Value: regexp:Flight Confirmation # [0-9]{4}-[0-9]{2}-[0-9]{5,10}

31. What are the regular expression patterns available in Selenium?

1. Selenium regular expression patterns offer the same wide array of special
characters that exist in JavaScript. Below are a subset of those special
characters

________________________________________________________________________
QEdge TECHNOLOGIES: # 204, 2nd Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
Page | 148
nd
QEdge TECHNOLOGIES: # 204, 2 Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
3. MATCH
2. PATTERN

5. any single character


4. .

7. character class: any single character that appears


6. [ ] inside the brackets

9. quantifier: 0 or more of the preceding character


8. * (or group)

11.quantifier: 1 or more of the preceding character


10. + (or group)

13.quantifier: 0 or 1 of the preceding character (or


12. ? group)

15.quantifier: 1 through 5 of the preceding character


14. {1,5} (or group)

17.alternation: the character/group on the left or


16. | the character/group on the right

19.grouping: often used with alternation and/or


18. ( ) quantifier

32. What is Selenese?

________________________________________________________________________
QEdge TECHNOLOGIES: # 204, 2nd Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
Page | 149
nd
QEdge TECHNOLOGIES: # 204, 2 Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
1. Selenium set of commands which are used for running the test are called as
Selenese.
2. There are three types of Selenese, those are:
1. Actions - used for performing the operations and interactions with the
target elements
2. Assertions - used as check points
3. Accessors - used for storing the values in a variable

33. How do you add check points or verification points in Selenium?

1. check points or verification points are known as Assertions in Selenium. The


keywords with below mentioned prefix will be used for adding check points
or verification points.
2. 1. verify
2. assert
3. waitFor

34. What is Assertion in Selenium?

1. Assertion is nothing but a check or verification point.

________________________________________________________________________
QEdge TECHNOLOGIES: # 204, 2nd Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
Page | 150
nd
QEdge TECHNOLOGIES: # 204, 2 Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
2. Assertion verifies the state of the application conforms to what is expected.
Examples include “make sure the page title is X” and “verify that this
checkbox is checked.

35. What are the types of Assertions there in Selenium?

1. Selenium Assertions can be used in 3 modes:


2. 1) assert - When an “assert” fails, the test will be aborted. If you are
executing test suite, the next state case will start
3. 2) verify - When a “verify” fails, the test will continue execution, logging
the failure.
4. 3) waitFor - “waitFor” commands wait for some condition to become true
(which can be useful for testing Ajax applications). They will succeed
immediately if the condition is already true. However, they will fail and
halt the test if the condition does not become true within the current
timeout setting

36. When to use Assert, Verify and WaitFor in Selenium?


________________________________________________________________________
QEdge TECHNOLOGIES: # 204, 2nd Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
Page | 151
nd
QEdge TECHNOLOGIES: # 204, 2 Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
1. 1) assert - If the expected value is mandatory to continue with the next set
of steps we will use Assert. As Assert aborts the test, if the expected value
doesn't match. It is good to use for any mandatory checks.
2. 2) verify - If the expected value is optional to continue with the next set of
steps we will use Verify. As Verify continues executing with the next set of
steps, if the expected value doesn't match. It is good to use for any optional
checks.
3. 3) waitFor - If your test needs to wait, if the expected value is not matching
we use waitFor. We normally use waitFor for AJAX kind of controls loading
within a page

37. What is an Accessor in Selenium?

1. Accessor is one of the type of Selenese.


2. I. Accessors are used for storing the value of a target in a variable.
3. Ex:
1) storeTitle - Stores the title of a window in a variable
4. 2) storeText - Stores the target element text in a variable
5. II. Accessors are also used for evaluating the result and storing the result in
a variable
6. Ex: storeTextPresent - Evaluates whether the text is present in the current
window. If the text is present stores true in the variable else stores false
7. Ex: storeEementPresent - Evaluates whether the element is present in the
current window. If the element is present stores true in the variable else
stores false

________________________________________________________________________
QEdge TECHNOLOGIES: # 204, 2nd Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
Page | 152
nd
QEdge TECHNOLOGIES: # 204, 2 Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
38. When to use Accessors in Selenium?

1. Accessors are mostly used for storing the value in a variable.


2. The variable can be used for following reasons:
3. 1) To get the value from an element and comparing with some dynamic
value
4. 2) To take a logical decision to execute the test steps
ex: if the value of the variable true execute step1 and step2 else step3 and
step4
5. 3) To execute some statements in a loop based on the value returned by the
element

39. How to capture bitmaps in Selenium?

1. Bitmaps are captured using the Selenium set of commands. There are two
modes of capturing the bitmaps
2. 1) Capture the bitmap for the entire page - it captures the browser main
page area of AUT
2) Capture the bitmap for the screen shots - it captures the entire screen
shot like the print scree that you give from your keyboard
3. Selenium doesn't support bitmap capturing for an element on AUT.

40. Which are the commands used for capturing the bitmaps?

1. captureEntirePageScreenshot
Saves the entire contents of the current window canvas to a PNG file.
Contrast this with the captureScreenshot command, which captures the
contents of the OS viewport (i.e. whatever is currently being displayed on
the monitor), and is implemented in the RC only. Currently this only works
in Firefox when running in chrome mode, and in IE non-HTA using the

________________________________________________________________________
QEdge TECHNOLOGIES: # 204, 2nd Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
Page | 153
nd
QEdge TECHNOLOGIES: # 204, 2 Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
EXPERIMENTAL "Snapsie" utility. The Firefox implementation is mostly
borrowed from the Screengrab! Firefox extension. Please see
captureEntirePageScreenshot for more details
2. captureEntirePageScreenshotAndWait
Saves the entire contents of the current window canvas to a PNG file.
Contrast this with the captureScreenshot command, which captures the
contents of the OS viewport (i.e. whatever is currently being displayed on
the monitor), and is implemented in the RC only. Currently this only works
in Firefox when running in chrome mode, and in IE non-HTA using the
EXPERIMENTAL "Snapsie" utility. The Firefox implementation is mostly
borrowed from the Screengrab! Firefox extension. Please see
captureEntirePageScreenshotAndWait for details.
3. Note: This command runs with only mozilla firefox when you run the tests
from RC. Other browsers it will not support

41. What is the difference between captureEntirePageScreenshot


and CaptureScreenShot?

1. captureEntirePageScreenshot
1. This captures the AUT web page only
2. This supports only mozilla firefox
3. Accepts two arguments. one is the file name to be saved and other
argument is back ground color
2. CaptureScreenShot
3. 1. This captures the System screen shot
2. This supports all the browsers when you run from Selenium RC
3. Accepts one argument. That is the file name to be saved.

________________________________________________________________________
QEdge TECHNOLOGIES: # 204, 2nd Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
Page | 154
nd
QEdge TECHNOLOGIES: # 204, 2 Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
42. How do you set user extensions in Selenium IDE?

1. 1. Open user-extensions.js with an editor (Notepad, etc.); it's found in the


selenium\core\scripts folder. If it doesn't exist, just create it.
2. If you need to, commit the user-extensions.js file (like if you use
subversion).
3. Open Selenium IDE and choose the Options menu and then Options...
from that menu.
4. Make sure the path to your user-extensions.js file is entered in the
Selenium Core extensions field (like \selenium\core\scripts\user-
extensions.js)
5. Press OK button on options
6. Restart the IDE to reflect your extensions.
2. Note: After reopen, Selenium IDE may show compilations errors if the user-
extensions.js file has any syntax errors.

43. What are the limitations of Selenium IDE

1. The limitations of Selenium IDE are:


2. 1) Selenium IDE uses only HTML language
2) Conditional or branching statements execution like using of if, select
statements is not possible
3) Looping statements using is not possible directly in Selenium HTML
language in ide
4) Reading from external files like .txt, .xls is not possible
5) Reading from the external databases is not possible with ide

________________________________________________________________________
QEdge TECHNOLOGIES: # 204, 2nd Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
Page | 155
nd
QEdge TECHNOLOGIES: # 204, 2 Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
6) Exceptional handling is not there
7) A neat formatted Reporting is not possible with ide
3. To eliminate the above issues we use Selenium RC

44. What are the pre-requisites to run Selenium RC tests with Junit?

1. The pre-requisites to run Selenium RC tests with Junit:


2. 1) Jre 1.5 or better version needs to be installed
2) /jre/bin folder must be added in environment variable "path"
3) Junit folder path must be added to path or build path in eclipse
4) Selenium Java Client drivers needs to be added to the path for execution

45. How to configure Selenium RC with eclipse to run Junit Tests?

1. 1) Download eclipse. click here to download the software


2) Open eclipse -> Workspace Launcher window will open
3) Create a workspace by giving meaningful name
3) Click on Workbench
4) Create a project of type java
5) Create a package under src folder of the package
6) Add Junit to the build path
7) Add selenium rc java client driver to the build path
8) Now drag and drop your test script (.which is exported from Selenium
IDE) to the package created

46. Which is the command used for running the Selenium RC Server?

The procedure followed to run the Selenium RC Server is:


1. Open the command prompt.
________________________________________________________________________
QEdge TECHNOLOGIES: # 204, 2nd Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
Page | 156
nd
QEdge TECHNOLOGIES: # 204, 2 Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
2. Change the folder path to Selenium RC Server
3. Issue the command "java -jar selenium-server.jar"
4. For more options on how to start selenium server. Please have a look at
Selenium RC Server startup Options

47. How do you run selenium commands in slow motion in Selenium


RC?

You can run the selenium commands in RC slow motion by two ways:
selenium.setSpeed
thread.sleep

48. What is the difference between Thread.Sleep() and


Selenium.setSpeed()?

selenium.setSpeed
1. takes a single argument in string format
ex: selenium.setSpeed("2000") - will wait for 2 seconds
2. Runs each command in after setSpeed delay by the number of milliseconds
mentioned in setSpeed.

1. thread.sleep
1. takes a single argument in integer format
ex: thread.sleep(2000) - will wait for 2 seconds
2. Waits for only once at the command given at sleep.

49. Why do you use assert and verify statements in Selenium RC


without referring to selenium?

1. SeleneseTestCase is the class which is having

________________________________________________________________________
QEdge TECHNOLOGIES: # 204, 2nd Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
Page | 157
nd
QEdge TECHNOLOGIES: # 204, 2 Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
2. 1. assertTrue
2. verifyTrue
3. assertEquals
4. verifyEquals
3. We use SeleneseTestCase class to extend the selenium test class file.
4. For Ex: the test class is declared as follows
public class BookFlightSel1 extends SeleneseTestCase
5. In the above example SeleneseTestCase is the base class and BookFlightSel1
is the derived class. So, we can directly call and use the parent class
methods verify and assert without instantiating the class in BookFlightSel1
class.

50. Which are the annotations generated with JUnit 4 tests in


Selenium IDE?

1. The annotations generated with JUnit 4 tests in Selenium are:


2. 1. @Before public void method() - Will perform the method() before each
test. This method can prepare the test
2. @Test public void method() - Annotation @Test identifies that this
method is a test method.environment, e.g. read input data, initialize the
class)
3. @After public void method() - Annotation @After is executed after the
test is been executed and this method consists of post test operations such
as closure of the application.

51. What are the challenges with Selenium RC test suites when
running in JUnit?

1. The challenges with Selenium RC test suites when running in JUnit


1. Each test case of Selenium RC test will invoke the browser and closes
________________________________________________________________________
QEdge TECHNOLOGIES: # 204, 2nd Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
Page | 158
nd
QEdge TECHNOLOGIES: # 204, 2 Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
after playing back
2. All the Test cases cannot run on a single browser session
3. If there is any dependency between the test cases, it is very difficult to
execute
4. Running the test suites in junit will be helpful for only independent test
cases.
2. Note: The dependent test case related issues can be addressed by using
TestNG with junit

52. What are the advantages of using TestNG over Junit?

The advantages of using TestNG over Junit:

1. The challenges of junit can be addressed using TestNG read What are the
challenges with Selenium RC test suites when running in JUnit? for more details
2. You can execute the test cases dependent with each other read Runnning
Selenium RC Tests Sequentially using TestNG for more details
3. You can execute test cases in a group read Use Group in TestNG framework for
more details
4. You can generate the reports using TestNg

53. What are the basic annotations used to run TestNG tests in
Selenium?

1. The basic annotations used to run TestNG tests in Selenium RC:


2. @BeforeClass: The annotated method with @BeforeClass will be run before
the first test method in the current class is invoked.

________________________________________________________________________
QEdge TECHNOLOGIES: # 204, 2nd Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
Page | 159
nd
QEdge TECHNOLOGIES: # 204, 2 Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
2. @AfterClass: The annotated method with @AfterClass will be run after all
the test methods in the current class have been run.
3. @BeforeMethod: The annotated method with @BeforeMethod will be run
before each test method.
4. @AfterMethod: The annotated method with @AfterMethod will be run
after each test method.
5. @Test: Marks a class or a method @Test with as part of the test.

54. How to run test cases with dependent in Selenium using TestNG?

1. The @Test should be followed by (dependsOnMethods = "testLogin")


Note:- The test case will be executed after the testLogin case
2. Ex: @Test(dependsOnMethods = "testLogin")

55. How to run Selenium IDE test suite with user


extensions using Selenium Remote Control?

1. Read this forum topic for How to run Selenium IDE TestSuite with Selenium
Remote Control
2. to run Selenium IDE test suite with user extensions using Selenium Remote
Control we need to use the below command.
3. java -jar selenium-server.jar -userExtensions user-extensions.js -htmlSuite
"*<browser>" "<base URL>" "<Selenium test suite file>" "<results log file>" -
timeout <millise>

56. How to start selenium rc server with user extensions?

1. The command used is


java -jar selenium-server.jar -userExtensions user-extensions.js
________________________________________________________________________
QEdge TECHNOLOGIES: # 204, 2nd Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
Page | 160
nd
QEdge TECHNOLOGIES: # 204, 2 Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
2. Note: In this case, the java script file user-extensions.js file name should
always fixed. If the name or extension is changed the selenium rc server
will not start.

57. What are the limitations of selenium RC

1. The limitations of selenium RC are:


1) Switching between the multiple instances of the same browser is not
possible
2) Switching between the multiple instances of the different browsers is not
possible
3) Browser navigation, like back and forward button emulations is not
possible
4) Limited features in terms of drag and drop of objects
5) To work with Ajax based UI elements there are very limited features are
there with Selenium RC

58. What is selenium webdriver?

WebDriver is a Advanced version of RC, in this no need to start the server


manually. It has Bigger API.

WebDriver Programs:
________________________________________________________________________
QEdge TECHNOLOGIES: # 204, 2nd Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
Page | 161
nd
QEdge TECHNOLOGIES: # 204, 2 Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
WebDriver Basic – Programs-1:
package WebDriver;

import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.firefox.FirefoxDriver;

import org.openqa.selenium.ie.InternetExplorerDriver;

import org.openqa.selenium.support.ui.ExpectedConditions;

import org.openqa.selenium.support.ui.WebDriverWait;

public class Webdriver_basic {

public static void main(String[] args) throws Exception {

WebDriver driver=new FirefoxDriver();

driver.manage().window().maximize(); //maximize window

driver.manage().timeouts().pageLoadTimeout(10, TimeUnit.MINUTES);
//aplicable for all line or entire class for page to load

driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

//entire class it'll wait until elments to load

Thread.sleep(2000);

driver.get("http://google.com");

driver.findElement(By.linkText("Gmail")).click();

Thread.sleep(2000);
________________________________________________________________________
QEdge TECHNOLOGIES: # 204, 2nd Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
Page | 162
nd
QEdge TECHNOLOGIES: # 204, 2 Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
driver.findElement(By.id("Email")).sendKeys("selenium");

driver.findElement(By.id("Passwd")).sendKeys("testing");

driver.findElement(By.id("signIn")).click();

WebDriver checkboxes – Programs-2:


package WebDriver;

import org.openqa.selenium.By;

import org.openqa.selenium.Keys;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.firefox.FirefoxDriver;

import org.testng.annotations.Test;

public class checkboxes {

@Test

public void main() throws Exception {

WebDriver driver=new FirefoxDriver();

driver.get("http://www.tizag.com/htmlT/htmlcheckboxes.php");

driver.manage().window().maximize();

//driver.findElement(By.linkText("Gmail")).click();

Thread.sleep(2000);

boolean
exits=driver.findElement(By.xpath("//html/body/table[3]/tbody/tr[1]/td[2]/t" +
________________________________________________________________________
QEdge TECHNOLOGIES: # 204, 2nd Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
Page | 163
nd
QEdge TECHNOLOGIES: # 204, 2 Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
"able/tbody/tr/td/div[4]/input[1]")).isEnabled();

for(int i=1;i<=4;i++){

driver.findElement(By.xpath("//html/body/table[3]/tbody/tr[1]/td[2]/table/t
body/tr/td/div[4]/input["+i+"]")).sendKeys(Keys.SPACE,Keys.TAB);

WebDriver GetText – Programs-3:


package WebDriver;

import org.openqa.selenium.By;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.firefox.FirefoxDriver;

import org.testng.annotations.Test;

public class getstring {

@Test

public void main() throws Exception {

WebDriver driver=new FirefoxDriver();

driver.get("http://gmail.com");

driver.manage().window().maximize();

driver.findElement(By.xpath("//*[@id='link-signup']")).click();

Thread.sleep(2000);
________________________________________________________________________
QEdge TECHNOLOGIES: # 204, 2nd Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
Page | 164
nd
QEdge TECHNOLOGIES: # 204, 2 Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
String
text=driver.findElement(By.xpath("//*[@id='recaptcha_image']/img")).getText();

System.out.println(text);

WebDriver Extract Links, Page Title, Page Source –


Programs-4:
package WebDriver;

import java.util.List;

import org.openqa.selenium.By;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.WebElement;

import org.openqa.selenium.firefox.FirefoxDriver;

public class webdriver_links {

public static void main(String[] args) throws Exception {

WebDriver driver=new FirefoxDriver();

driver.get("http://google.com");

driver.manage().window().maximize();

//driver.findElement(By.linkText("Gmail")).click();

Thread.sleep(2000);

/*System.out.println(driver.getCurrentUrl());

System.out.println(driver.getTitle());

________________________________________________________________________
QEdge TECHNOLOGIES: # 204, 2nd Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
Page | 165
nd
QEdge TECHNOLOGIES: # 204, 2 Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
System.out.println("********Page source******");

System.out.println(driver.getPageSource());*/

List<WebElement> links=driver.findElements(By.tagName("a"));

System.out.println("Total links="+links.size());

for(int i=0;i<links.size();i++){

System.out.println(links.get(i).getText());

WebDriver Handle WebTable – Programs-5:


package WebTable;

import org.openqa.selenium.By;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.firefox.FirefoxDriver;

import org.openqa.selenium.internal.seleniumemulation.GetText;

public class webtabe_webdriver {

public static void main(String[] args) {

WebDriver driver =new FirefoxDriver();

driver.manage().window().maximize();

driver.get("http://www.timeanddate.com/worldclock/");

//System.out.println(driver.findElement(By.xpath("//*[@id='p72']")).getText());

________________________________________________________________________
QEdge TECHNOLOGIES: # 204, 2nd Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
Page | 166
nd
QEdge TECHNOLOGIES: # 204, 2 Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
for(int i=1;i<=36;i++){

for(int j=1;j<=8;j++){

System.out.print(driver.findElement(By.xpath("//html/body/div[9]/table/tbod
y/tr["+i+"]/td["+j+"]")).getText()+"---");

System.out.println();

Out put of WebTable Program:


Accra‐‐‐Wed 06:09‐‐‐Casablanca *‐‐‐Wed 07:09‐‐‐Kiritimati‐‐‐
Wed 20:09‐‐‐Prague *‐‐‐Wed 08:09‐‐‐ 
Addis Ababa‐‐‐Wed 09:09‐‐‐Chicago *‐‐‐Wed 01:09‐‐‐Kolkata‐‐‐
Wed 11:39‐‐‐Reykjavik‐‐‐Wed 06:09‐‐‐ 
Adelaide‐‐‐Wed 15:39‐‐‐Columbus *‐‐‐Wed 02:09‐‐‐Kuala 
Lumpur‐‐‐Wed 14:09‐‐‐Rio de Janeiro‐‐‐Wed 03:09‐‐‐ 
Algiers‐‐‐Wed 07:09‐‐‐Copenhagen *‐‐‐Wed 08:09‐‐‐Kuwait 
City‐‐‐Wed 09:09‐‐‐Riyadh‐‐‐Wed 09:09‐‐‐ 
Almaty‐‐‐Wed 12:09‐‐‐Dallas *‐‐‐Wed 01:09‐‐‐Kyiv *‐‐‐Wed 
09:09‐‐‐Rome *‐‐‐Wed 08:09‐‐‐ 
Amman *‐‐‐Wed 09:09‐‐‐Dar es Salaam‐‐‐Wed 09:09‐‐‐La Paz‐‐‐
Wed 02:09‐‐‐Salt Lake City *‐‐‐Wed 00:09‐‐‐ 
Amsterdam *‐‐‐Wed 08:09‐‐‐Darwin‐‐‐Wed 15:39‐‐‐Lagos‐‐‐Wed 
07:09‐‐‐San Francisco *‐‐‐Tue 23:09‐‐‐ 
Anadyr‐‐‐Wed 18:09‐‐‐Denver *‐‐‐Wed 00:09‐‐‐Lahore‐‐‐Wed 
11:09‐‐‐San Juan‐‐‐Wed 02:09‐‐‐ 
Anchorage *‐‐‐Tue 22:09‐‐‐Detroit *‐‐‐Wed 02:09‐‐‐Las Vegas 
*‐‐‐Tue 23:09‐‐‐San Salvador‐‐‐Wed 00:09‐‐‐ 
________________________________________________________________________
QEdge TECHNOLOGIES: # 204, 2nd Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
Page | 167
nd
QEdge TECHNOLOGIES: # 204, 2 Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
Ankara *‐‐‐Wed 09:09‐‐‐Dhaka‐‐‐Wed 12:09‐‐‐Lima‐‐‐Wed 01:09‐
‐‐Santiago‐‐‐Wed 02:09‐‐‐ 
Antananarivo‐‐‐Wed 09:09‐‐‐Doha‐‐‐Wed 09:09‐‐‐Lisbon *‐‐‐Wed 
07:09‐‐‐Santo Domingo‐‐‐Wed 02:09‐‐‐ 
Asuncion‐‐‐Wed 02:09‐‐‐Dubai‐‐‐Wed 10:09‐‐‐London *‐‐‐Wed 
07:09‐‐‐São Paulo‐‐‐Wed 03:09‐‐‐ 
Athens *‐‐‐Wed 09:09‐‐‐Dublin *‐‐‐Wed 07:09‐‐‐Los Angeles *‐
‐‐Tue 23:09‐‐‐Seattle *‐‐‐Tue 23:09‐‐‐ 
Atlanta *‐‐‐Wed 02:09‐‐‐Edmonton *‐‐‐Wed 00:09‐‐‐Madrid *‐‐‐
Wed 08:09‐‐‐Seoul‐‐‐Wed 15:09‐‐‐ 
Auckland‐‐‐Wed 18:09‐‐‐Frankfurt *‐‐‐Wed 08:09‐‐‐Managua‐‐‐
Wed 00:09‐‐‐Shanghai‐‐‐Wed 14:09‐‐‐ 
Baghdad‐‐‐Wed 09:09‐‐‐Guatemala‐‐‐Wed 00:09‐‐‐Manila‐‐‐Wed 
14:09‐‐‐Singapore‐‐‐Wed 14:09‐‐‐ 
Bangalore‐‐‐Wed 11:39‐‐‐Halifax *‐‐‐Wed 03:09‐‐‐Melbourne‐‐‐
Wed 16:09‐‐‐Sofia *‐‐‐Wed 09:09‐‐‐ 
Bangkok‐‐‐Wed 13:09‐‐‐Hanoi‐‐‐Wed 13:09‐‐‐Mexico City *‐‐‐
Wed 01:09‐‐‐St. John's *‐‐‐Wed 03:39‐‐‐ 
Barcelona *‐‐‐Wed 08:09‐‐‐Harare‐‐‐Wed 08:09‐‐‐Miami *‐‐‐Wed 
02:09‐‐‐Stockholm *‐‐‐Wed 08:09‐‐‐ 
Beijing‐‐‐Wed 14:09‐‐‐Havana *‐‐‐Wed 02:09‐‐‐Minneapolis *‐‐
‐Wed 01:09‐‐‐Suva‐‐‐Wed 18:09‐‐‐ 
Beirut *‐‐‐Wed 09:09‐‐‐Helsinki *‐‐‐Wed 09:09‐‐‐Minsk‐‐‐Wed 
09:09‐‐‐Sydney‐‐‐Wed 16:09‐‐‐ 
Belgrade *‐‐‐Wed 08:09‐‐‐Hong Kong‐‐‐Wed 14:09‐‐‐Montevideo‐
‐‐Wed 03:09‐‐‐Taipei‐‐‐Wed 14:09‐‐‐ 
Berlin *‐‐‐Wed 08:09‐‐‐Honolulu‐‐‐Tue 20:09‐‐‐Montreal *‐‐‐
Wed 02:09‐‐‐Tallinn *‐‐‐Wed 09:09‐‐‐ 
Bogota‐‐‐Wed 01:09‐‐‐Houston *‐‐‐Wed 01:09‐‐‐Moscow‐‐‐Wed 
10:09‐‐‐Tashkent‐‐‐Wed 11:09‐‐‐ 
Boston *‐‐‐Wed 02:09‐‐‐Indianapolis *‐‐‐Wed 02:09‐‐‐Mumbai‐‐
‐Wed 11:39‐‐‐Tegucigalpa‐‐‐Wed 00:09‐‐‐ 
Brasilia‐‐‐Wed 03:09‐‐‐Islamabad‐‐‐Wed 11:09‐‐‐Nairobi‐‐‐Wed 
09:09‐‐‐Tehran *‐‐‐Wed 10:39‐‐‐ 
Brisbane‐‐‐Wed 16:09‐‐‐Istanbul *‐‐‐Wed 09:09‐‐‐Nassau *‐‐‐
Wed 02:09‐‐‐Tokyo‐‐‐Wed 15:09‐‐‐ 

________________________________________________________________________
QEdge TECHNOLOGIES: # 204, 2nd Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
Page | 168
nd
QEdge TECHNOLOGIES: # 204, 2 Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
Brussels *‐‐‐Wed 08:09‐‐‐Jakarta‐‐‐Wed 13:09‐‐‐New Delhi‐‐‐
Wed 11:39‐‐‐Toronto *‐‐‐Wed 02:09‐‐‐ 
Bucharest *‐‐‐Wed 09:09‐‐‐Jerusalem *‐‐‐Wed 09:09‐‐‐New 
Orleans *‐‐‐Wed 01:09‐‐‐Vancouver *‐‐‐Tue 23:09‐‐‐ 
Budapest *‐‐‐Wed 08:09‐‐‐Johannesburg‐‐‐Wed 08:09‐‐‐New York 
*‐‐‐Wed 02:09‐‐‐Vienna *‐‐‐Wed 08:09‐‐‐ 
Buenos Aires‐‐‐Wed 03:09‐‐‐Kabul‐‐‐Wed 10:39‐‐‐Oslo *‐‐‐Wed 
08:09‐‐‐Warsaw *‐‐‐Wed 08:09‐‐‐ 
Cairo‐‐‐Wed 08:09‐‐‐Karachi‐‐‐Wed 11:09‐‐‐Ottawa *‐‐‐Wed 
02:09‐‐‐Washington DC *‐‐‐Wed 02:09‐‐‐ 
Calgary *‐‐‐Wed 00:09‐‐‐Kathmandu‐‐‐Wed 11:54‐‐‐Paris *‐‐‐
Wed 08:09‐‐‐Winnipeg *‐‐‐Wed 01:09‐‐‐ 
Canberra‐‐‐Wed 16:09‐‐‐Khartoum‐‐‐Wed 09:09‐‐‐Perth‐‐‐Wed 
14:09‐‐‐Yangon‐‐‐Wed 12:39‐‐‐ 
Cape Town‐‐‐Wed 08:09‐‐‐Kingston‐‐‐Wed 01:09‐‐‐Philadelphia 
*‐‐‐Wed 02:09‐‐‐Zagreb *‐‐‐Wed 08:09‐‐‐ 
Caracas‐‐‐Wed 01:39‐‐‐Kinshasa‐‐‐Wed 07:09‐‐‐Phoenix‐‐‐Tue 
23:09‐‐‐Zürich *‐‐‐Wed 08:09‐‐‐ 

For Some More Programs in class room


training or online Training.

________________________________________________________________________
QEdge TECHNOLOGIES: # 204, 2nd Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
 
GRID
Introduction
Grid allows you to :

• scale by distributing tests on several machines ( parallel execution )


• manage multiple environments from a central point, making it easy to run the tests
against a vast combination of browsers / OS.
• minimize the maintenance time for the grid by allowing you to implement custom hooks
to leverage virtual infrastructure for instance.

Quick Start
This example will show you how to start the Selenium 2 Hub, and register both a WebDriver
node and a Selenium 1 RC legacy node. We’ll also show you how to call the grid from Java.
The hub and nodes are shown here running on the same machine, but of course you can copy
the selenium-server-standalone to multiple machines.

Note: The selenium-server-standalone package includes the Hub, WebDriver, and legacy RC
needed to run the grid. Ant is not required anymore. You can download the selenium-server-
standalone-*.jar from http://code.google.com/p/selenium/downloads/list. This walk-through
assumes you already have Java installed.

Step 1: Start the hub

The Hub is the central point that will receive all the test request and distribute them the the right
nodes.

Open a command prompt and navigate to the directory where you copied the selenium-server-
standalone file. Type the following command:

java -jar selenium-server-standalone-2.14.0.jar -role hub

The hub will automatically start-up using port 4444 by default. To change the default port, you
can add the optional parameter -port when you run the command. You can view the status of
the hub by opening a browser window and navigating to: http://localhost:4444/grid/console

Step 2: Start the nodes

Regardless on whether you want to run a grid with new WebDriver functionality, or a grid with
Selenium 1 RC functionality, or both at the same time, you use the same selenium-server-
standalone jar file to start the nodes.
java -jar selenium-server-standalone-2.14.0.jar -role node -hub
http://localhost:4444/grid/register

Note: The port defaults to 5555 if not specified whenever the "-role" option is provided and is not
hub.

For backwards compatibility "wd" and "rc" roles are still a valid subset of the "node" role. But
those roles limit the types of remote connections to their corresponding API, while "node" allows
both RC and WebDriver remote connections.

Using grid to run tests


( using java as an example ) Now that the grid is in-place, we need to access the grid from our
test cases. For the Selenium 1 RC nodes, you can continue to use the DefaultSelenium object
and pass in the hub information:

Selenium selenium = new DefaultSelenium(“localhost”, 4444, “*firefox”,


“http://www.google.com”);

For WebDriver nodes, you will need to use the RemoteWebDriver and
the DesiredCapabilities object to define which browser, version and platform you wish to use.
Create the target browser capabilities you want to run the tests against:

DesiredCapabilities capability = DesiredCapabilities.firefox();

Pass that into the RemoteWebDriver object:

WebDriver driver = new RemoteWebDriver(new


URL("http://localhost:4444/wd/hub"), capability);

The hub will then assign the test to a matching node.

A node matches if all the requested capabilities are met. To request specific capabilities on the
grid, specify them before passing it into the WebDriver object.

capability.setBrowserName();
capability.setPlatform();
capability.setVersion()
capability.setCapability(,);

Example: A node registered with the setting:

-browser browserName=firefox,version=3.6,platform=LINUX
will be a match for:
capability.setBrowserName(“firefox” );
capability.setPlatform(“LINUX”);
capability.setVersion(“3.6”);
and would also be a match for

capability.setBrowserName(“firefox” );
capability.setVersion(“3.6”);

The capabilities that are not specified will be ignored. If you specify capabilities that do not exist
on your grid (for example, your test specifies Firefox version 4.0, but have no Firefox 4 instance)
then there will be no match and the test will fail to run.

Configuring the nodes


The node can be configured in 2 different ways; one is by specifying command line parameters,
the other is by specifying a json file.

Configuring the nodes by command line


By default, this starts 11 browsers : 5 Firefox, 5 Chrome, 1 Internet Explorer. The maximum
number of concurrent tests is set to 5 by default. To change this and other browser settings, you
can pass in parameters to each -browser switch (each switch represents a node based on your
parameters). If you use the -browser parameter, the default browsers will be ignored and only
what you specify command line will be used.

-browser browserName=firefox,version=3.6,maxInstances=5,platform=LINUX

This setting starts 5 Firefox 3.6 nodes on a linux machine.

If your remote machine has multiple versions of Firefox you’d like to use, you can map the
location of each binary to a particular version on the same machine:

-browser
browserName=firefox,version=3.6,firefox_binary=/home/myhomedir/firefox36/fire
fox,maxInstances=3,platform=LINUX -browser
browserName=firefox,version=4,firefox_binary=/home/myhomedir/firefox4/firefox
,maxInstances=4,platform=LINUX

Tip: If you need to provide a space somewhere in your browser parameters, then surround the
parameters with quotation marks:

-browser “browserName=firefox,version=3.6,firefox_binary=c:\Program
Files\firefox ,maxInstances=3, platform=WINDOWS”

Optional parameters
• -port 4444 (4444 is default)
• -timeout 30 (30 is default) The timeout in seconds before the hub automatically releases
a node that hasn't received any requests for more than the specified number of seconds.
After this time, the node will be released for another test in the queue. This helps to clear
client crashes without manual intervention. To remove the timeout completely, specify -
timeout 0 and the hub will never release the node.
Note: This is NOT the WebDriver timeout for all ”wait for WebElement” type of commands.

• -maxSession 5 (5 is default) The maximum number of browsers that can run in parallel
on the node. This is different from the maxInstance of supported browsers (Example: For
a node that supports Firefox 3.6, Firefox 4.0 and Internet Explorer 8, maxSession=1 will
ensure that you never have more than 1 browser running. With maxSession=2 you
can have 2 Firefox tests at the same time, or 1 Internet Explorer and 1 Firefox test).

• -browser < params > If -browser is not set, a node will start with 5 firefox, 1 chrome, and
1 internet explorer instance (assuming it’s on a windows box). This parameter can be set
multiple times on the same line to define multiple types of browsers.

Parameters allowed for -browser: browserName={android, chrome, firefox, htmlunit, internet


explorer, iphone, opera} version={browser version} firefox_binary={path to executable binary}
chrome_binary={path to executable binary} maxInstances={maximum number of browsers of
this type} platform={WINDOWS, LINUX, MAC}

• -registerCycle = how often in ms the node will try to register itself again.Allow to restart
the hub without having to restart the nodes.

• Relly large (>50 node) Hub installations may need to increase the jetty threads by setting
-DPOOL_MAX=512 (or larger) on the java command line.

Configuring timeouts (Version 2.21 required)


Timeouts in the grid should normally be handled through webDriver.manage().timeouts(), which
will control how the different operations time out.

To preserve run-time integrity of a grid with selenium-servers, there are two other timeout
values that can be set.

On the hub, setting the -timeout command line option to "30" seconds will ensure all resources
are reclaimed 30 seconds after a client crashes. On the hub you can also set -browserTimeout
60 to make the maximum time a node is willing to hang inside the browser 60 seconds. This will
ensure all resources are reclaimed slightly after 60 seconds. All the nodes use these two values
from the hub if they are set. Locally set parameters on a single node has precedence, it is
generally recommended not to set these timeouts on the node.

The browserTimeout should be:

• Higher than the socket lock timeout (45 seconds)


• Generally higher than values used in webDriver.manage().timeouts(), since this
mechanism is a "last line of defense".
Configuring the nodes by JSON
java -jar selenium-server-standalone.jar -role node -nodeConfig nodeconfig.json

A sample nodeconfig file can be seen

{
"capabilities":
[
{
"browserName": "*firefox",
"maxInstances": 5,
"seleniumProtocol": "Selenium"
},
{
"browserName": "*googlechrome",
"maxInstances": 5,
"seleniumProtocol": "Selenium"
},
{
"browserName": "*iexplore",
"maxInstances": 1,
"seleniumProtocol": "Selenium"
},
{
"browserName": "firefox",
"maxInstances": 5,
"seleniumProtocol": "WebDriver"
},
{
"browserName": "chrome",
"maxInstances": 5,
"seleniumProtocol": "WebDriver"
},
{
"browserName": "internet explorer",
"maxInstances": 1,
"seleniumProtocol": "WebDriver"
}
],
"configuration":
{
"proxy": "org.openqa.grid.selenium.proxy.DefaultRemoteProxy",
"maxSession": 5,
"port": 5555,
"host": ip,
"register": true,
"registerCycle": 5000,
"hubPort": 4444,
"hubHost": ip
}
}
Hide details

Configuring the hub by JSON


java -jar selenium-server-standalone.jar -role hub -hubConfig hubconfig.json

A sample hubconfig.json file can be seen

{
"host": null,
"port": 4444,
"newSessionWaitTimeout": -1,
"servlets" : [],
"prioritizer": null,
"capabilityMatcher":
"org.openqa.grid.internal.utils.DefaultCapabilityMatcher",
"throwOnCapabilityNotPresent": true,
"nodePolling": 5000,
"cleanUpCycle": 5000,
"timeout": 300000,
"browserTimeout": 0,
"maxSession": 5
}

Hub diagnostic messages


Upon detecting anomalious usage patterns, the hub can give the following message:

Client requested session XYZ that was terminated due to REASON


Reason Cause/fix
The session timed out because the client did not access
TIMEOUT it within the timeout. If the client has been somehow
suspended, this may happen when it wakes up

The node timed out the browser because it was hanging


BROWSER_TIMEOUT
for too long (parameter browserTimeout)

A client waiting in queue has given up once it was


ORPHAN
offered a new session

The session was stopped using an ordinary call to


CLIENT_STOPPED_SESSION
stop/quit on the client. Why are you using it again??

The client process (your code) appears to have died or


CLIENT_GONE otherwise not responded to our requests, intermittent
network issues may also cause

The hub was unable to forward to the node. Out of


FORWARDING_TO_NODE_FAILED
memory errors/node stability issues or network problems

The node failed to create the browser. This can typically


happen when there are environmental/configuration
CREATIONFAILED
problems on the node. Try using the node directly to
track problem.

The session has been discarded because the node has


PROXY_REREGISTRATION
re-registered on the grid (in mid-test)

Tips for running with grid


If your tests are running in parallel, make sure that each thread deallocates its webdriver
resource independently of any other tests running on other threads. Starting 1 browser per
thread at the start of the test-run and deallocating all browsers at the end is not a good idea. (If
one test-case decides to consume abnormal amounts of time you may get timeouts on all the
other tests because they're waiting for the slow test. This can be very confusing)

 
What is Maven?
Maven is a project management and comprehension tool. Maven provides developers a complete build
lifecycle framework. Development team can automate the project's build infrastructure in almost no time
as Maven uses a standard directory layout and a default build lifecycle.

In case of multiple development teams environment, Maven can set-up the way to work as per standards
in a very short time. As most of the project setups are simple and reusable, Maven makes life of
developer easy while creating reports, checks, build and testing automation setups.

Maven provides developers ways to manage following:

• Builds

• Documentation

• Reporting

• Dependencies

• SCMs

• Releases

• Distribution

• mailing list

To summarize, Maven simplifies and standardizes the project build process. It handles compilation,
distribution, documentation, team collaboration and other tasks seamlessly. Maven increases reusability
and takes care of most of build related tasks.

Maven History
Maven was originally designed to simplify building processes in Jakarta Turbine project. There were
several projects and each project contained slightly different ANT build files. JARs were checked into
CVS.

Apache group then developed Maven which can build multiple projects together, publish projects
information, deploy projects, share JARs across several projects and help in collaboration of teams.

Maven Objective
Maven primary goal is to provide developer

• A comprehensive model for projects which is reusable, maintainable, and easier to comprehend.

• plugins or tools that interact with this declarative model.

Maven project structure and contents are declared in an xml file, pom.xml referred as Project Object
Model (POM), which is the fundamental unit of the entire Maven system. Refer to Maven POM section for
more detail.
Convention over Configuration
Maven uses Convention over Configuration which means developers are not required to create build
process themselves.

Developers do not have to mention each and every configuration detail. Maven provides sensible default
behavior for projects. When a Maven project is created, Maven creates default project structure.
Developer is only required to place files accordingly and he/she need not to define any configuration in
pom.xml.

As an example, following table shows the default values for project source code files, resource files and
other configurations. Assuming, ${basedir} denotes the project location:
Item Default

source code ${basedir}/src/main/java

resources ${basedir}/src/main/resources

Tests ${basedir}/src/test

Complied byte code ${basedir}/target/classes

distributable JAR ${basedir}/target

In order to build the project, Maven provides developers options to mention life-cycle goals and project
dependencies (that rely on Maven pluging capabilities and on its default conventions). Much of the project
management and build related tasks are maintained by Maven plugins.

Developers can build any given Maven project without need to understand how the individual plugins
work. Refer to Maven Plug-ins section for more detail.

Maven is Java based tool, so the very first requirement is to have JDK installed in your machine.

System Requirement
JDK 1.5 or above.

Memory no minimum requirement.

Disk Space no minimum requirement.

Operating System no minimum requirement.

Step 1 - verify Java installation in your machine


Now open console and execute the following java command.
OS Task Command

Windows Open Command Console c:\> java -version

Linux Open Command Terminal $ java -version

Mac Open Terminal machine:~ joseph$ java -version


Let's verify the output for all the operating systems:

OS Output

java version "1.6.0_21"


Windows Java(TM) SE Runtime Environment (build 1.6.0_21-b07)
Java HotSpot(TM) Client VM (build 17.0-b17, mixed mode, sharing)

java version "1.6.0_21"


Linux Java(TM) SE Runtime Environment (build 1.6.0_21-b07)
Java HotSpot(TM) Client VM (build 17.0-b17, mixed mode, sharing)

java version "1.6.0_21"


Mac Java(TM) SE Runtime Environment (build 1.6.0_21-b07)
Java HotSpot(TM)64-Bit Server VM (build 17.0-b17, mixed mode, sharing)
If you do not have Java installed, install the Java Software Development Kit (SDK)
fromhttp://www.oracle.com/technetwork/java/javase/downloads/index.html. We are assuming Java
1.6.0_21 as installed version for this tutorial.

Step 2: Set JAVA environment


Set the JAVA_HOME environment variable to point to the base directory location where Java is installed
on your machine. For example
OS Output

Windows Set the environment variable JAVA_HOME to C:\Program Files\Java\jdk1.6.0_21

Linux export JAVA_HOME=/usr/local/java-current

Mac export JAVA_HOME=/Library/Java/Home

Append Java compiler location to System Path.

OS Output

Append the string ;C:\Program Files\Java\jdk1.6.0_21\bin to the end of the system


Windows
variable, Path.

Linux export PATH=$PATH:$JAVA_HOME/bin/

Mac not required


Verify Java Installation using java -version command explained above.

Step 3: Download Maven archive


Download Maven 2.2.1 from http://maven.apache.org/download.html
OS Archive name

Windows apache-maven-2.0.11-bin.zip

Linux apache-maven-2.0.11-bin.tar.gz

Mac apache-maven-2.0.11-bin.tar.gz

Step 4: Extract the Maven archive


Extract the archive, to the directory you wish to install Maven 2.2.1. The subdirectory apache-maven-
2.2.1 will be created from the archive.

OS Location (can be different based on your installation)

Windows C:\Program Files\Apache Software Foundation\apache-maven-2.2.1

Linux /usr/local/apache-maven

Mac /usr/local/apache-maven

Step 5: Set Maven environment variables


Add M2_HOME, M2, MAVEN_OPTS to environment variables.

OS Output

Set the environment variables using system properties.


M2_HOME=C:\Program Files\Apache Software Foundation\apache-maven-2.2.1
Windows
M2=%M2_HOME%\bin
MAVEN_OPTS=-Xms256m -Xmx512m

Open command terminal and set environment variables.


export M2_HOME=/usr/local/apache-maven/apache-maven-2.2.1
Linux
export M2=%M2_HOME%\bin
export MAVEN_OPTS=-Xms256m -Xmx512m

Open command terminal and set environment variables.


export M2_HOME=/usr/local/apache-maven/apache-maven-2.2.1
Mac
export M2=%M2_HOME%\bin
export MAVEN_OPTS=-Xms256m -Xmx512m

Step 6: Add Maven bin directory location to system


path
Now append M2 variable to System Path

OS Output

Windows Append the string ;%M2% to the end of the system variable, Path.

Linux export PATH=$M2:$PATH

Mac export PATH=$M2:$PATH

Step 8: Verify Maven installation


Now open console, execute the following mvn command.
OS Task Command

Windows Open Command Console c:\> mvn --version

Linux Open Command Terminal $ mvn --version

Mac Open Terminal machine:~ joseph$ mvn --version


Finally, verify the output of the above commands, which should be something as follows:

OS Output

Apache Maven 2.2.1 (r801777; 2009-08-07 00:46:01+0530)


Windows Java version: 1.6.0_21
Java home: C:\Program Files\Java\jdk1.6.0_21\jre

Apache Maven 2.2.1 (r801777; 2009-08-07 00:46:01+0530)


Linux Java version: 1.6.0_21
Java home: C:\Program Files\Java\jdk1.6.0_21\jre

Apache Maven 2.2.1 (r801777; 2009-08-07 00:46:01+0530)


Mac Java version: 1.6.0_21
Java home: C:\Program Files\Java\jdk1.6.0_21\jre

POM stands for Project Object Model. It is fundamental Unit of Work in Maven. It is an XML file. It always
resides in the base directory of the project as pom.xml.

The POM contains information about the project and various configuration detail used by Maven to build
the project(s).

POM also contains the goals and plugins. While executing a task or goal, Maven looks for the POM in the
current directory. It reads the POM, gets the needed configuration information, then executes the goal.
Some of the configuration that can be specified in the POM are following:

• project dependencies

• plugins

• goals

• build profiles

• project version

• developers

• mailing list

Before creating a POM, we should first decide the project group (groupId), its name(artifactId) and its
version as these attributes help in uniquely identifying the project in repository.

Example POM
<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>com.companyname.project-group</groupId>
<artifactId>project</artifactId>
<version>1.0</version>
</project>

It should be noted that there should be a single POM file for each project.

• All POM files require the project element and three mandatory fields: groupId, artifactId,version.
• Projects notation in repository is groupId:artifactId:version.
• Root element of POM.xml is project and it has three major sub-nodes :
Node Description

This is an Id of project's group. This is generally unique amongst an organization or


groupId a project. For example, a banking group com.company.bank has all bank related
projects.

This is an Id of the project.This is generally name of the project. For example,


artifactId consumer-banking. Along with the groupId, the artifactId defines the artifact's
location within the repository.

This is the version of the project.Along with the groupId, It is used within an artifact's
repository to separate versions from each other. For example:
version
com.company.bank:consumer-banking:1.0
com.company.bank:consumer-banking:1.1.

Super POM
All POMs inherit from a parent (despite explicitly defined or not). This base POM is known as the Super
POM, and contains values inherited by default.

Maven use the effective pom (configuration from super pom plus project configuration) to execute
relevant goal. It helps developer to specify minimum configuration detail in his/her pom.xml. Although
configurations can be overridden easily.

An easy way to look at the default configurations of the super POM is by running the following
command: mvn help:effective-pom

Create a pom.xml in any directory on your computer.Use the content of above mentioned example pom.

In example below, We've created a pom.xml in C:\MVN\project folder.

Now open command console, go the folder containing pom.xml and execute the following mvncommand.
C:\MVN\project>mvn help:effective-pom

Maven will start processing and display the effective-pom.

[INFO] Scanning for projects...


[INFO] Searching repository for plugin with prefix: 'help'.
[INFO] ----------------------------------------------------------------------
--
[INFO] Building Unnamed - com.companyname.project-group:project-name:jar:1.0
[INFO] task-segment: [help:effective-pom] (aggregator-style)
[INFO] ----------------------------------------------------------------------
--
[INFO] [help:effective-pom {execution: default-cli}]
[INFO]
.....

[INFO] ----------------------------------------------------------------------
--
[INFO] BUILD SUCCESSFUL
[INFO] ----------------------------------------------------------------------
--
[INFO] Total time: < 1 second
[INFO] Finished at: Thu Jul 05 11:41:51 IST 2012
[INFO] Final Memory: 6M/15M
[INFO] ----------------------------------------------------------------------
--

Effective POM displayed as result in console, after inheritance, interpolation, and profiles are applied.

<?xml version="1.0" encoding="UTF-8"?>


<!-- ================================================================= -->
<!-- -->
<!-- Generated by Maven Help Plugin on 2012-07-05T11:41:51 -->
<!-- See: http://maven.apache.org/plugins/maven-help-plugin/ -->
<!-- -->
<!-- ================================================================= -->

<!-- ================================================================= -->


<!-- -->
<!-- Effective POM for project -->
<!-- 'com.companyname.project-group:project-name:jar:1.0' -->
<!-- -->
<!-- ================================================================= -->

<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 h
ttp://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.companyname.project-group</groupId>
<artifactId>project</artifactId>
<version>1.0</version>
<build>
<sourceDirectory>C:\MVN\project\src\main\java</sourceDirectory>
<scriptSourceDirectory>src/main/scripts</scriptSourceDirectory>
<testSourceDirectory>C:\MVN\project\src\test\java</testSourceDirectory>
<outputDirectory>C:\MVN\project\target\classes</outputDirectory>
<testOutputDirectory>C:\MVN\project\target\test-
classes</testOutputDirectory>
<resources>
<resource>
<mergeId>resource-0</mergeId>
<directory>C:\MVN\project\src\main\resources</directory>
</resource>
</resources>
<testResources>
<testResource>
<mergeId>resource-1</mergeId>
<directory>C:\MVN\project\src\test\resources</directory>
</testResource>
</testResources>
<directory>C:\MVN\project\target</directory>
<finalName>project-1.0</finalName>
<pluginManagement>
<plugins>
<plugin>
<artifactId>maven-antrun-plugin</artifactId>
<version>1.3</version>
</plugin>
<plugin>
<artifactId>maven-assembly-plugin</artifactId>
<version>2.2-beta-2</version>
</plugin>
<plugin>
<artifactId>maven-clean-plugin</artifactId>
<version>2.2</version>
</plugin>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.0.2</version>
</plugin>
<plugin>
<artifactId>maven-dependency-plugin</artifactId>
<version>2.0</version>
</plugin>
<plugin>
<artifactId>maven-deploy-plugin</artifactId>
<version>2.4</version>
</plugin>
<plugin>
<artifactId>maven-ear-plugin</artifactId>
<version>2.3.1</version>
</plugin>
<plugin>
<artifactId>maven-ejb-plugin</artifactId>
<version>2.1</version>
</plugin>
<plugin>
<artifactId>maven-install-plugin</artifactId>
<version>2.2</version>
</plugin>
<plugin>
<artifactId>maven-jar-plugin</artifactId>
<version>2.2</version>
</plugin>
<plugin>
<artifactId>maven-javadoc-plugin</artifactId>
<version>2.5</version>
</plugin>
<plugin>
<artifactId>maven-plugin-plugin</artifactId>
<version>2.4.3</version>
</plugin>
<plugin>
<artifactId>maven-rar-plugin</artifactId>
<version>2.2</version>
</plugin>
<plugin>
<artifactId>maven-release-plugin</artifactId>
<version>2.0-beta-8</version>
</plugin>
<plugin>
<artifactId>maven-resources-plugin</artifactId>
<version>2.3</version>
</plugin>
<plugin>
<artifactId>maven-site-plugin</artifactId>
<version>2.0-beta-7</version>
</plugin>
<plugin>
<artifactId>maven-source-plugin</artifactId>
<version>2.0.4</version>
</plugin>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.4.3</version>
</plugin>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>2.1-alpha-2</version>
</plugin>
</plugins>
</pluginManagement>
<plugins>
<plugin>
<artifactId>maven-help-plugin</artifactId>
<version>2.1.1</version>
</plugin>
</plugins>
</build>
<repositories>
<repository>
<snapshots>
<enabled>false</enabled>
</snapshots>
<id>central</id>
<name>Maven Repository Switchboard</name>
<url>http://repo1.maven.org/maven2</url>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<releases>
<updatePolicy>never</updatePolicy>
</releases>
<snapshots>
<enabled>false</enabled>
</snapshots>
<id>central</id>
<name>Maven Plugin Repository</name>
<url>http://repo1.maven.org/maven2</url>
</pluginRepository>
</pluginRepositories>
<reporting>
<outputDirectory>C:\MVN\project\target/site</outputDirectory>
</reporting>
</project>

In above pom.xml , you can see the default project source folders structure,output directory, plug-ins
required, repositories, reporting directory which Maven will be using while executing the desired goals.

Maven pom.xml is also not required to be written manually.

Maven provides numerous archetype plugins to create projects which in order create the project structure
and pom.xml

What is Build Lifecycle?


A Build Lifecycle is a well defined sequence of phases which define the order in which the goals are to be executed.
Here phase represents a stage in life cycle.
As an example, a typical Maven Build Lifecycle is consists of following sequence of phases
Phase Handles Description

prepare-resources resource copying Resource copying can be customized in this phase.

compile compilation Source code compilation is done in this phase.

This phase creates the JAR / WAR package as


package packaging
mentioned in packaging in POM.xml.

This phase installs the package in local / remote


install installation
maven repository.
There are always pre and post phases which can be used to register goals which must run prior to or after a
particular phase.

When Maven starts building a project, it steps through a defined sequence of phases and executes goals which are
registered with each phase. Maven has following three standard lifecycles:

• clean

• default(or build)

• site

A goal represents a specific task which contributes to the building and managing of a project. It may be bound to zero
or more build phases. A goal not bound to any build phase could be executed outside of the build lifecycle by direct
invocation.
The order of execution depends on the order in which the goal(s) and the build phase(s) are invoked. For example,
consider the command below. The clean and package arguments are build phases while the dependency:copy-
dependencies is a goal.
mvn clean dependency:copy-dependencies package
Here the clean phase will be executed first, and then the dependency:copy-dependencies goal will be executed, and
finally package phase will be executed.

Clean Lifecycle
When we execute mvn post-clean command, Maven invokes the clean lifecycle consisting of the following phases.
• pre-clean

• clean

• post-clean

Maven clean goal (clean:clean) is bound to the clean phase in the clean lifecycle. Its clean:clean goal deletes the
output of a build by deleting the build directory. Thus when mvn clean command executes, Maven deletes the build
directory.

We can customize this behavior by mentioning goals in any of the above phases of clean life cycle.

In the following example, We'll attach maven-antrun-plugin:run goal to the pre-clean, clean, and post-clean phases.
This will allow us to echo text messages displaying the phases of the clean lifecycle.

We've created a pom.xml in C:\MVN\project folder.

<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>com.companyname.projectgroup</groupId>
<artifactId>project</artifactId>
<version>1.0</version>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-antrun-plugin</artifactId>
<version>1.1</version>
<executions>
<execution>
<id>id.pre-clean</id>
<phase>pre-clean</phase>
<goals>
<goal>run</goal>
</goals>
<configuration>
<tasks>
<echo>pre-clean phase</echo>
</tasks>
</configuration>
</execution>
<execution>
<id>id.clean</id>
<phase>clean</phase>
<goals>
<goal>run</goal>
</goals>
<configuration>
<tasks>
<echo>clean phase</echo>
</tasks>
</configuration>
</execution>
<execution>
<id>id.post-clean</id>
<phase>post-clean</phase>
<goals>
<goal>run</goal>
</goals>
<configuration>
<tasks>
<echo>post-clean phase</echo>
</tasks>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
Now open command console, go to the folder containing pom.xml and execute the following mvncommand.
C:\MVN\project>mvn post-clean

Maven will start processing and display all the phases of clean life cycle

[INFO] Scanning for projects...


[INFO] ------------------------------------------------------------------
[INFO] Building Unnamed - com.companyname.projectgroup:project:jar:1.0
[INFO] task-segment: [post-clean]
[INFO] ------------------------------------------------------------------
[INFO] [antrun:run {execution: id.pre-clean}]
[INFO] Executing tasks
[echo] pre-clean phase
[INFO] Executed tasks
[INFO] [clean:clean {execution: default-clean}]
[INFO] [antrun:run {execution: id.clean}]
[INFO] Executing tasks
[echo] clean phase
[INFO] Executed tasks
[INFO] [antrun:run {execution: id.post-clean}]
[INFO] Executing tasks
[echo] post-clean phase
[INFO] Executed tasks
[INFO] ------------------------------------------------------------------
[INFO] BUILD SUCCESSFUL
[INFO] ------------------------------------------------------------------
[INFO] Total time: < 1 second
[INFO] Finished at: Sat Jul 07 13:38:59 IST 2012
[INFO] Final Memory: 4M/44M
[INFO] ------------------------------------------------------------------
You can try tuning mvn clean command which will display pre-clean and clean, nothing will be executed for post-
clean phase.

Default (or Build) Lifecycle


This is the primary life cycle of Maven and is used to build the application. It has following 23 phases.

Lifecycle Phase Description

Validates whether project is correct and all necessary information is


validate
available to complete the build process.

initialize Initializes build state, for example set properties

generate-sources Generate any source code to be included in compilation phase.

process-sources Process the source code, for example, filter any value.
generate-resources Generate resources to be included in the package.

Copy and process the resources into the destination directory, ready for
process-resources
packaging phase.

compile Compile the source code of the project.

Post-process the generated files from compilation, for example to do


process-classes
bytecode enhancement/optimization on Java classes.

generate-test-sources Generate any test source code to be included in compilation phase.

process-test-sources Process the test source code, for example, filter any values.

test-compile Compile the test source code into the test destination directory.

process-test-classes Process the generated files from test code file compilation.

test Run tests using a suitable unit testing framework(Junit is one).

Perform any operations necessary to prepare a package before the actual


prepare-package
packaging.

Take the compiled code and package it in its distributable format, such as
package
a JAR, WAR, or EAR file.

Perform actions required before integration tests are executed. For


pre-integration-test
example, setting up the required environment.

Process and deploy the package if necessary into an environment where


integration-test
integration tests can be run.

Perform actions required after integration tests have been executed. For
post-integration-test
example, cleaning up the environment.

Run any check-ups to verify the package is valid and meets quality
verify
criterias.

Install the package into the local repository, which can be used as a
install
dependency in other projects locally.

Copies the final package to the remote repository for sharing with other
deploy
developers and projects.

There are few important concepts related to Maven Lifecycles which are wroth to mention:

• When a phase is called via Maven command, for example mvn compile, only phases upto and including that phase
will execute.

• Different maven goals will be bound to different phases of Maven lifecycle depending upon the type of packaging
(JAR / WAR / EAR).

In the following example, We'll attach maven-antrun-plugin:run goal to few of the phases of Build lifecycle. This will
allow us to echo text messages displaying the phases of the lifecycle.

We've updated pom.xml in C:\MVN\project folder.

<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>com.companyname.projectgroup</groupId>
<artifactId>project</artifactId>
<version>1.0</version>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-antrun-plugin</artifactId>
<version>1.1</version>
<executions>
<execution>
<id>id.validate</id>
<phase>validate</phase>
<goals>
<goal>run</goal>
</goals>
<configuration>
<tasks>
<echo>validate phase</echo>
</tasks>
</configuration>
</execution>
<execution>
<id>id.compile</id>
<phase>compile</phase>
<goals>
<goal>run</goal>
</goals>
<configuration>
<tasks>
<echo>compile phase</echo>
</tasks>
</configuration>
</execution>
<execution>
<id>id.test</id>
<phase>test</phase>
<goals>
<goal>run</goal>
</goals>
<configuration>
<tasks>
<echo>test phase</echo>
</tasks>
</configuration>
</execution>
<execution>
<id>id.package</id>
<phase>package</phase>
<goals>
<goal>run</goal>
</goals>
<configuration>
<tasks>
<echo>package phase</echo>
</tasks>
</configuration>
</execution>
<execution>
<id>id.deploy</id>
<phase>deploy</phase>
<goals>
<goal>run</goal>
</goals>
<configuration>
<tasks>
<echo>deploy phase</echo>
</tasks>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
Now open command console, go the folder containing pom.xml and execute the following mvncommand.
C:\MVN\project>mvn compile

Maven will start processing and display phases of build life cycle upto compile phase.

[INFO] Scanning for projects...


[INFO] ------------------------------------------------------------------
[INFO] Building Unnamed - com.companyname.projectgroup:project:jar:1.0
[INFO] task-segment: [compile]
[INFO] ------------------------------------------------------------------
[INFO] [antrun:run {execution: id.validate}]
[INFO] Executing tasks
[echo] validate phase
[INFO] Executed tasks
[INFO] [resources:resources {execution: default-resources}]
[WARNING] Using platform encoding (Cp1252 actually) to copy filtered resources,
i.e. build is platform dependent!
[INFO] skip non existing resourceDirectory C:\MVN\project\src\main\resources
[INFO] [compiler:compile {execution: default-compile}]
[INFO] Nothing to compile - all classes are up to date
[INFO] [antrun:run {execution: id.compile}]
[INFO] Executing tasks
[echo] compile phase
[INFO] Executed tasks
[INFO] ------------------------------------------------------------------
[INFO] BUILD SUCCESSFUL
[INFO] ------------------------------------------------------------------
[INFO] Total time: 2 seconds
[INFO] Finished at: Sat Jul 07 20:18:25 IST 2012
[INFO] Final Memory: 7M/64M
[INFO] ------------------------------------------------------------------

Site Lifecycle
Maven Site plugin is generally used to create fresh documentation to create reports, deploy site etc.

Phases

• pre-site

• site

• post-site

• site-deploy
In the following example, We'll attach maven-antrun-plugin:run goal to all the phases of Site lifecycle. This will allow
us to echo text messages displaying the phases of the lifecycle.

We've updated pom.xml in C:\MVN\project folder.

<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>com.companyname.projectgroup</groupId>
<artifactId>project</artifactId>
<version>1.0</version>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-antrun-plugin</artifactId>
<version>1.1</version>
<executions>
<execution>
<id>id.pre-site</id>
<phase>pre-site</phase>
<goals>
<goal>run</goal>
</goals>
<configuration>
<tasks>
<echo>pre-site phase</echo>
</tasks>
</configuration>
</execution>
<execution>
<id>id.site</id>
<phase>site</phase>
<goals>
<goal>run</goal>
</goals>
<configuration>
<tasks>
<echo>site phase</echo>
</tasks>
</configuration>
</execution>
<execution>
<id>id.post-site</id>
<phase>post-site</phase>
<goals>
<goal>run</goal>
</goals>
<configuration>
<tasks>
<echo>post-site phase</echo>
</tasks>
</configuration>
</execution>
<execution>
<id>id.site-deploy</id>
<phase>site-deploy</phase>
<goals>
<goal>run</goal>
</goals>
<configuration>
<tasks>
<echo>site-deploy phase</echo>
</tasks>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
Now open command console, go the folder containing pom.xml and execute the following mvncommand.
C:\MVN\project>mvn site

Maven will start processing and display phases of site life cycle upto site phase.

[INFO] Scanning for projects...


[INFO] ------------------------------------------------------------------
[INFO] Building Unnamed - com.companyname.projectgroup:project:jar:1.0
[INFO] task-segment: [site]
[INFO] ------------------------------------------------------------------
[INFO] [antrun:run {execution: id.pre-site}]
[INFO] Executing tasks
[echo] pre-site phase
[INFO] Executed tasks
[INFO] [site:site {execution: default-site}]
[INFO] Generating "About" report.
[INFO] Generating "Issue Tracking" report.
[INFO] Generating "Project Team" report.
[INFO] Generating "Dependencies" report.
[INFO] Generating "Project Plugins" report.
[INFO] Generating "Continuous Integration" report.
[INFO] Generating "Source Repository" report.
[INFO] Generating "Project License" report.
[INFO] Generating "Mailing Lists" report.
[INFO] Generating "Plugin Management" report.
[INFO] Generating "Project Summary" report.
[INFO] [antrun:run {execution: id.site}]
[INFO] Executing tasks
[echo] site phase
[INFO] Executed tasks
[INFO] ------------------------------------------------------------------
[INFO] BUILD SUCCESSFUL
[INFO] ------------------------------------------------------------------
[INFO] Total time: 3 seconds
[INFO] Finished at: Sat Jul 07 15:25:10 IST 2012
[INFO] Final Memory: 24M/149M
[INFO] ------------------------------------------------------------------

What is a Maven Repository?


In Maven terminology, a repository is a place i.e. directory where all the project jars, library jar, plugins or any other
project specific artifacts are stored and can be used by Maven easily.

Maven repository are of three types

• local
• central

• remote

Local Repository
Maven local repository is a folder location on your machine. It gets created when you run any maven command for
the first time.

Maven local repository keeps your project's all dependencies (library jars, plugin jars etc). When you run a Maven
build, then Maven automatically downloads all the dependency jars into the local repository.It helps to avoid
references to dependencies stored on remote machine every time a project is build.

Maven local repository by default get created by Maven in %USER_HOME% directory. To override the default
location, mention another path in Maven settings.xml file available at %M2_HOME%\conf directory.

<settings xmlns="http://maven.apache.org/SETTINGS/1.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0
http://maven.apache.org/xsd/settings-1.0.0.xsd">
<localRepository>C:/MyLocalRepository</localRepository>
</settings>

When you run Maven command, Maven will download dependencies to your custom path.

Central Repository
Maven central repository is repository provided by Maven community. It contains a large number of commonly used
libraries.

When Maven does not find any dependency in local repository, it starts searching in central repository using following
URL: http://repo1.maven.org/maven2/

Key concepts of Central repository

• This repository is managed by Maven community.

• It is not required to be configured.

• It requires internet access to be searched.

To browse the content of central maven repository, maven community has provided a
URL:http://search.maven.org/#browse. Using this library, a developer can search all the available libraries in central
repository.

Remote Repository
Sometime, Maven does not find a mentioned dependency in central repository as well then it stopped build process
and output error message to console. To prevent such situation, Maven provides concept of Remote
Repository which is developer's own custom repository containing required libraries or other project jars.

For example, using below mentioned POM.xml,Maven will download dependency (not available in central repository)
from Remote Repositories mentioned in the same pom.xml.

<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>com.companyname.projectgroup</groupId>
<artifactId>project</artifactId>
<version>1.0</version>
<dependencies>
<dependency>
<groupId>com.companyname.common-lib</groupId>
<artifactId>common-lib</artifactId>
<version>1.0.0</version>
</dependency>
<dependencies>
<repositories>
<repository>
<id>companyname.lib1</id>
<url>http://download.companyname.org/maven2/lib1</url>
</repository>
<repository>
<id>companyname.lib2</id>
<url>http://download.companyname.org/maven2/lib2</url>
</repository>
</repositories>
</project>

Maven Dependency Search Sequence


When we execute Maven build commands, Maven starts looking for dependency libraries in the following sequence:

• Step 1 - Search dependency in local repository, if not found, move to step 2 else if found then do the further
processing.
• Step 2 - Search dependency in central repository, if not found and remote repository/repositories is/are mentioned
then move to step 4 else if found, then it is downloaded to local repository for future reference.
• Step 3 - If a remote repository has not been mentioned, Maven simply stops the processing and throws error (Unable
to find dependency).
• Step 4 - Search dependency in remote repository or repositories, if found then it is downloaded to local repository for
future reference otherwise Maven as expected stop processing and throws error (Unable to find dependency).

Creating Java Project using Maven

Maven uses archetype plugins to create projects. To create a simple java application, we'll use maven-
archetype-quickstart plugin. In example below, We'll create a maven based java application project in
C:\MVN folder.
Let's open command console, go the C:\MVN directory and execute the following mvn command.
C:\MVN>mvn archetype:generate
-DgroupId=com.companyname.bank
-DartifactId=consumerBanking
-DarchetypeArtifactId=maven-archetype-quickstart
-DinteractiveMode=false

Maven will start processing and will create the complete java application project structure.

INFO] Scanning for projects...


[INFO] Searching repository for plugin with prefix: 'archetype'.
[INFO] -------------------------------------------------------------------
[INFO] Building Maven Default Project
[INFO] task-segment: [archetype:generate] (aggregator-style)
[INFO] -------------------------------------------------------------------
[INFO] Preparing archetype:generate
[INFO] No goals needed for project - skipping
[INFO] [archetype:generate {execution: default-cli}]
[INFO] Generating project in Batch mode
[INFO] -------------------------------------------------------------------
[INFO] Using following parameters for creating project
from Old (1.x) Archetype: maven-archetype-quickstart:1.0
[INFO] -------------------------------------------------------------------
[INFO] Parameter: groupId, Value: com.companyname.bank
[INFO] Parameter: packageName, Value: com.companyname.bank
[INFO] Parameter: package, Value: com.companyname.bank
[INFO] Parameter: artifactId, Value: consumerBanking
[INFO] Parameter: basedir, Value: C:\MVN
[INFO] Parameter: version, Value: 1.0-SNAPSHOT
[INFO] project created from Old (1.x) Archetype in dir:
C:\MVN\consumerBanking
[INFO] ------------------------------------------------------------------
[INFO] BUILD SUCCESSFUL
[INFO] ------------------------------------------------------------------
[INFO] Total time: 14 seconds
[INFO] Finished at: Tue Jul 10 15:38:58 IST 2012
[INFO] Final Memory: 21M/124M
[INFO] ------------------------------------------------------------------

Now go to C:/MVN directory. You'll see a java application project created named consumerBanking (as
specified in artifactId). Maven uses a standard directory layout as shown below:

Using above example, we can understand following key concepts


Folder Structure Description

consumerBanking contains src folder and pom.xml

src/main/java contains java code files under the package structure (com/companyName/bank).

contains test java code files under the package structure


src/main/test
(com/companyName/bank).

it contains images/properties files (In above example, we need to create this


src/main/resources
structure manually).

If you see, Maven also created a sample Java Source file and Java Test file. Open
C:\MVN\consumerBanking\src\main\java\com\companyname\bank folder, you will see App.java.

package com.companyname.bank;

/**
* Hello world!
*
*/
public class App
{
public static void main( String[] args )
{
System.out.println( "Hello World!" );
}
}

Open C:\MVN\consumerBanking\src\test\java\com\companyname\bank folder, you will see AppTest.java.

package com.companyname.bank;

import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;

/**
* Unit test for simple App.
*/
public class AppTest extends TestCase
{
/**
* Create the test case
*
* @param testName name of the test case
*/
public AppTest( String testName )
{
super( testName );
}

/**
* @return the suite of tests being tested
*/
public static Test suite()
{
return new TestSuite( AppTest.class );
}

/**
* Rigourous Test :-)
*/
public void testApp()
{
assertTrue( true );
}
}

Developers are required to place their files as mentioned in table above and Maven handles the all the
build related complexities.

In next section, we'll discuss how to build and test the project using maven Maven Build & Test Project.

What we learnt in Project Creation chapter is how to create a Java application using Maven. Now we'll
see how to build and test the application.

Go to C:/MVN directory where you've created your java application. Open consumerBanking folder.You
will see the POM.xml file with following contents.
<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>com.companyname.projectgroup</groupId>
<artifactId>project</artifactId>
<version>1.0</version>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
</dependency>
</dependencies>
</project>
Here you can see, Maven already added Junit as test framework. By default Maven adds a source
fileApp.java and a test file AppTest.java in its default directory structure discussed in previous chapter.
Let's open command console, go the C:\MVN\consumerBanking directory and execute the
followingmvn command.
C:\MVN\consumerBanking>mvn clean package

Maven will start building the project.

[INFO] Scanning for projects...


[INFO] -------------------------------------------------------------------
[INFO] Building consumerBanking
[INFO] task-segment: [clean, package]
[INFO] -------------------------------------------------------------------
[INFO] [clean:clean {execution: default-clean}]
[INFO] Deleting directory C:\MVN\consumerBanking\target
[INFO] [resources:resources {execution: default-resources}]
[WARNING] Using platform encoding (Cp1252 actually) to copy filtered
resources,
i.e. build is platform dependent!
[INFO] skip non existing resourceDirectory C:\MVN\consumerBanking\src\main\
resources
[INFO] [compiler:compile {execution: default-compile}]
[INFO] Compiling 1 source file to C:\MVN\consumerBanking\target\classes
[INFO] [resources:testResources {execution: default-testResources}]
[WARNING] Using platform encoding (Cp1252 actually) to copy filtered
resources,
i.e. build is platform dependent!
[INFO] skip non existing resourceDirectory C:\MVN\consumerBanking\src\test\
resources
[INFO] [compiler:testCompile {execution: default-testCompile}]
[INFO] Compiling 1 source file to C:\MVN\consumerBanking\target\test-classes
[INFO] [surefire:test {execution: default-test}]
[INFO] Surefire report directory: C:\MVN\consumerBanking\target\
surefire-reports
-------------------------------------------------------
T E S T S
-------------------------------------------------------
Running com.companyname.bank.AppTest
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.027 sec

Results :

Tests run: 1, Failures: 0, Errors: 0, Skipped: 0

[INFO] [jar:jar {execution: default-jar}]


[INFO] Building jar: C:\MVN\consumerBanking\target\
consumerBanking-1.0-SNAPSHOT.jar
[INFO] ----------------------------------------------------------------------
--
[INFO] BUILD SUCCESSFUL
[INFO] ----------------------------------------------------------------------
--
[INFO] Total time: 2 seconds
[INFO] Finished at: Tue Jul 10 16:52:18 IST 2012
[INFO] Final Memory: 16M/89M
[INFO] ----------------------------------------------------------------------
--

You've built your project and created final jar file, following are the key learning concepts

• We give maven two goals, first to clean the target directory (clean) and then package the project build
output as jar(package).

• Packaged jar is available in consumerBanking\target folder as consumerBanking-1.0-SNAPSHOT.jar.

• Test reports are available in consumerBanking\target\surefire-reports folder.

• Maven compiled source code file(s) and then test source code file(s).
• Then Maven run the test cases.

• Finally Maven created the package.

Now open command console, go the C:\MVN\consumerBanking\target\classes directory and execute the
following java command.

C:\MVN\consumerBanking\target\classes>java com.companyname.bank.App

You will see the result

Hello World!

Adding Java Source Files


Let's see how we can add additional Java files in our project. Open
C:\MVN\consumerBanking\src\main\java\com\companyname\bank folder, create Util class in it as
Util.java.

package com.companyname.bank;

public class Util


{
public static void printMessage(String message){
System.out.println(message);
}
}

Update App class to use Util class.

package com.companyname.bank;

/**
* Hello world!
*
*/
public class App
{
public static void main( String[] args )
{
Util.printMessage("Hello World!");
}
}
Now open command console, go the C:\MVN\consumerBanking directory and execute the
followingmvn command.
C:\MVN\consumerBanking>mvn clean compile

After Maven build is successful, go the C:\MVN\consumerBanking\target\classes directory and execute


the following java command.

C:\MVN\consumerBanking\target\classes>java -cp com.companyname.bank.App


You will see the result

Hello World!

Maven External Dependencies

Now as you know Maven does the dependency management using concept of Maven Repositories. But what
happens if dependency is not available in any of remote repositories and central repository? Maven provides answer
for such scenario using concept of External Dependency.
For an example, let us do the following changes to project created in Maven Creating Project section.
• Add lib folder to src folder
• Copy any jar into the lib folder. We've used ldapjdk.jar, which is a helper library for LDAP operations.

Now our project structure should look like following:

Here you are having your own library specific to project, which is very usual case and it can contain jars which may
not be available in any repository for maven to download from. If your code is using this library with Maven then
Maven build will fail because it cannot download or refer to this library during compilation phase.

To handle the situation, let's add this external dependency to maven pom.xml using following way.
<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/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.companyname.bank</groupId>
<artifactId>consumerBanking</artifactId>
<packaging>jar</packaging>
<version>1.0-SNAPSHOT</version>
<name>consumerBanking</name>
<url>http://maven.apache.org</url>

<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>ldapjdk</groupId>
<artifactId>ldapjdk</artifactId>
<scope>system</scope>
<version>1.0</version>
<systemPath>${basedir}\src\lib\ldapjdk.jar</systemPath>
</dependency>
</dependencies>

</project>
Look at the second dependency element under dependencies in above example which clears following key concepts
about External Dependency.

• External dependencies (library jar location) can be configured in pom.xml in same way as other dependencies.

• Specify groupId same as name of the library.

• Specify artifactId same as name of the library.

• Specify scope as system.

• Specify system path relative to project location.

Hope now you are clear about external dependencies and you will be able to specify external dependencies in your
Maven project.

Maven Project Documents


 

This tutorial will teach you how to create documentation of the application in one go. So let's start, go to
C:/MVN directory where you had created your java consumerBanking application.
OpenconsumerBanking folder and execute the following mvn command.
C:\MVN>mvn site

Maven will start building the project.

[INFO] Scanning for projects...


[INFO] -------------------------------------------------------------------
[INFO] Building consumerBanking
[INFO] task-segment: [site]
[INFO] -------------------------------------------------------------------
[INFO] [site:site {execution: default-site}]
[INFO] artifact org.apache.maven.skins:maven-default-skin:
checking for updates from central
[INFO] Generating "About" report.
[INFO] Generating "Issue Tracking" report.
[INFO] Generating "Project Team" report.
[INFO] Generating "Dependencies" report.
[INFO] Generating "Continuous Integration" report.
[INFO] Generating "Source Repository" report.
[INFO] Generating "Project License" report.
[INFO] Generating "Mailing Lists" report.
[INFO] Generating "Plugin Management" report.
[INFO] Generating "Project Summary" report.
[INFO] -------------------------------------------------------------------
[INFO] BUILD SUCCESSFUL
[INFO] -------------------------------------------------------------------
[INFO] Total time: 16 seconds
[INFO] Finished at: Wed Jul 11 18:11:18 IST 2012
[INFO] Final Memory: 23M/148M
[INFO] -------------------------------------------------------------------

That's it. Your project documentation is ready. Maven has created a site within target directory.

Open C:\MVN\consumerBanking\target\site folder. Click on index.html to see the documentation.


Maven creates the documentation using a documentation-processing engine called Doxia which reads
multiple source formats into a common document model.To write documentation for your project, you can
write your content in a following few commonly used formats which are parsed by Doxia.
Format Name Description Reference

A Plain Text document


APT http://maven.apache.org/doxia/format.html
format

A Maven 1.x documentation


XDoc http://jakarta.apache.org/site/jakarta-site2.html
format

http://maven.apache.org/doxia/references/fml-
FML Used for FAQ documents
format.html

XHTML Extensible HTML http://en.wikipedia.org/wiki/XHTML


 

Maven Project Templates


 

Maven provides users,a very large list of different types of project templates (614 in numbers) using
concept of Archetype. Maven helps users to quickly start a new java project using following command
mvn archetype:generate
What is Archetype?
Archetype is a Maven plugin whose task is to create a project structure as per its template. We are going
to use quickstart archetype plugin to create a simple java application here.

Using Project Template


Let's open command console, go the C:\ > MVN directory and execute the following mvn command
C:\MVN>mvn archetype:generate

Maven will start processing and will ask to choose required archetype

INFO] Scanning for projects...


[INFO] Searching repository for plugin with prefix: 'archetype'.
[INFO] -------------------------------------------------------------------
[INFO] Building Maven Default Project
[INFO] task-segment: [archetype:generate] (aggregator-style)
[INFO] -------------------------------------------------------------------
[INFO] Preparing archetype:generate
...
600: remote -> org.trailsframework:trails-archetype (-)
601: remote -> org.trailsframework:trails-secure-archetype (-)
602: remote -> org.tynamo:tynamo-archetype (-)
603: remote -> org.wicketstuff.scala:wicket-scala-archetype (-)
604: remote -> org.wicketstuff.scala:wicketstuff-scala-archetype
Basic setup for a project that combines Scala and Wicket,
depending on the Wicket-Scala project.
Includes an example Specs test.)
605: remote -> org.wikbook:wikbook.archetype (-)
606: remote -> org.xaloon.archetype:xaloon-archetype-wicket-jpa-glassfish (-)
607: remote -> org.xaloon.archetype:xaloon-archetype-wicket-jpa-spring (-)
608: remote -> org.xwiki.commons:xwiki-commons-component-archetype
(Make it easy to create a maven project for creating XWiki Components.)
609: remote -> org.xwiki.rendering:xwiki-rendering-archetype-macro
(Make it easy to create a maven project for creating XWiki Rendering Macros.)
610: remote -> org.zkoss:zk-archetype-component (The ZK Component archetype)
611: remote -> org.zkoss:zk-archetype-webapp (The ZK wepapp archetype)
612: remote -> ru.circumflex:circumflex-archetype (-)
613: remote -> se.vgregion.javg.maven.archetypes:javg-minimal-archetype (-)
614: remote -> sk.seges.sesam:sesam-annotation-archetype (-)
Choose a number or apply filter
(format: [groupId:]artifactId, case sensitive contains): 203:

Press Enter to choose to default option(203: maven-archetype-quickstart)

Maven will ask for particular version of archetype

Choose org.apache.maven.archetypes:maven-archetype-quickstart version:


1: 1.0-alpha-1
2: 1.0-alpha-2
3: 1.0-alpha-3
4: 1.0-alpha-4
5: 1.0
6: 1.1
Choose a number: 6:
Press Enter to choose to default option(6: maven-archetype-quickstart:1.1)

Maven will ask for project detail. Enter project detail as asked.Press Enter if default value is provided. You
can override them by entering your own value.

Define value for property 'groupId': : com.companyname.insurance


Define value for property 'artifactId': : health
Define value for property 'version': 1.0-SNAPSHOT:
Define value for property 'package': com.companyname.insurance:

Maven will ask for project detail confirmation. Press enter or press Y

Confirm properties configuration:


groupId: com.companyname.insurance
artifactId: health
version: 1.0-SNAPSHOT
package: com.companyname.insurance
Y:

Now Maven will start creating project structure and will display the following:

[INFO] ----------------------------------------------------------------------
-
[INFO] Using following parameters for creating project
from Old (1.x) Archetype: maven-archetype-quickstart:1.1
[INFO] ----------------------------------------------------------------------
-
[INFO] Parameter: groupId, Value: com.companyname.insurance
[INFO] Parameter: packageName, Value: com.companyname.insurance
[INFO] Parameter: package, Value: com.companyname.insurance
[INFO] Parameter: artifactId, Value: health
[INFO] Parameter: basedir, Value: C:\MVN
[INFO] Parameter: version, Value: 1.0-SNAPSHOT
[INFO] project created from Old (1.x) Archetype in dir: C:\MVN\health
[INFO] ----------------------------------------------------------------------
-
[INFO] BUILD SUCCESSFUL
[INFO] ----------------------------------------------------------------------
-
[INFO] Total time: 4 minutes 12 seconds
[INFO] Finished at: Fri Jul 13 11:10:12 IST 2012
[INFO] Final Memory: 20M/90M
[INFO] ----------------------------------------------------------------------
-

Created Project
Now go to C:\ > MVN directory. You'll see a java application project created named health which was
given as artifactId at the time of project creation. Maven will create a standard directory layout for the
project as shown below:
Created POM.xml
Maven generates a POM.xml file for the project as listed below:

<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>com.companyname.insurance</groupId>
<artifactId>health</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<name>health</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>

Created App.java
Maven generates sample java source file, App.java for the project as listed below:

Location: C:\ > MVN > health > src > main > java > com > companyname > insurance > App.java
package com.companyname.insurance;

/**
* Hello world!
*
*/
public class App
{
public static void main( String[] args )
{
System.out.println( "Hello World!" );
}
}

Created AppTest.java
Maven generates sample java source test file, AppTest.java for the project as listed below:

Location: C:\ > MVN > health > src > test > java > com > companyname > insurance > AppTest.java
package com.companyname.insurance;

import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;

/**
* Unit test for simple App.
*/
public class AppTest
extends TestCase
{
/**
* Create the test case
*
* @param testName name of the test case
*/
public AppTest( String testName )
{
super( testName );
}

/**
* @return the suite of tests being tested
*/
public static Test suite()
{
return new TestSuite( AppTest.class );
}

/**
* Rigourous Test :-)
*/
public void testApp()
{
assertTrue( true );
}
}

That's it. Now you can see the power of Maven. You can create any kind of project using single command
in maven and can kick-start your development.

Maven Eclispe IDE Integration


 

Eclipse provides an excellent plugin m2eclipse which seamlessly integrates Maven and Eclipse together.

Some of features of m2eclipse are listed below

• You can run Maven goals from Eclipse.

• You can view the output of Maven commands inside the Eclipse using its own console.

• You can update maven dependencies with IDE.

• You can Launch Maven builds from within Eclipse.

• It does the dependency management for Eclipse build path based on Maven's pom.xml.

• It resolves Maven dependencies from the Eclipse workspace without installing to local Maven repository
(requires dependency project be in same workspace).

• It automatic downloads required dependencies and sources from the remote Maven repositories.

• It provides wizards for creating new Maven projects, pom.xml and to enable Maven support on existing
projects

• It provides quick search for dependencies in remote Maven repositories

Installing m2eclipse plugin


Use one of the following links to install m2eclipse:

Eclipse URL

Eclipse 3.5 (Gallileo) Installing m2eclipse in Eclipse 3.5 (Gallileo)

Eclipse 3.6 (Helios) Installing m2eclipse in Eclipse 3.6 (Helios)

Following example will help you to leverage benefits of integrating Eclipse and maven.

Import a maven project in Eclipse


• Open Eclipse.
• Select File > Import > option.

• Select Maven Projects Option. Click on Next Button.

• Select Project location, where a project was created using Maven. We've create a Java Project
consumerBanking.See Maven Creating Project to see how to create a project using Maven.

• Click Finish Button.


Now, you can see the maven project in eclipse.
Now, have a look at consumerBanking project properties.You can see that Eclipse has added Maven
dependencies to java build path.
Now, Its time to build this project using maven capability of eclipse.

• Right Click on consumerBanking project to open context menu.

• Select Run as option

• Then maven package option

Maven will start building the project. You can see the output in Eclipse Console

[INFO] Scanning for projects...


[INFO] -------------------------------------------------------------------
[INFO] Building consumerBanking
[INFO]
[INFO] Id: com.companyname.bank:consumerBanking:jar:1.0-SNAPSHOT
[INFO] task-segment: [package]
[INFO] -------------------------------------------------------------------
[INFO] [resources:resources]
[INFO] Using default encoding to copy filtered resources.
[INFO] [compiler:compile]
[INFO] Nothing to compile - all classes are up to date
[INFO] [resources:testResources]
[INFO] Using default encoding to copy filtered resources.
[INFO] [compiler:testCompile]
[INFO] Nothing to compile - all classes are up to date
[INFO] [surefire:test]
[INFO] Surefire report directory:
C:\MVN\consumerBanking\target\surefire-reports

-------------------------------------------------------
T E S T S
-------------------------------------------------------
Running com.companyname.bank.AppTest
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.047 sec

Results :

Tests run: 1, Failures: 0, Errors: 0, Skipped: 0

[INFO] [jar:jar]
[INFO] -------------------------------------------------------------------
[INFO] BUILD SUCCESSFUL
[INFO] -------------------------------------------------------------------
[INFO] Total time: 1 second
[INFO] Finished at: Thu Jul 12 18:18:24 IST 2012
[INFO] Final Memory: 2M/15M
[INFO] -------------------------------------------------------------------
Now, right click on App.java. Select Run As option. Select As Java Application.

You will see the result

Hello World!
 

You might also like