Selenium Java PDF
Selenium Java PDF
Selenium Java PDF
1.Framework
2.JAVA
5.Selenium RC
7.Web Driver.
Framework
General Data Driven Framework &
TestNG WebDriver Data Driven
Framework Aim or Goals of Framework:
¾ Generate Logs
________________________________________________________________________
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
in base create initialize function and declare global variables like xls files
with path.
________________________________________________________________________
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
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.
________________________________________________________________________
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
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.
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.
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.
________________________________________________________________________
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.
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.
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.
________________________________________________________________________
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.
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.
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.
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:
________________________________________________________________________
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.
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.
________________________________________________________________________
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.
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.
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.
&& 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
________________________________________________________________________
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
&& And
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;
}
}
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.
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.
________________________________________________________________________
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;
}
9. Cheat Sheets
The following can be used as a reference for certain task which you have to do.
Table 3.
What to do How to do it
package test;
}
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 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;
}
}
package test;
________________________________________________________________________
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() {
}
package test;
public MyNewClass(String
para1) {
var1 = para1;
// or this.var1= para1;
}
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;
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
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
________________________________________________________________________
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:
1
2
3
4
5
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:
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.
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 an Iterator?
________________________________________________________________________
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.
TOP
________________________________________________________________________
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.
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).
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?
________________________________________________________________________
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 do not provide the String array as the argument to the 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.
________________________________________________________________________
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.
A: No the program fails to compile. The compiler says that the main method is already
defined in the class.
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.
________________________________________________________________________
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.
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.
________________________________________________________________________
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.
• Abstraction
• Polymorphism
• Inheritance
• Encapsulation
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.
________________________________________________________________________
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?
________________________________________________________________________
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).
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
________________________________________________________________________
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.
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:
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?
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.
NO, because main is a static method. A static method can't be overridden in Java.
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:
________________________________________________________________________
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?
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.
No, constructor cannot be inherited, though a derived class can call the base class
constructor.
Constructors Methods
________________________________________________________________________
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
• 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 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.
• 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.
________________________________________________________________________
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..
• 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.
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?
________________________________________________________________________
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.
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.
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.
________________________________________________________________________
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.
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.
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:
________________________________________________________________________
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
¾ Hard coding
¾ While integrating the modules
¾ Lack of documentation
¾ Miscommunication
¾ Time pressure
¾ Dynamically changing requirements
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.
________________________________________________________________________
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.
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.
________________________________________________________________________
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.
________________________________________________________________________
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.
________________________________________________________________________
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.
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.
Step: Allows one to “step” through a test case by running it one command at a
time. Use for debugging test cases.
________________________________________________________________________
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 –>.
Source View
Since Source view provides the equivalent of a WYSIWYG editor, simply modify which
line you wish– command, parameter, or comment.
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.
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
¾ database testing
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.
5.1 RC Components
¾ 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.
________________________________________________________________________
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.
________________________________________________________________________
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.
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:
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.
________________________________________________________________________
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.
________________________________________________________________________
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.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.
}
}
________________________________________________________________________
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");
}
}
}
________________________________________________________________________
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?
1. Annotation Support
The annotation supports are implemented in both JUnit 4 and TestNG look similar.
________________________________________________________________________
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
@Test(expected = @Test(expectedExceptions =
expected exception
ArithmeticException.class) ArithmeticException.class)
________________________________________________________________________
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.
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
________________________________________________________________________
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.
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.
________________________________________________________________________
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 {
@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
Unit Test
________________________________________________________________________
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
<classes>
<class name="com.framework.TestCase_A1" />
</classes>
</test>
</suite>
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.
________________________________________________________________________
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;
}
@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());
}
________________________________________________________________________
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);
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
@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");
}
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.
________________________________________________________________________
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.
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.
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.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”.
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);
element.clear();
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:
________________________________________________________________________
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.
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:
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
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:
________________________________________________________________________
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.
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*.
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:
// 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.
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.
________________________________________________________________________
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):
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
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.
________________________________________________________________________
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?
Hardcore programming.
¾ Finding locators/xpaths.
¾ 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.
________________________________________________________________________
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.
¾ Any reporting related capabilities, you need to depend on third party tools.
3. Advantages of Selenium?
¾ Once we prepare the code in the windows platform we can run in any
4. Disadvantages of Selenium?
¾ Selenium Can’t record the Desktop application
________________________________________________________________________
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
Selenium IDE
Selenium Core
Selenium 1 (known as. Selenium RC or Remote Control)
Selenium 2 (known as. Selenium Webdriver)
Selenium-Grid
As you know Selenium is a free ware open source testing tool. There are many
challenges with Selenium.
________________________________________________________________________
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
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
1. Selenium can record only on firefox and It can support or run only on firefox
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
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
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
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. 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?
________________________________________________________________________
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
________________________________________________________________________
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
1. .Net,
2. Java (Junt 3, Junt 4, TestNG, Groovy)
3. Perl,
4. Python,
5. PHP,
6. Ruby
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.
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.
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.
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.
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}
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
________________________________________________________________________
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
________________________________________________________________________
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.
________________________________________________________________________
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. 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
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?
________________________________________________________________________
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?
46. Which is the command used for running the Selenium RC Server?
You can run the selenium commands in RC slow motion by two ways:
selenium.setSpeed
thread.sleep
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.
________________________________________________________________________
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.
51. What are the challenges with Selenium RC test suites when
running in 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?
________________________________________________________________________
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. 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>
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;
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);
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();
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;
@Test
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);
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.Test;
@Test
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);
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;
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());
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.internal.seleniumemulation.GetText;
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();
________________________________________________________________________
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‐‐‐
________________________________________________________________________
QEdge TECHNOLOGIES: # 204, 2nd Floor, Nagasuri Plaza, Ameerpet, Hyderabad.
Email: [email protected], ph:040-64644491/92, 7702944491.
GRID
Introduction
Grid allows you to :
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.
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:
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
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.
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:
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(,);
-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.
-browser browserName=firefox,version=3.6,maxInstances=5,platform=LINUX
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.
• -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.
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.
{
"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
{
"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
}
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.
• 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.
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
resources ${basedir}/src/main/resources
Tests ${basedir}/src/test
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.
OS Output
OS Output
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
Linux /usr/local/apache-maven
Mac /usr/local/apache-maven
OS Output
OS Output
Windows Append the string ;%M2% to the end of the system variable, Path.
OS Output
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 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.
Now open command console, go the folder containing pom.xml and execute the following mvncommand.
C:\MVN\project>mvn help:effective-pom
[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.
<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 provides numerous archetype plugins to create projects which in order create the project structure
and pom.xml
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.
<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
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.
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.
Take the compiled code and package it in its distributable format, such as
package
a JAR, WAR, or EAR file.
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.
<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.
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.
<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.
• 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/
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>
• 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).
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.
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:
src/main/java contains java code files under the package structure (com/companyName/bank).
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!" );
}
}
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
Results :
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).
• Maven compiled source code file(s) and then test source code file(s).
• Then Maven run the test cases.
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
Hello World!
package com.companyname.bank;
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
Hello World!
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.
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.
Hope now you are clear about external dependencies and you will be able to specify external dependencies in your
Maven project.
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
That's it. Your project documentation is ready. Maven has created a site within target directory.
http://maven.apache.org/doxia/references/fml-
FML Used for FAQ documents
format.html
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.
Maven will start processing and will ask to choose required archetype
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.
Maven will ask for project detail confirmation. Press enter or press 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.
Eclipse provides an excellent plugin m2eclipse which seamlessly integrates Maven and Eclipse together.
• You can view the output of Maven commands inside the Eclipse using its own console.
• 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
Eclipse URL
Following example will help you to leverage benefits of integrating Eclipse and maven.
• 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.
Maven will start building the project. You can see the output in Eclipse Console
-------------------------------------------------------
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 :
[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.
Hello World!