Wednesday, May 5, 2010

Running Java Test Cases using Selenium GRIDs Tutorial

This tutorial explains how to use the Selenium GRID to run multiple Selenium Test Cases (Java Based). Although not recommended this allows you to use the selenium GRID as a stress testing tool.

Prerequisites:
1. Selenium IDE, Selenium RC(Remote Control) and Selenium GRIDS need to be installed
2. Intermediate Knowledge of the above is required. (If you dont have the necessary knowledge then please go through the above tools before continuing further).
3. Basic Knowledge on Java

NOTE:
Test Case - A Collection of Tests.

Test Suite - A Collection of Test Suites

1. Record the Test Suite / Test Case using the selenium IDE.
2. Export the test cases as JAVA (TestNG)

Each class should contain a method for the testing as shown below.

Import_Statements

public class WSC_login extends SeleneseTestNgHelper{

public static final String TIMEOUT = "120000";

@Test
public void testWSC_login() throws Exception {
session().open("/wi5/dev/ava/index.php?PG&&lan=english");
session().type("textfield2", "ava1");
session().type("textfield", "12345678");
session().click("//img[@alt='login']");
Thread.sleep(2000);
session().click("link=home");
assertTrue(session().getConfirmation().matches("^Are you sure you want to logout[\\s\\S]$"));
}
}

3. Modify the class as follows
i. remove the “extends SeleneseTestNgHelper” section
ii. add the following code

public static final String TIMEOUT = "120000";

@BeforeMethod(groups = {"default", "example"}, alwaysRun = true)
@Parameters({"seleniumHost", "seleniumPort", "browser", "webSite"})
protected void startSession(String seleniumHost, int seleniumPort, String browser, String webSite) throws Exception {
startSeleniumSession(seleniumHost, seleniumPort, browser, webSite);
session().setTimeout(TIMEOUT);
}

@AfterMethod(groups = {"default", "example"}, alwaysRun = true)
protected void closeSession() throws Exception {
closeSeleniumSession();
}

iii. Modify the package name and place the java files in the proper folder structure that matches the package
iv. Replace all instances of “selenium.” With “session().”. Do not replace the instance on the import name.
v. Replace all instances of “verify” with “assert”
vi. Replace all variable selenium variable names with java variable names. Eg:- replace “${Login_Name}” with Login_Name.
vii. Add the following imports

import static com.thoughtworks.selenium.grid.tools.ThreadSafeSeleniumSessionStorage.closeSeleniumSession;
import static com.thoughtworks.selenium.grid.tools.ThreadSafeSeleniumSessionStorage.session;
import static com.thoughtworks.selenium.grid.tools.ThreadSafeSeleniumSessionStorage.startSeleniumSession;
import static org.testng.AssertJUnit.assertTrue;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Parameters;

Note : When the test is run using the grid, each “test” method will be run as a new instance. If you wish to run the same test multiple times then copies of the “test” method you with to run must exist. However they cannot have the same method name.

viii. Add the @BeforeMethod to set the actions that need to be done before the test methods are run.

@BeforeMethod(groups = {"default", "example"}, alwaysRun = true)
@Parameters({"seleniumHost", "seleniumPort", "browser", "webSite"})
protected void startSession(String seleniumHost, int seleniumPort, String browser, String webSite) throws Exception {
startSeleniumSession(seleniumHost, seleniumPort, browser, webSite);
session().setTimeout(TIMEOUT);
session().setSpeed("500");
}

ix. Add the @AfterMethod to set the actions that need to be done after the test methods are run.

@AfterMethod(groups = {"default", "example"}, alwaysRun = true)
protected void closeSession() throws Exception {
closeSeleniumSession();
}

4. Place the folder used in step 3.iii within the following folder. We will be using the ant build files provided with the selenium grid release. It is possible to create our own build files.

5. Update the build.xml file within the

\examples\java folder
Place the following code and modify the necessary values

[target name="run_WSC_Test"
description="WSC Test"]
[java classpathref="runtime.classpath"
classname="org.testng.TestNG"
failonerror="true"]

[sysproperty key="java.security.policy" file="${rootdir}/lib/testng.policy"/]
[sysproperty key="webSite" value="http://192.168.11.47/wi5/dev/ava/index.php" /]
[sysproperty key="seleniumHost" value="${seleniumHost}" /]
[sysproperty key="seleniumPort" value="${seleniumPort}" /]
[sysproperty key="browser" value="${browser}" /]
[arg value="-d" /]
[arg value="${basedir}/target/reports" /]
[arg value="-suitename" /]
[arg value="WSC TEST" /]
[arg value="-parallel"/]
[arg value="methods"/]
[arg value="-threadcount"/]
[arg value="5"/]
[arg value="WSC_test.xml"/]
[!--arg value="-testclass"/]
[arg value="com.thoughtworks.selenium.grid.examples.java.WSC_login"/--]
[/java]

[/target]

target name="run_WSC_Test" description="WSC Test"] - name of the ant build

[java classpathref="runtime.classpath"
classname="org.testng.TestNG"
failonerror="true"] - The runtime.classpath is a ant path that points to necessary selenium libraries.

[sysproperty key="java.security.policy" file="${rootdir}/lib/testng.policy"/] - Policy file that depicts the actions permittied by the selenium grid

[sysproperty key="webSite" value="http://192.168.11.47/wi5/dev/ava/index.php" /] - Name of the website that the test will run upon

[sysproperty key="seleniumHost" value="${seleniumHost}" /]
[sysproperty key="seleniumPort" value="${seleniumPort}" /] - points to the selenium grid host and port. The default values are 4444 / localhost

[sysproperty key="browser" value="${browser}" /] - Browser type used for the tests. Default is Firefox

[arg value="-d" /]
[arg value="${basedir}/target/reports" /] - location where the reports are genereated

[arg value="-suitename" /]
[arg value="WSC TEST" /] - The suit name

[arg value="-parallel"/]
[arg value="methods"/]
[arg value="-threadcount"/]
[arg value="5"/] - amount of threads used for the tests.

[arg value="WSC_test.xml"/] - xml file that describes the classes and other parameters used for the test. This part can be replaced with the following.

[!--arg value="-testclass"/]
[arg value="com.thoughtworks.selenium.grid.examples.java.WSC_login"/--]
[/java]

[/target]

6. If the target value points to a xml file then prepare the file as follows.

[!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" ]

[suite name="WSC Testing" parallel="methods" thread-count="5" verbose="3" ]
[test name="WSC Testing" ]
[!--packages]
[package name="com.thoughtworks.selenium.grid.examples.java" /]
[/packages--]
[classes]
[class name="WSC_Selenium_Grid_PT.java.WSC_login"/]
[/classes]
[/test]
[/suite]


[!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" ]

[suite name="WSC Testing" parallel="methods" thread-count="5" verbose="3" ]
[test name="WSC Testing" ]
[/packages--]

[classes]
[class name="WSC_Selenium_Grid_PT.java.WSC_login"/] - classes used for the test

[!--packages]
[package name="com.thoughtworks.selenium.grid.examples.java" /] - If the classes in the entire package are to be used then it can be specified as above.

[/classes]
[/test]
[/suite]


7. Open a new Command Prompt and navigate to the \examples\java folder. And run “ant build”. This will compile the files and place them within the classpath specified within the build.xml file

8. Start the Selenium Grid as well as multiple instances of the selenium RC

9. run the test by “ant ”. Note the target name should match that which is specified in the build.xml file.

Wednesday, March 24, 2010

Java Interview Questions and Answers

Java is an extensive language and is also a highly sought after one. Many candidates face some simple but tough questions with respect to Java interviews. This section covers many of the possible Questions asked by interviewers as well as Answers for them.

Q.
What is transient variable?

A. Transient variable can't be serialize. For example if a variable is declared as transient in a Serializable class and the class is written to an ObjectStream, the value of the variable can't be written to the stream instead when the class is retrieved from the ObjectStream the value of the variable becomes null.

Q. What do you understand by Synchronization?

A. Synchronization is a process of controlling the access of shared resources by the multiple threads in such a manner that only one thread can access one resource at a time. In non synchronized multi threaded application, it is possible for one thread to modify a shared object while another thread is in the process of using or updating the object's value. Synchronization prevents such type of data corruption.

E.g. Synchronizing a function:
public synchronized void Method1 () {
// Appropriate method-related code.}
E.g. Synchronizing a block of code inside a function:
public myFunction (){
synchronized (this) {
// Synchronized code here.}}

Q. What is the Collection API?

A. The Collection API is a set of classes and interfaces that support operation on collections of objects. These classes and interfaces are more flexible, more powerful, and more regular than the vectors, arrays, and hashtables if effectively replaces.
Example of classes:
HashSet, HashMap, ArrayList, LinkedList, TreeSet and TreeMap.
Example of interfaces:
Collection, Set, List and Map.

Q. Is Iterator a Class or Interface?

A. Iterator is an interface which is used to step through the elements of a Collection.

Q. What are the similarities/difference between an Abstract class and Interface?

A. Differences: Interfaces provide a form of multiple inheritance. A given class can implement multiple interfaces but can only extend one abstract class.Interfaces are limited to public methods and constants with no implementation. Abstract classes can have a partial implementation, protected parts, static methods, etc.

Similarities: Neither Abstract classes or Interface can be instantiated.All abstract methods declared within them must be implemented by the first concrete class that implements / inherits them.

Q. What is an abstract Class?

A. It is a class that cannot be instantiated. It is defined using the keyword abstract. It must be extended in order to be used. There must be at least one abstract method in this class.

Q. What are the three mail principals of OOP? Explain them.

A. Inheritance, Polymorphism and Encapsulation

Encapsulation is a process of binding or wrapping the data and the codes that operates on the data into a single entity. This keeps the data safe from outside interface and misuse. One way to think about encapsulation is as a protective wrapper that prevents code and data from being arbitrarily accessed by other code defined outside the wrapper.

Inheritance is the process by which one object acquires the properties of another object.

The meaning of Polymorphism is something like one name many forms. Polymorphism enables one entity to be used as general category for different types of actions. The specific action is determined by the exact nature of the situation. The concept of polymorphism can be explained as "one interface, multiple methods".

Q. Explain garbage collection.

A. Garbage collection is also called automatic memory management as JVM automatically removes the unused variables/objects (value is null) from the memory. User program cannot directly free the object from memory, instead it is the job of the garbage collector to automatically free the objects that are no longer referenced by a program.
Every class inherits finalize() method from java.lang.Object, the finalize() method is called by garbage collector when it determines no more references to the object exists.
You can explicitly call the System.gc() method but there is no guarantee that the garbage collector will execute.

Q. Does Java use "Pass by value" or "Pass by reference”?

A. Java uses "Pass by value". For primitive variables it just passes the value. For objects it passes the value of the reference.

int x =10;
int y=x;
y=20;
System.out.println(x); x--> 10

String a="aaa";

String b=a;
b="bbb";
System.out.println(a); a--> bbb

Integer q=10;

Integer r=q;
r=20;
System.out.println(q); q--> 10 (Wrappers are treated as primitives)

ColumnItem aaa= new ColumnItem ("aaa");

ColumnItem bbb= new ColumnItem("ccc");
bbb=aaa;
bbb.name="bbb";
System.out.println(aaa.name); aaa.name --> bbb