Tuesday, April 17, 2012

Selenium remote control & Selenium Client API Introduction


Selenium remote control is a server implemented in Java, which accepts commands via http and perform requested operation in requested browser.

Selenium Client API is a framework developed to encapsulate the command implementation of the operations, we need might want to perform on browser via selenium remote control. Selenium Client API have been developed in multiple languages like java and .net.

Being a java programmer, here I will give examples using java language (wherever necessary)

The combination of Selenium remote control & Selenium client API is useful in following scenarios –
  1. Performing Automation testing of web based application.
  2. Performing some automated operation on the website and retrieve the result

Selenium Remote control and Selenium Client API frame work implements client sever model. Selenium remote control works as server and we implement the client to perform operations, using Selenium Client API.

In high level, we follow the following steps to use it –
  1. Start selenium remote control server
  2. Execute client possibly a java program to fire the commands and perform the operation
Details of the way to perform these operations is as mentioned below –
Starting the selenium remote control server –
Selenium remote control server can be started in two ways –
  1. Starting from command line as stand alone application – We can use the following command to start the selenium rc server.

    java -jar selenium-server.jar -trustAllSSLcertificates -multiWindow

    By default the server starts listening on port no 4444. If this port is not available to connected, You will get connection reset error while trying to connect from client. In this case, you can use another available port with below command line -

    java -jar selenium-server.jar -trustAllSSLcertificates -multiWindow -port 8080

    selenium-server.jar can downloaded from the following url - 
    http://selenium.googlecode.com/files/selenium-remote-control-1.0.3.zip

  2. Starting from with in the application – We can include the jar in the application and start the server from using below sample code -

    SeleniumServer server = new SeleniumServer ();
    server.start();
    --------
    server.stop();

    By default it will listen at  port 4444 but we can reset it if needed before starting the server.
Starting selenium client code executionWe can use below section of code to
develop the selenium client code to perform operation on the respective site - 
 Selenium selenium = new DefaultSelenium( String seleniumServerHost, int seleniumServerPort,  
                      String browserType,  
                      String baseURL);  
 selenium.open ("http://www.somesite.com/somePage.html");  
 selenium.stop ();  

Demo -
Below is sample display of code of combination of selenium remote control server and selenium client in execution.

It performs below operations -
1- Open the browser
2- Type the url & go to site
3- Put the pin in site & click on go
4- Count the number of locations obtained
5- Retrieves pre-defined number of locations
6- Save them in a file.



Note  - If video looks to be blurred, kindly choose 720p (HD) quality option in the embedded player to get fine quality picture.

We can easily integration selenium in the project using below mentioned maven dependencies.

    <dependency>
      <groupId>org.seleniumhq.selenium</groupId>
      <artifactId>selenium-java</artifactId>
      <version>2.21.0</version>
    </dependency>
    <dependency>
      <groupId>org.seleniumhq.selenium.server</groupId>
      <artifactId>selenium-server</artifactId>
      <version>2.21.0</version>
    </dependency>

These dependencies exist on below mentioned repository -
          http://repo1.maven.org/maven2/org/seleniumhq/selenium

Debugging – If selenium client faces any issues while connecting, we can test the proper functioning of each component independently. We can test the proper setup of server by running it using interactive mode. The steps to test are as mentioned below - 
  1. Run Selenium server in interactive mode. To do this run the command:
            java -jar selenium-server.jar -interactive -multiWindow
    Once the server starts in the interactive mode you will see a line that says:
    Entering interactive mode ... type selenium commands here

  2.  Now you can start a new selenium browser session using the command:
    cmd=getNewBrowserSession&1=*firefox&2=http://www.google.com
    This should open a new blank Firefox browser window.

  3. Now run the following command:
    cmd=open&1=http://www.google.com
    If the browser starts and you see Google’s home page in it, your basic setup seems to be fine.

  4. Type quit to exit the interactive mode
     
Refenreces - .
http://seleniumhq.org/download/maven.html
http://www.bitmotif.com/selenium/selenium-remote-control-for-java-a-tutorial/
http://www.qaautomation.net/?p=17
http://seleniumhq.org/projects/
 

Thursday, April 5, 2012

Spring Batch – Introduction


Java enterprise edition had been developed to provide the platform to fulfill all enterprise requirements. Multiple open source projects were developed to fulfill various kinds of needs but a standard framework for Batch processing was still missing.

Each organization use to have their own back office processing where most of the activities needs to be performed without any manual intervention. It might range from performing some cleanup activity to processing millions rows of data.

As there was no standard java framework to handle batch processing each organization use to invest huge amount of money and time in developing in house solutions. Spring source tapped this opportunity and developed a standard java batch framework, which is open source and available free of cost.

In the mean time we got another framework called Java Batch Job Framework. But Spring Batch framework got more popularity because of its close integration with Spring Core. Spring core brings inversion of control capability to Spring batch framework.

Application with spring batch use to have three tier architecture, which is as mentioned below –
Top Tier - This is our application which defines what needs to be done and in what sequence
Middle Tier – This is the layer where we have spring batch APIs. It manages and controls the activities of complete batch operation.
Third Tier – Third tier is the infrastructure to which middle layer interacts to get all the activities performed.

Spring provides two ways to configure our job, which are as mentioned below –

Chunk Based Processing –
As most of the batch processing use to have a specific pattern, which is retrieving the data, performing some operations on it and then writing the processed data, spring batch provides specific configuration and transaction management to these tasks.

While configuring these, we implement or use existing reader, processor and writer. Spring manages the transaction of the complete operation on the chunk level. We can configure the chunk size. If any problem occurs, all the operations done the complete chunk will be rolled back.

Tasklet – Tasklet is another type of possible processing is available in Spring Batch. We use this processing, when the task does not fit to the chunk based scenario. Such task can be updating some bulk data in the database.

Spring job provides transaction on the tasklet level. If the complete job consists of five sequential operations and exception occurs at third operation, only the third operation will be rolled back, not the complete job.

Al the job configuration is written in XML, where we can use IOC to bind the job with possible chunk processors and taksets.

We can execute the job in various ways including the command line execution. If we are using maven, we can prefer maven commend to start execution of the job. Maven will help us avoiding the activity of setting the class path’s required for the job execution. The template command is as mentioned below –
 
mvn exec:java -Dexec.mainClass=org.springframework.batch.core.launch.support.CommandLineJobRunner
-Dexec.args="JobConfigurationXML JobBeanName"

Example -
 
mvn exec:java -Dexec.mainClass=org.springframework.batch.core.launch.support.CommandLineJobRunner
-Dexec.args="simpleJob.xml simpleJob"

Spring job can be easily integrated into the application by including below repository and maven dependency –;
Repository –   
<repository>
    <id>spring-releases</id>
    <name>Spring Maven RELEASE Repository</name>
    <url>http://maven.springframework.org</url>
</repository>  
Dependency – 
<dependency>
  <groupId>org.springframework.batch</groupId>
  <artifactId>spring-batch-core</artifactId>
  <version>2.1.8.RELEASE</version>
</dependency> 
I personally prefer this for batch processing applications because of following reasons –
1.      It provides nice integration with spring core, enabling us to use IOC
2.      It provides ability to include various type of processing in a single job by using chunk based and tasklet configuration.

Monday, April 2, 2012

Unit Testing the private methods in Java


It very common situation, where we create proper encapsulated classes, and then think how to unit test private methods.

We can tackle the situation in the following ways –
1.      Testing from the less restrictive methods available in the class.
2.      Breaking the encapsulation by changing to less restrictive access and test
3.      Test by bypassing Java modifier security in our unit test.

As the first two approaches are self explanatory, I will jump to third approach “Unit test by bypassing the java modifier security in our unit test”.

There is an open source library called JUnitAddons, which provide multiple utilities to help us in unit testing the component. One of these is PrivateAceessor.

PrivateAccessor is a class, which provides us the necessary functions to bypass the java security in our unit tests. We can use it’s invoke method to access the protected, default or private methods, which might not be accessible without bypassing java modifier security.

Its syntaxes are as mentioned below –

  1. PrivateAccessor.invoke (Object, String, Class [], Object [])
  2. PrivateAccessor.invoke (Class, String, Class [], Object [])

Sample Use
1.      PrivateAccessor.invoke (ObjectContanigFunction, “methodName”, parameterTypeArray, parameters)
2.      PrivateAccessor.invoke (ClassContanigFunction, “methodName”, parameterTypeArray, parameters)

We can easily use JUnitAddons by adding below mentioned maven dependency in our project.
        <dependency>
                 <artifactId>junit-addons</artifactId>
                 <groupId>junit-addons</groupId>
                   <version>1.4</version>
        </dependency>

Sample code example is as mentioned below -

PrivateMethodClass - Class having factorial method, which is private

public class PrivateMethodClass {
	private static int getFactorialOf(Integer integerNumber) {
		return integerNumber==0?1:integerNumber * getFactorialOf(integerNumber - 1);
	}
}

PrivateMethodTest - Class testing the factorial method defined in the above 

import junit.framework.TestCase;
import junitx.util.PrivateAccessor;
import org.junit.Test;

public class PrivateMethodTest extends TestCase{

	@Test
	public void test() throws Throwable{
		assertEquals(6, PrivateAccessor.invoke(PrivateMethodClass.class,"getFactorialOf",new Class[] {Integer.class} ,new Object[]{new Integer(3)}));
	}
}

I personally prefer using PrivateAccessor than other two methods mentioned above. Because it provides deep control on testing without breaking encapsulation.