Projeto de caixas acústicas utilizando alto-falantes Selenium.Descrição completa
SeleniumDeskripsi lengkap
Descrição: Descrição do falante
njh jhgjhgjgnjgnjgbhjgvhgb
Different Frameworks for Selenium automationFull description
Deskripsi lengkap
Selenium IT Testing Tool Tutorial for beginnersFull description
Selenium interview QuestionsFull description
Full description
selenium
Caixa Selenium SPM 1202AFull description
Descrição: SELENIUM CATÁLOGO PROFISIONAL 2013
ujknkjhkjFull description
seleniumFull description
SeleniumFull description
Descripción: dsdsdfsdf
selenium web driverFull description
Found on InternetFull description
CONTENTS 1.Framework a.General Data Driven Framework b. Testing Web Driver Data Driven Framework 2.JAVA 3.Sample Programs on Java 4.Interview Questions on Java 5.Selenium RC 6.TestNG and JUnit 7.Web Driver. 8.Sample Programs on Selenium 9.Interview Question on Selenium
Framework General Data Driven Framework & TestNG WebDriver Data Driven Framework Aim or Goals of Framework: ¾ Tests With Multiple Suite ¾ Run Selective Test Suite ¾ Run Selected Test Cases ¾ Generate Logs ¾ Repeat a test case – Parameterize ¾ Execute Test cases with multiple sets of data ¾ Run complete Project in Console or command line ¾ BAT file for execution through ANT ¾ Generate Html Reports using TestNG ¾ Generate XSLT Reports or Pie Graphs for Result
Prepare Test Cases and Test data xls for Test Suites. One xls file per test suite Introduce Runmodes Make eclipse Java project make package- suiteA make package- suiteB make package- suiteC make package- logs make package- util make package- base, in base create initialize function and declare global variables like xls files with path. make package- config, create OR.properties and config.properties make package- xls Put xls files in xls Prepare config.properties and OR.properties
Make TestUtil.java in util package Prepare function to check Runmode of a Test Suite - isSuiteRunnable ________________________________________________________________________
Prepare function to check Runmode of a Test Case in Test Suite isTestCaseRunnable Prepare function to return test data for a test case in two dim array getData Make TestBase.java Prepare initialize function to initialize the logs, Make TestSuiteBase.java class in each test Suite package Prepare all test classes in all suites Prepare testng.xml and individual suite xmls Batch run and check empty project Implement @BeforeSuite and @BeforeTest functions in Project to check Runmode of Suite and Test Batch run and check empty project Implement @dataprovider Functions in all test classes - PARAMETRIZING THE TEST CASES Implement build.xml and run project through command prompt Make a .bat file to run the frameworkDouble clicking on bat file your will or complete script will execute and generate the reports and logs.
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 ________________________________________________________________________
11. Questions and Discussion 12. Links and Literature
1. Introduction to Java 1.1. History Java is a programming language created by James Gosling from Sun Microsystems in 1991. The first publicly available version of Java (Java 1.0) was released in 1995. Over time new enhanced versions of Java have been released. The current version of Java is Java 1.7 which is also known as Java 7. From the Java programming language the Java platform evolved. The Java platform allows that the program code is written in other languages than the Java programming language and still runs on the Java virtual machine.
1.2. Java Virtual machine The Java virtual machine (JVM) is a software implementation of a computer that executes programs like a real machine. The Java virtual machine is written specifically for a specific operating system, e.g. for Linux a special implementation is required as well as for Windows. Java programs are compiled by the Java compiler into so-called bytecode. The Java virtual machine interprets this bytecode and executes the Java program.
1.3. Java Runtime Environment vs. Java Development Kit Java comes in two flavors, the Java Runtime Environment (JRE) and the Java Development Kit (JDK). The Java runtime environment (JRE) consists of the JVM and the Java class libraries and contains the necessary functionality to start Java programs. The JDK contains in addition the development tools necessary to create Java programs. The JDK consists therefore of a Java compiler, the Java virtual machine, and the Java class libraries.
1.4. Characteristics of Java The target of Java is to write a program once and then run this program on multiple operating systems. Java has the following properties: •
Platform independent: Java programs use the Java virtual machine as abstraction and do not access the operating system directly. This makes Java programs highly portable. A Java program which is standard complaint and follows certain rules can run unmodified on all supported platforms, e.g. Windows or Linux.
•
Object-orientated programming language: Except the primitive data types, all elements in Java are objects.
•
Strongly-typed programming language: Java is strongly-typed, e.g. the types of the used variables must be pre-defined and conversion to other objects is relatively strict, e.g. must be done in most cases by the programmer.
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 deallocation for creating new objects. The program does not have direct access to the memory. The so-called garbage collector deletes automatically objects to which no active pointer exists.
The Java syntax is similar to C++. Java is case sensitive, e.g. the variables myValue and myvalue will be treated as different variables.
1.5. Development Process with Java The programmer writes Java source code in a text editor which supports plain text. Normally the programmer uses an Integrated Development Environment (IDE) for programming. An IDE supports the programmer in the task of writing code, e.g. it provides auto-formating of the source code, highlighting of the important keywords, etc. At some point the programmer (or the IDE) calls the Java compiler (javac). The Java compiler creates the bytecode instructions. . These instructions are stored in .class files and can be executed by the Java Virtual Machine.
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.
3. Your first Java program 3.1. Write source code The following Java program is developed under Microsoft Windows. The process on other operating system should be similar but is not covered in this description.
Select a new directory which will contain your Java code. I will use the c:\temp\java which will be called javadir in the following description. Open a text editor which supports plain text, e.g. Notepad under Windows and write the following source code. You can start Notepad via Start → Run → Notepad and by pressing enter. // A small Java program public class HelloWorld { public static void main(String[] args) { System.out.println("Hello World"); } }
Save the source code in your javadir directory with the HelloWorld.java filename. The name of a Java source file must always equals the class name (within the source code) and end with the .java extension. In this example the filename must be HelloWorld.java because the class is called HelloWorld.
3.2. Compile and run your Java program
Switch to the command line, e.g. under Windows Start-> Run -> cmd. Switch to the javadir directory with the command cd javadir, for example in my case cd c:\temp\java. Use the command dir to see that the source file is in the directory. javac testjava.java Check the content of the directory with the command "dir". The directory contains now a file "testjava.class". If you see this file you have successfully compiled your first Java source code into bytecode. By default, the compiler puts each class file in the same directory as its source file. You can specify a separate destination directory with the -d compiler flag. ________________________________________________________________________
The system should write "learning selenium" on the command line.
3.3. Using the classpath You can use the classpath to run the program from another place in your directory. Switch to the command line, e.g. under Windows Start-> Run -> cmd. Switch to any directory you want. Type: java learning selenium
If you are not in the directory in which the compiled class is stored then the system should result an error message Exception in thread "main" java.lang.NoClassDefFoundError: test/TestClass To use the class type the following command. Replace "mydirectory" with the directory which contains the test directory. You should again see the " learning selenium " output. java -classpath "mydirectory" learning selenium
4. Integrated Development Environment The previous chapter explained how to create and compile a Java program on the command line. A Java Integrated Development Environment (IDE) provides lots of ease of use functionality for creating java programs. There are other very powerful IDE's available, for example the Eclipse IDE. . In the following I will say "Create a Java project SomeName". This will refer to creating an Eclipse Java project. If you are using a different IDE please follow the required steps in this IDE.
4.1. To Install Java: 1. Go to google and type “download JDK” 2. Now select your OS compatibility (32bit or 64bit) 3. Install in your system.
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 ________________________________________________________________________
5. Your first graphical user interface application (GUI) Introduction of Eclipse and eclipse GUI. Now open eclipse short cut from the desktop as above explained. It’ll displays like below screenshot.
c a new Javva proje ect : Using Eclipse create Step 1: 1. Go to o file menu ÆNewÆsselect Java a Project _______ __________ __________ _________ __________ __________ __________ __________ ____
Step 6: 1. Type e class Nam me, Ex: BasicPrograms,, spaces it won’t allow w. 2. Selecct public sttatic void main m check box 3. Click k on finish button. b
6. Statements The following describes certain aspects of the software.
6.1. Boolean Operations Use == to compare two primitives or to see if two references refers to the same object. Use the equals() method to see if two different objects are equal. && and || are both Short Circuit Methods which means that they terminate once the result of an evaluation is already clear. Example (true || ....) is always true while (false && ...) always false is. Usage: (var !=null && var.method1()..) ensures that var is not null before doing the real check. Table 1. Boolean Operations ==
Description Is equal, in case of objects the system checks if the reference variable point to the same object, is will not compare the
a.equalsIgnoreCase(b) Checks if string a equals b while ignoring lower cases If (value ? false : true) {}
Return true if value is not true. Negotiation
6.2. Switch Statement The switch statement can be used to handle several alternatives if they are based on the same constant value. switch (expression) { case constant1: command; break; // Will prevent that the other cases or also executed case constant2: command; break; ... default: } Example: switch (cat.getLevel()) { ________________________________________________________________________
Returns the index of the last occurrence of the specified string. StringBuffer does not support this method. Hence first convert the StringBuffer to String via method toString.
Spits myString at / into Strings. Attention: the split string is a regular expression, so if you using special characters which have a meaning in regular expressions you need to quote them. In the second example the . is used and must be quoted by two backslashes.
8. Type Conversion If you use variables of different types Java requires for certain types an explicit conversion. The following gives examples for this conversion.
8.1. Conversion to String Use the following to convert from other types to Strings // Convert from int to String String s1 = String.valueOf (10); // "10" String s2 = // Convert from double to String String.valueOf (Math.PI); // "3.141592653589793" ________________________________________________________________________
String s3 = String.valueOf (1 < 2); // "true" // Convert from date to String String s4 = String.valueOf (new Date()); // "Tue Jun 03 14:40:38 CEST 2003"
8.2. Conversion from String to Number // Conversion from String to int int i = Integer.parseInt(String); // Conversion from float to int float f = Float.parseFloat(String); // Conversion from double to int double d = Double.parseDouble(String); The conversion from string to number is independent from the Locale settings, e.g. it is always using the English notification for number. In this notification a correct number format is "8.20". The German number "8,20" would result in an error. To convert from a German number you have to use the NumberFormat class. The challenges is that if the value is for example 98.00 then the NumberFormat class would create a Long which cannot be casted to Double. Hence the following complex conversion class. private Double convertStringToDouble(String s) { Locale l = new Locale("de", "DE"); Locale.setDefault(l); NumberFormat nf = NumberFormat.getInstance(); Double result = 0.0; try { if (Class.forName("java.lang.Long").isInstance(nf.parse(s))) { ________________________________________________________________________
How to do it public class MyNewClass { private String var1; } package test;
Create a Constructor for "MyNewClass which has a String parameter and assigns the value of it to the "var1" instance variable.
public class MyNewClass { private String var1; public MyNewClass(String para1) { var1 = para1; // or this.var1= para1; } } package test; public class MyNewClass { private String var1;
Create a new method "doSomeThing" in class which do not return a value and has no parameters
public MyNewClass(String para1) { var1 = para1; // or this.var1= para1; } public void doSomeThing() { } } package test;
Create a new method "doSomeThing2" in class which do not return a value and has two parameters, a int and a Person
public class MyNewClass { private String var1; public MyNewClass(String para1) { var1 = para1; // or this.var1= para1; }
How to do it public void doSomeThing() { } public void doSomeThing2(int a, Person person) { } } package test; public class MyNewClass { private String var1; public MyNewClass(String para1) { var1 = para1; // or this.var1= para1; } public void doSomeThing() {
Create a new method "doSomeThing2" in class which do return an int value and has three parameters, two Strings and a Person
} public void doSomeThing2(int a, Person person) { } public int doSomeThing3(String a, String b, Person person) { return 5; // Any value will do for this example } } package test;
Create a class "MyOtherClass" with two instance variables. One will store a String, the other will store a Dog. Create getter and setter for these variables. public class MyOtherClass { ________________________________________________________________________
How to do it String myvalue; Dog dog; public String getMyvalue() { return myvalue; } public void setMyvalue(String myvalue) { this.myvalue = myvalue; } public Dog getDog() { return dog; }
}
public void setDog(Dog dog) { this.dog = dog; }
9.2. Working with local variable A local variable must always be declared in a method.
Declare a (local) variable of type string and assign "Test" to it. Declare a (local) variable of type Person
String variable2 = "Test"; Person person;
Declare a (local) variable of type Person, create a new Object and assign the variable to this object. Declare a array of type String
Person person = new Person(); String array[];
Declare a array of type Person and create an array for this variable which can hold 5 Persons. Assign 5 to the int variable var1 (which was already declared); Assign the existing variable pers2 to the exiting variable pers1; Declare a ArrayList variable which can hold
Person array[]= new Person[5];
var1 = 5;
pers1 = pers2;
ArrayList persons;
objects of type Person Create a new ArrayList with objects of type Person and assign it to the existing variable
persons = new ArrayList();
persons Declare a ArrayList variable which can hold objects of type Person and create a new Object for it.
Java basic program- Program-1: package Pack1; public class JavaBasic_Commands { public static void main(String[]args){ System.out.println("learning selenium"); int a=10; //32bit it can store the numeric values int b=11,c=12; long l=67; //64 bit it can store the numeric values double d=45.6; //it can any decimal values double d1=35; System.out.println(a+d); char c1='j'; //it can strore a single char String str="selenium"; System.out.println(str); } }
Out put: learning selenium ________________________________________________________________________
Program-2: package Pack1; public class String_functions { public static void main (String[]args){ String str="learning"; //it can store no.of chars or group of words, String str1="the rain have been started"; System.out.println(str+"===="+str1); int length=str1.length(); System.out.println(length); //String[] test=str1.split(" "); } }
Out put: learning====the rain have been started 26
For loops Program-3: package Pack1; public class For_Loops { public static void main(String[] args) { ________________________________________________________________________
If conditions programs-4: package Pack1; public class If_Conditions { public static void main (String[]args){ /*int a=120, b=25; if(a>b){ System.out.println("a is the greatest value= "+a); }else{ System.out.println("b is the greatest value= "+b); //type syso+contl+spacebar } */ //< > + ‐ / % & int a=14, b=13, c=45; if(a>b && a>c){ System.out.println("a is the greatest value= "+a); }else if(b>c){ ________________________________________________________________________
}else{ System.out.println("c is the greatest value= }
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[]) { ________________________________________________________________________
Date dNow = new Date(); System.out.println("Current Date: " + dNow); } }
Out put:
Current Date: Tue Apr 23 14:15:54 IST 2013
Find Smallest Number and Largest Number in an array: Program-7: public class FindLargestSmallestNumber { public static void main(String[] args) { int numbers[] = new int[]{32,43,53,54,32,65,63,98,111,23,21}; int smallest = numbers[0]; int largetst = numbers[0]; for(int i=1; i< numbers.length; i++){ if(numbers[i] > largetst) largetst = numbers[i]; else if (numbers[i] < smallest) smallest = numbers[i]; } System.out.println("Largest Number is : " + largetst); System.out.println("Smallest Number is : " + smallest); } }
Out put: Largest Number is : 111 Smallest Number is : 21 ________________________________________________________________________
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;ilargest) largest=numbers[i]; else if(numbers[i]
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
________________________________________________________________________
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
Out put:70
Java Important Interview Questions: Q: What is the difference between an Interface and an Abstract class?
A: An abstract class can have instance methods that implement a default behavior. An Interface can only declare constants and instance methods, but cannot implement default behavior and all methods are implicitly abstract. An interface has all public members and no implementation. An abstract class is a class which may have the usual flavors of class members (private, protected, etc.), but has some abstract methods.
Q: What is the difference between a constructor and a method? A: A constructor is a member function of a class that is used to create objects of that class. It has the same name as the class itself, has no return type, and is invoked using the new operator. A method is an ordinary member function of a class. It has its own name, a return type (which may be void), and is invoked using the dot operator.
Q: What is an Iterator? A: Some of the collection classes provide traversal of their contents via a java.util.Iterator interface. This interface allows you to walk through a collection ________________________________________________________________________
of objects, operating on each object in turn. Remember when using Iterators that they contain a snapshot of the collection at the time the Iterator was obtained; generally it is not advisable to modify the collection itself while traversing an Iterator.
Q: State the significance of public, private, protected, default modifiers both singly and in combination and state the effect of package relationships on declared items qualified by these modifiers. A: public : Public class is visible in other packages, field is visible everywhere (class must be public too) private : Private variables or methods may be used only by an instance of the same class that declares the variable or method, A private feature may only be accessed by the class that owns the feature. protected : Is available to all classes in the same package and also available to all subclasses of the class that owns the protected feature.This access is provided even to subclasses that reside in a different package from the class that owns the protected feature. default :What you get by default ie, without any access modifier (ie, public private or protected).It means that it is visible to all within a particular package. TOP
Q:What is an abstract class? A: Abstract class must be extended/subclassed (to be useful). It serves as a template. A class that is abstract may not be instantiated (ie, you may not call its constructor), abstract class may contain static data. Any class with an abstract method is automatically abstract itself, and must be declared as such. ________________________________________________________________________
A class may be declared abstract even if it has no abstract methods. This prevents it from being instantiated.
Q:What is static in java? A: Static means one per class, not one for each object no matter how many instance of a class might exist. This means that you can use them without creating an instance of a class.Static methods are implicitly final, because overriding is done based on the type of the object, and static methods are attached to a class, not an object. A static method in a superclass can be shadowed by another static method in a subclass, as long as the original method was not declared final. However, you can't override a static method with a nonstatic method. In other words, you can't change a static method into an instance method in a subclass.
Q:What is final? A: A final class can't be extended ie., final class may not be subclassed. A final method can't be overridden when its class is inherited. You can't change value of a final variable (is a constant). Q:What if the main method is declared as private? A: The program compiles properly but at runtime it will give "Main method not public." message.
Q:What if the static modifier is removed from the signature of the main method? A: Program compiles. But at runtime throws an error "NoSuchMethodError". ________________________________________________________________________
Q:What if I write static public void instead of public static void? A: Program compiles and runs properly.
Q:What if I do not provide the String array as the argument to the method? A: Program compiles but throws a runtime error "NoSuchMethodError".
Q:What is the first argument of the String array in main method? A: The String array is empty. It does not have any element. This is unlike C/C++ where the first element by default is the program name. Q:If I do not provide any arguments on the command line, then the String array of Main method will be empty or null? A: It is empty. But not null.
Q:How can one prove that the array is not null but empty using one line of code? A: Print args.length. It will print 0. That means it is empty. But if it would have been null then it would have thrown a NullPointerException on attempting to print args.length.
Q:Can an application have multiple classes having main method? ________________________________________________________________________
A: Yes it is possible. While starting the application we mention the class name to be run. The JVM will look for the Main method only in the class whose name you have mentioned. Hence there is not conflict amongst the multiple classes having main method.
Q:Can I have multiple main methods in the same class? A: No the program fails to compile. The compiler says that the main method is already defined in the class.
Q:Do I need to import java.lang package any time? Why ? A: No. It is by default loaded internally by the JVM.
Q:Can I import same package/class twice? Will the JVM load the package twice at runtime? A: One can import the same package or same class multiple times. Neither compiler nor JVM complains abt it. And the JVM will internally load the class only once no matter how many times you import the same class.
Q:What are Checked and UnChecked Exception? A: A checked exception is some subclass of Exception (or Exception itself), excluding class RuntimeException and its subclasses. Making an exception checked forces client programmers to deal with the possibility that the exception will be thrown. eg, IOException thrown by ________________________________________________________________________
Unchecked exceptions are RuntimeException and any of its subclasses. Class Error and its subclasses also are unchecked. With an unchecked exception, however, the compiler doesn't force client programmers either to catch the exception or declare it in a throws clause. In fact, client programmers may not even know that the exception could be thrown. eg, StringIndexOutOfBoundsException thrown by String's charAt() method· Checked exceptions must be caught at compile time. Runtime exceptions do not need to be. Errors often cannot be.
Q: What is Overriding? A: When a class defines a method using the same name, return type, and arguments as a method in its superclass, the method in the class overrides the method in the superclass. When the method is invoked for an object of the class, it is the new definition of the method that is called, and not the method definition from superclass. Methods may be overridden to be more public, not more private.
Q:What are different types of inner classes? A: Nested top-level classes, Member classes, Local classes, Anonymous classes Nested top-level classes- If you declare a class within a class and specify the static modifier, the compiler treats the class just like any other top-level class. Any class outside the declaring class accesses the nested class with the declaring class name acting similarly to a package. eg, outer.inner. Top-level inner classes implicitly have access only to static variables.There can also be inner interfaces. All of these are of the nested top-level variety. ________________________________________________________________________
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.*? ________________________________________________________________________
A: No you will have to import the subpackages explicitly. Importing com.MyTest.* will import classes in the package MyTest only. It will not import any class in any of it's subpackage.
Q: What is the difference between declaring a variable and defining a variable? A: In declaration we just mention the type of the variable and it's name. We do not initialize it. But defining means declaration + initialization. e.g String s; is just a declaration while String s = new String ("abcd"); Or String s = "abcd"; are both definitions.
Q:Can a top level class be private or protected? A: No. A top level class can not be private or protected. It can have either "public" or no modifier. If it does not have a modifier it is supposed to have a default access.If a top level class is declared as private the compiler will complain that the "modifier private is not allowed here". This means that a top level class can not be private. Same is the case with protected. Q: What type of parameter passing does Java support? A: In Java the arguments are always passed by value. Q: Objects are passed by value or by reference? A: Java only supports pass by value. With objects, the object reference itself is passed by value and so both the original reference and parameter copy both refer to the same object. Q: What is Externalizable interface? ________________________________________________________________________
A: Externalizable is an interface which contains two methods readExternal and writeExternal. These methods give you a control over the serialization mechanism. Thus if your class implements this interface, you can customize the serialization process by implementing these methods.
Oops Interview Questions: 1. What are the principle concepts of OOPS? There are four principle concepts upon which object oriented design and programming rest. They are: •
Abstraction
•
Polymorphism
•
Inheritance
•
Encapsulation (i.e. easily remembered as A-PIE).
2. What is Abstraction? Abstraction refers to the act of representing essential features without including the background details or explanations. 2. What is Encapsulation? Encapsulation is a technique used for hiding the properties and behaviors of an object and allowing outside access only as appropriate. It prevents other objects from directly altering or accessing the properties or methods of the encapsulated object. 3. What is the difference between abstraction and encapsulation? ________________________________________________________________________
Abstraction focuses on the outside view of an object (i.e. the interface) Encapsulation (information hiding) prevents clients from seeing it’s inside view, where the behavior of the abstraction is implemented.
•
Abstraction solves the problem in the design side while Encapsulation is the Implementation.
•
Encapsulation is the deliverables of Abstraction. Encapsulation barely talks about grouping up your abstraction to suit the developer needs.
4. What is Inheritance? •
Inheritance is the process by which objects of one class acquire the properties of objects of another class.
•
A class that is inherited is called a superclass.
•
The class that does the inheriting is called a subclass.
•
Inheritance is done by using the keyword extends.
•
The two most common reasons to use inheritance are: o
To promote code reuse
o
To use polymorphism
5. What is Polymorphism? Polymorphism is briefly described as "one interface, many implementations." Polymorphism is a characteristic of being able to assign a different meaning or usage to something in different contexts - specifically, to allow an entity such as a variable, a function, or an object to have more than one form. 6. How does Java implement polymorphism?
(Inheritance, Overloading and Overriding are used to achieve Polymorphism in java). Polymorphism manifests itself in Java in the form of multiple methods having the same name. •
In some cases, multiple methods have the same name, but different formal argument lists (overloaded methods).
•
In other cases, multiple methods have the same name, same return type, and same formal argument list (overridden methods).
7. Explain the different forms of Polymorphism. There are two types of polymorphism one is Compile time polymorphism and the other is run time polymorphism. Compile time polymorphism is method overloading. Runtime time polymorphism is done using inheritance and interface. Note: From a practical programming viewpoint, polymorphism manifests itself in three distinct forms in Java: •
Method overloading
•
Method overriding through inheritance
•
Method overriding through the Java interface
8.What is runtime polymorphism or dynamic method dispatch? In Java, runtime polymorphism or dynamic method dispatch is a process in which a call to an overridden method is resolved at runtime rather than at compile-time. In this process, an overridden method is called through the reference variable of a superclass. The determination of the method to be called is based on the object being referred to by the reference variable.
10.What is Dynamic Binding? Binding refers to the linking of a procedure call to the code to be executed in response to the call. Dynamic binding (also known as late binding) means that the code associated with a given procedure call is not known until the time of the call at run-time. It is associated with polymorphism and inheritance.
11.What is method overloading? Method Overloading means to have two or more methods with same name in the same class with different arguments. The benefit of method overloading is that it allows you to implement methods that support the same semantic operation but differ by argument number or type. Note: •
Overloaded methods MUST change the argument list
•
Overloaded methods CAN change the return type
•
Overloaded methods CAN change the access modifier
•
Overloaded methods CAN declare new or broader checked exceptions
•
A method can be overloaded in the same class or in a subclass
12.What is method overriding? Method overriding occurs when sub class declares a method that has the same type arguments as a method declared by one of its superclass. The key benefit of overriding is the ability to define behavior that’s specific to a particular subclass type. Note: ________________________________________________________________________
The overriding method cannot have a more restrictive access modifier than the method being overridden (Ex: You can’t override a method marked public and make it protected).
•
You cannot override a method marked final
•
You cannot override a method marked static
13.What are the differences between method overloading and method overriding? Overloaded Method
Overridden Method
Arguments
Must change
Must not change
Return type
Can change
Can’t change except for covariant returns
Exceptions
Can change
Can reduce or eliminate. Must not throw new or broader checked exceptions
Access
Can change
Must not make more restrictive (can be less restrictive)
Invocation
Reference type determines which
Object type determines which
overloaded version is selected.
method is selected. Happens at
Happens at compile time.
runtime.
14.Can overloaded methods be override too? Yes, derived classes still can override the overloaded methods. Polymorphism can still happen. Compiler will not binding the method calls since it is overloaded, because it might be overridden now or in the future. ________________________________________________________________________
15.Is it possible to override the main method? NO, because main is a static method. A static method can't be overridden in Java.
16.How to invoke a superclass version of an Overridden method? To invoke a superclass method that has been overridden in a subclass, you must either call the method directly through a superclass instance, or use the super prefix in the subclass itself. From the point of the view of the subclass, the super prefix provides an explicit reference to the superclass' implementation of the method. // From subclass super.overriddenMethod(); 17.What is super? super is a keyword which is used to access the method or member variables from the superclass. If a method hides one of the member variables in its superclass, the method can refer to the hidden variable through the use of the super keyword. In the same way, if a method overrides one of the methods in its superclass, the method can invoke the overridden method through the use of the super keyword. Note: •
You can only go back one level.
•
In the constructor, if you use super(), it must be the very first code, and you cannot access any this.xxx variables or methods to compute its parameters.
A constructor is a special method whose task is to initialize the object of its class.
•
It is special because its name is the same as the class name.
•
They do not have return types, not even void and therefore they cannot return values.
•
They cannot be inherited, though a derived class can call the base class constructor.
•
Constructor is invoked whenever an object of its associated class is created.
32.How does the Java default constructor be provided? If a class defined by the code does not have any constructor, compiler will automatically provide one no-parameter-constructor (default-constructor) for the class in the byte code. The access modifier (public/private/etc.) of the default constructor is the same as the class itself.
33.Can constructor be inherited? No, constructor cannot be inherited, though a derived class can call the base class constructor.
34.What are the differences between Contructors and Methods?
lowercase letter by convention -usually the name of an action
this
Refers to another constructor in
Refers to an instance of the
the same class. If used, it must
owning class. Cannot be used by
be the first line of the
static methods.
constructor super
Calls the constructor of the
Calls an overridden method in the
parent class. If used, must be the
parent class
first line of the constructor Inheritance
Constructors are not inherited
Methods are inherited
35.How are this() and super() used with constructors? •
Constructors use this to refer to another constructor in the same class with a different parameter list.
•
Constructors use super to invoke the superclass's constructor. If a constructor uses super, it must use it in the first line; otherwise, the compiler will complain.
36.What are the differences between Class Methods and Instance Methods? ________________________________________________________________________
Instance Methods Instance methods on the other hand require an instance of the class to exist
Class methods are methods which are
before they can be called, so an instance
declared as static. The method can be
of a class needs to be created by using
called without creating an instance of the
the new keyword.
class
Instance methods operate on specific instances of classes.
Class methods can only operate on class
Instance methods of the class can also
members and not on instance members as
not be called from within a class method
class methods are unaware of instance
unless they are being called on an
members.
instance of that class.
Class methods are methods which are declared as static. The method can be
Instance methods are not declared as
called without creating an instance of
static.
the class.
37.How are this() and super() used with constructors? •
Constructors use this to refer to another constructor in the same class with a different parameter list.
•
Constructors use super to invoke the superclass's constructor. If a constructor uses super, it must use it in the first line; otherwise, the compiler will complain.
38.What are Access Specifiers? ________________________________________________________________________
One of the techniques in object-oriented programming is encapsulation. It concerns the hiding of data in a class and making this class available only through methods. Java allows you to control access to classes, methods, and fields via so-called access specifiers..
39.What are Access Specifiers available in Java? Java offers four access specifiers, listed below in decreasing accessibility: •
Public- public classes, methods, and fields can be accessed from everywhere.
•
Protected- protected methods and fields can only be accessed within the same class to which the methods and fields belong, within its subclasses, and within classes of the same package.
•
Default(no specifier)- If you do not set access to specific level, then such a class, method, or field will be accessible from inside the same package to which the class, method, or field belongs, but not from outside this package.
•
Private- private methods and fields can only be accessed within the same class to which the methods and fields belong. private methods and fields are not visible within subclasses and are not inherited by subclasses.
Situation Accessible to class from same package? Accessible to class from different package?
public
protected
default
private
yes
yes
yes
no
yes
no, unless it is a subclass
no
no
40.What is final modifier? ________________________________________________________________________
The final modifier keyword makes that the programmer cannot change the value anymore. The actual meaning depends on whether it is applied to a class, a variable, or a method. •
final Classes- A final class cannot have subclasses.
•
final Variables- A final variable cannot be changed once it is initialized.
•
final Methods- A final method cannot be overridden by subclasses.
41.What are the uses of final method? There are two reasons for marking a method as final: •
Disallowing subclasses to change the meaning of the method.
•
Increasing efficiency by allowing the compiler to turn calls to the method into inline Java code.
42.What is static block? Static block which exactly executed exactly once when the class is first loaded into JVM. Before going to the main method the static block will execute.
43.What are static variables? Variables that have only one copy per class are known as static variables. They are not attached to a particular instance of a class but rather belong to a class as a whole. They are declared by using the static keyword as a modifier. static type varIdentifier;
where, the name of the variable is varIdentifier and its data type is specified by type. Note: Static variables that are not explicitly initialized in the code are automatically initialized with a default value. The default value depends on the data type of the variables.
44.What is the difference between static and non-static variables? A static variable is associated with the class as a whole rather than with specific instances of a class. Non-static variables take on unique values with each object instance.
45.What are static methods? Methods declared with the keyword static as modifier are called static methods or class methods. They are so called because they affect a class as a whole, not a particular instance of the class. Static methods are always invoked without reference to a particular instance of a class. Note:The use of a static method suffers from the following restrictions: •
A static method can only call other static methods.
•
A static method must only access static data.
•
A static method cannot reference to the current object using keywords super or this.
To eliminate the errors or defects and improve the quality of application
2. Why defects occur? ¾ Hard coding ¾ While integrating the modules ¾ Lack of documentation ¾ Miscommunication ¾ Time pressure ¾ Dynamically changing requirements
3. What is automation Testing? It is a process of implementing particular work automatically by using a machine, to reduce the need of human work in the production of goods and services...
4. What is meant by Automation in software testing? It is a process of testing an application(executing the tests, comparing expected and actual results under some controlled conditions and generating the reports) automatically by using a 'Tool' to reduce the need of human effort. This tool may be Selenium / QTP / RFT / SilkTest /sahi/watir etc…
5. Why you choose selenium? ¾ Selenium is a open source tool ¾ It can Automate any Web Application ¾ It is a perfect tool for Browser Automation ¾ In the market very demand Automation Tool ¾ Around 60-70% companies are using selenium ¾ In future it may be 90% ¾ Job opportunities are very high ________________________________________________________________________
¾ Once we prepare the code in the windows platform we can run in any OS, platform independent. ¾ We can integrate with No. of tools and languages
6. Types of Automation Tools ¾ Functional Automation Tools: QTP, Winrunner, Silktest, Selenium, Sahi, watir etc. ¾ Performance Tools: LoadRunner, RFT, SOAP etc. ¾ Management tools: Test Director, Quality center, Testlink, Rally etc. ¾ Bugtracking tools: Jira, Bagzilla ¾ Build Tools: ANT and Rake
7. What is Selenium? ¾ Selenium is Functional Automation tool ¾ Selenium is Browser or Web based Automation Tool ¾ Selenium is suite of tools, SeleniumIDE, RC, WebDriver, Grid ¾ It can record or automate any web application but it can’t support for client or desktop application. ¾ It can support many languages java, C#, Ruby, python ¾ Data driven is possible ¾ User can enhance script in any following language JAVA, C#, PHP, Ruby, Python ¾ Selenium is a Functional Testing Tool can be used for Regression testing of Web applications in a variety of browsers and platforms ¾ Selenium was developed by ThoughtWorks, now takeover by sauce labs. ¾ It's an Open Source Tool ¾ Selenium supported platforms are Windows, Linux, Mac OS
1. What to Automate or Not to Automate? Is automation always advantageous? When should one decide to automate test cases? It is not always advantageous to automate test cases. There are times when manual testing may be more appropriate. For instance, if the application’s user interface will change considerably in the near future, then any automation would need to be rewritten. Also, sometimes there simply is not enough time to build test automation. For the short term, manual testing may be more effective. If an application has a very tight deadline, there is currently no test automation available, and it’s imperative that the testing get done within that time frame, then manual testing is the best solution. However, automation has specific advantages for improving the long-term efficiency of a software team’s testing processes.
Test automation supports: • Frequent regression testing • Rapid feedback to developers during the development process • Virtually unlimited iterations of test case execution • Customized reporting of application defects • Support for Agile and eXtreme development methodologies • Disciplined documentation of test cases • Finding defects missed by manual testing
5. Test Automation for Web Applications? Many, perhaps most, software applications today are written as web-based applications to be run in an Internet browser. The effectiveness of testing these applications varies widely among companies and organizations. In an era of continuously improving software processes, such as eXtreme programming (XP) and Agile, it can be argued that disciplined testing and quality assurance practices are still underdeveloped in many organizations. Software testing is often conducted manually. At times, this is effective; however there are alternatives to manual testing that many organizations are unaware of, or lack the skills to perform. Utilizing these alternatives would in most cases greatly improve the efficiency of their software development by adding efficiencies to their testing. Test automation is often the answer. Test automation means using a tool to run repeatable tests against the target application whenever necessary.
3. Introducing Selenium Selenium is a robust set of tools that supports rapid development of test automation for web-based applications. Selenium provides a rich set of testing functions specifically geared to the needs of testing of a web application. These operations are highly flexible, allowing many options for locating UI elements and comparing expected test results against actual application behavior. One of Selenium’s key features is the support for executing one’s tests on multiple browser platforms.
4. Selenium Components Selenium is composed of three major tools. Each one has a specific role in aiding the development of web application test automation.
4.1 Selenium-IDE Selenium-IDE is the Integrated Development Environment for building Selenium test cases. It operates as a Firefox add-on and provides an easy-to-use interface for developing and running individual test cases or entire test suites. Selenium-IDE has a recording feature, which will keep account of user actions as they are performed and store them as a reusable script to play back. It also has a context menu (right-click) integrated with the Firefox browser, which allows the user to pick from a list of assertions and verifications for the selected location. Selenium-IDE also offers full editing of test cases for more precision and control. Although Selenium-IDE is a Firefox only add-on, tests created in it can also be run against other browsers by using Selenium-RC and specifying the name of the test suite on the command line.
4.2 Selenium-RC (Remote Control) Selenium-RC allows the test automation developer to use a programming language for maximum flexibility and extensibility in developing test logic. For instance, if the application under test returns a result set, and if the automated test program needs to run tests on each element in the result set, the programming language’s iteration support can be used to iterate through the result set, calling Selenium commands to run tests on each item. Selenium-RC provides an API (Application Programming Interface) and library for each of its supported languages: HTML, Java, C#, Perl, PHP, Python, and Ruby. This ability to use Selenium-RC with a highlevel programming language to develop test cases also allows the automated testing to be integrated with a project’s automated build environment.
4.3 Selenium-Grid Selenium-Grid allows the Selenium-RC solution to scale for large test suites or test suites that must be run in multiple environments. With Selenium-Grid, multiple instances of Selenium-RC are running on various operating system and browser configurations. Each of these when launching register with a hub. When tests are sent to the hub they are then redirected to an available Selenium-RC, which will launch the browser and run the test. This allows for running tests in parallel, with the entire test suite theoretically taking only as long to run as the longest individual test.
Selenium 1.0 and Selenium-RC. This is the old, support platform for Selenium 1.0. It should still apply to the Selenium 2.0 release of Selenium-RC. Browser
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.
4.2 Installing the IDE Using Firefox, first, download the IDE from the Seleniumhq.org downloads page When downloading from Firefox, you’ll be presented with the following window. After Installing Selenium IDE will display like below:
1. IDE Features 1.1 Menu Bar The File menu allows you to create, open and save test case and test suite files. The Edit menu allows copy, paste, delete, undo and select all operations for editing the commands in your test case. The Options menu allows the changing of settings. You can set the timeout value for certain commands, add user-defined user extensions to the base set of Selenium commands, and specify the format (language) used when saving your test cases. The Help menu is the standard Firefox Help menu; only one item on this menu–UI-Element Documentation–pertains to Selenium-IDE.
1.2 Toolbar The toolbar contains buttons for controlling the execution of your test cases, including a step feature for debugging your test cases. The right-most button, the one with the red-dot, is the record button.
Speed Control: controls how fast your test case runs.
Run All: Runs the entire test suite when a test suite with multiple test cases is loaded.
Run: Runs the currently selected test. When only a single test is loaded this button and the Run All button have the same effect.
Pause/Resume: Allows stopping and re-starting of a running test case.
Step: Allows one to “step” through a test case by running it one command at a time. Use for debugging test cases.
Record: Records the user’s browser actions.
1.3 Test Case Pane Your script is displayed in the test case pane. It has two tabs, one for displaying the command and their parameters in a readable “table” format.
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.
Source View: Select the point in your test case where you want to insert the comment. Add an HTML-style comment, i.e., .
Edit a Command or Comment Table View Simply select the line to be changed and edit it using the Command, Target, and Value fields.
Source View Since Source view provides the equivalent of a WYSIWYG editor, simply modify which line you wish– command, parameter, or comment.
1.5 Opening and Saving a Test Case The File=>Open, Save and Save As menu commands behave similarly to opening and saving files in most other programs. When you open an existing test case, SeleniumIDE displays its Selenium commands in the test case pane. Test suite files can also be opened and saved via the File menu. However, such operations have their own menu entries near the bottom; the Open, Save, and Save As items are only for files.
Note: At the time of this writing, there’s a bug, where at times, when the IDE is first opened and then you select File=>Open, nothing happens. If you see this, close down ________________________________________________________________________
the IDE and restart it (you don’t need to close the browser itself). This will fix the problem.
1.6 Running Test Cases The IDE allows many options for running your test case. You can run a test case all at once, stop and start it, run it one line at a time, run a single command you are currently developing, and you can do a batch run of an entire test suite. Execution of test cases is very flexible in the IDE. Run a Test Case Click the Run button to run the currently displayed test case. Run a Test Suite Click the Run All button to run all the test cases in the currently loaded test suite. Stop and Start The Pause button can be used to stop the test case while it is running. The icon of this button then changes to indicate the Resume button. To continue click Resume. Stop in the Middle You can set a breakpoint in the test case to cause it to stop on a particular command. This is useful for debugging your test case. To set a breakpoint, select a command, right-click, and from the context menu select Toggle Breakpoint. Start from the Middle You can tell the IDE to begin running from a specific command in the middle of the test case. This also is used for debugging. To set a startpoint, select a command, right-click, and from the context menu select Set/Clear Start Point.
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.
1. Introduction Selenium-RC is the solution for tests that need more than simple browser actions and linear execution. Selenium-RC uses the full power of programming languages to create more complex tests like reading and writing files, querying a database, emailing test results. You’ll want to use Selenium-RC whenever your test requires logic not supported by Selenium-IDE. What logic could this be? For example, Selenium-IDE does not directly support: ¾ condition statements ¾ iteration ¾ logging and reporting of test results ¾ error handling, particularly unexpected errors ¾ database testing ¾ test case grouping ¾ re-execution of failed tests ¾ test case dependency ¾ screenshot capture of test failures ________________________________________________________________________
Although these tasks are not supported by Selenium directly, all of them can be achieved by using programming techniques with a language-specific Selenium-RC client library. In the Adding Some Spice to Your Tests section, you’ll find examples that demonstrate the advantages of using a programming language for your tests.
2. How Selenium-RC Works First, we will describe how the components of Selenium-RC operate and the role each plays in running your test scripts.
5.1 RC Components Selenium-RC components are: ¾ The Selenium Server which launches and kills browsers, interprets and runs the Selenese commands passed from the test program, and acts as an HTTP proxy, intercepting and verifying HTTP messages passed between the browser and the AUT. ¾ Client libraries which provide the interface between each programming language and the Selenium-RC Server. Here is a simplified architecture diagram....
The diagram shows the client libraries communicate with the Server passing each Selenium command for execution. Then the server passes the Selenium command to the browser using Selenium-Core JavaScript commands. The browser, using its JavaScript interpreter, executes the Selenium command. This runs the Selenese action or verification you specified in your test script.
2.2 Selenium Server ________________________________________________________________________
Selenium Server receives Selenium commands from your test program, interprets them, and reports back to your program the results of running those tests. The RC server bundles Selenium Core and automatically injects it into the browser. This occurs when your test program opens the browser (using a client library API function). Selenium-Core is a JavaScript program, actually a set of JavaScript functions which interprets and executes Selenese commands using the browser’s built-in JavaScript interpreter. The Server receives the Selenese commands from your test program using simple HTTP GET/POST requests. This means you can use any programming language that can send HTTP requests to automate Selenium tests on the browser.
2.3 Client Libraries The client libraries provide the programming support that allows you to run Selenium commands from a program of your own design. There is a different client library for each supported language. A Selenium client library provides a programming interface (API), i.e., a set of functions, which run Selenium commands from your own program. Within each interface, there is a programming function that supports each Selenese command. The client library takes a Selenese command and passes it to the Selenium Server for processing a specific action or test against the application under test (AUT). The client library also receives the result of that command and passes it back to your program. Your program can receive the result and store it into a program variable and reporting it as a success or failure, or possibly taking corrective action if it was an unexpected error. So to create a test program, you simply write a program that runs a set of Selenium commands using a client library API. And, optionally, if you already have a Selenese ________________________________________________________________________
test script created in the Selenium-IDE, you can generate the Selenium-RC code. The Selenium-IDE can translate (using its Export menu item) its Selenium commands into a client-driver’s API function calls. See the Selenium-IDE chapter for specifics on exporting RC code from Selenium-IDE.
2.3 Installation After downloading the Selenium-RC zip file from the downloads page, you’ll notice it has several subfolders. These folders have all the components you need for using Selenium-RC with the programming language of your choice. Once you’ve chosen a language to work with, you simply need to: ¾ Install the Selenium-RC Server. ¾ Set up a programming project using a language specific client driver.
5.2 Installing Selenium Server The Selenium-RC server is simply a Java jar file (selenium-server.jar), which doesn’t require any special installation. Just downloading the zip file and extracting the server in the desired directory is sufficient.
3.2 Running Selenium Server Before starting any tests you must start the server. Go to the directory where Selenium-RC’s server is located and run the following from a command-line console. java -jar selenium-server.jar
This can be simplified by creating a batch or shell executable file (.bat on Windows and .sh on Linux) containing the command above. Then make a shortcut to that executable on your desktop and simply double-click the icon to start the server. For the server to run you’ll need Java installed and the PATH environment variable correctly configured to run it from the console. You can check that you have Java correctly installed by running the following on a console: java –version If you get a version number (which needs to be 1.5 or later), you’re ready to start using Selenium-RC.
3.3 Using the Java Client Driver ¾ Download Selenium-RC from the SeleniumHQ downloads page. ¾ Extract the file selenium-java-client-driver.jar. ¾ Open your desired Java IDE (Eclipse, NetBeans, IntelliJ, Netweaver, etc.) ¾ Create a new project. ¾ Add the selenium-java-client-driver.jar files to your project as references. ¾ Add to your project classpath the file selenium-java-client-driver.jar. ¾ From Selenium-IDE, export a script to a Java file and include it in your Java. project, or write your Selenium test in Java using the selenium-java-client API. The API is presented later in this chapter. You can either use JUnit, or TestNg to run your test, or you can write your own simple main() program. These concepts are explained later in this section. ¾ Run Selenium server from the console. ________________________________________________________________________
Selenium RC Basic Program-3: package Selenium_RC; import org.junit.Test; public class Methodcall { @Test public void testcall(){ Junit_Annotations ja=new Junit_Annotations(); //Object creating ja.CloseBrowser(); //using the object calling methods ja.OpenBrowser(); ja.test1(); ja.test2(); } }
Gmail Test Using JUnit Program-4: package Selenium_RC; import org.junit.Ignore; ________________________________________________________________________
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
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 {
JUnit 4 and TestNG are both very popular unit test framework in Java. Both frameworks look very similar in functionality. Which one is better? Which unit test framework should i use in Java project? Defference between JUnit 4 and TestNG.
1. Annotation Support The annotation supports are implemented in both JUnit 4 and TestNG look similar. Feature
JUnit 4
TestNG
test annotation
@Test
@Test
run before all tests in – this suite have run
@BeforeSuite
run after all tests in this suite have run
–
@AfterSuite
run before the test
–
@BeforeTest
run after the test
–
@AfterTest
run before the first test method that belongs to any of these groups is
1. In JUnit 4, we have to declare “@BeforeClass” and “@AfterClass” method as static method. TestNG is more flexible in method declaration, it does not have this constraints. 2. 3 additional setUp/tearDown level: suite and group (@Before/AfterSuite, @Before/AfterTest, @Before/AfterGroup). JUnit 4 @BeforeClass public static void oneTimeSetUp() { // one-time initialization code System.out.println("@BeforeClass - oneTimeSetUp"); } TestNG @BeforeClass public void oneTimeSetUp() { // one-time initialization code System.out.println("@BeforeClass - oneTimeSetUp"); } In JUnit 4, the annotation naming convention is a bit confusing, e.g “Before”, “After” and “Expected”, we do not really understand what is “Before” and “After” do, and what we “Expected” from test method? TestNG is easier to understand, it using “BeforeMethod”, “AfterMethod” and “ExpectedException” instead.
2. Exception Test The “exception testing” means what exception throw from the unit test, this feature are implemented in both JUnit 4 and TestNG. JUnit 4 @Test(expected = ArithmeticException.class) public void divisionWithException() { int i = 1/0; } TestNG @Test(expectedExceptions = ArithmeticException.class) public void divisionWithException() { int i = 1/0; }
3. Ignore Test The “Ignored” means whether it should ignore the unit test, this feature are implemented in both JUnit 4 and TestNG . JUnit 4 @Ignore("Not Ready to Run") @Test public void divisionWithException() { System.out.println("Method is not ready yet"); } ________________________________________________________________________
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. ________________________________________________________________________
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, ________________________________________________________________________
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. ________________________________________________________________________
With “Grouping” test concept, the integration test possibility is unlimited. For example, we can only test the “DatabaseFuntion” group from all of the unit test classes.
6. Parameterized Test The “Parameterized Test” means vary parameter value for unit test. This feature is implemented in both JUnit 4 and TestNG. However both are using very different method to implement it. JUnit 4 The “@RunWith” and “@Parameter” is use to provide parameter value for unit test, @Parameters have to return List[], and the parameter will pass into class constructor as argument. @RunWith(value = Parameterized.class) public class JunitTest6 { private int number; public JunitTest6(int number) { this.number = number; } ________________________________________________________________________