Tuesday, January 31, 2012

Introduction

JMock is the famous library which can be used for working with Mock Objects.
(Please check www.MockObjects.com to know more about Mock Objects.) . How ever you might be excited to know that Mock Objects are not just Stubs!! They give a different approach to unit testing.
So finally testing is also becoming as interesting as Coding.
In simple words we can say that a mock object is something which can be used for testing the behavior of other objects. It will mimic the behavior of an actual class / interface.
A Mock object can also observe how other objects uses its methods and compare with the expected behavior. (I will explain this in detail with code sample.)

This means that we can test and verify how our class uses the available environment. 
Let's assume you are developing a Customer class which has to interact with a BookShopclass. But unfortunately BookShop class your friend is developing and as usual it is not available yet. So naturally we will decide to use a Mock Object of BookShop instead of an actual instance. 
Customer has function doTransaction().
BookShop has methods pay(Money) , Book getBook()
Using JMock we will be able to specify that getBook() is always called only after pay().
So if anywhere in our doTransaction method if getBook is called with out pay() it will result in an error with bright red colour while testing it. 
This way we can ensure that our class uses the available interface in the desired way.
In a TestDrivenDevelopment environment this means that interface problems can be found even before the actual coding of it starts.
JMock makes our life easier by creating mock objects dynamically and providing features to specify expectations (How it should behave, etc).


Download Link

The JMock jar/zip can be downloaded from www.JMock.org
This can be added as external jar file in your Eclipse project.

Using JMock

Here comes the interesting part!
Lets develop as class called DispFile , which is a highly useful class for displaying a given file in console.
DispFile class uses the IFileHandler interface for the file operations .
Code for IFileHandler

public interface IFileHandler {   public void open(String filename) ;   public void close() ;   public String read() ;    } 

Code for DispFile 
public class DispFile {     public DispFile()  {     }    
     /**      * Business method to display the given file line by line      */     public boolean display(String filename)  {         
  Boolean status = true;         
  try   {             
   IFileHandler fileIntf = new FileHandler();             
   fileIntf.open(filename);             
   String line = null;             
   while ((line = fileIntf.read()) != null)    {                 
    System.out.println(line);             
   }            
   fileIntf.close();         } catch (Exception e)    {             
  Status = false;         
 }        
 return status;     } } 

 Here the line "new FileHandler" is the problem! We know the actual implementation is not yet available. So we have to use a MockObject for IFileHandler instead of an actual instance.  We must change the class to make it testable . The changes are minimal and it is a low price to pay for getting the testability with Mock Objects. This refactoring also makes the design cleaner.  The modified code is given below. 


public class DispFile {   
... /** Business method to display the given file line by line */   
public boolean display(String filename) {    
Boolean status = true; 
Try {     
IFileHandler fileIntf = getFileHandler();     
 ....       
}catch (Exception e) { 
Status = false 
}     
return status;  
 }   
/**   Its true that this method seems nonsense, but it is very important forUnit testing with Mock Object technology. */ 
protected IFileHandler getFileHandler() {  
return new FileHandler(); 
}    
} 

Code for Test Class 
package chkJMock;  
import junit.framework.TestCase;  
import org.jmock.*;  
public class DispFileTest extends MockObjectTestCase {   
/ *    * Test method for 'chkJMock. DispFile.display(fileName)'    */   
public void testDisplay() { ....   }  
} 

We will check the code             required in testDisplay method in detail. 


//set up the Mock Object .
//First we have to set up the context             in which our test will execute.
//We have to create a DispFile to test. We             have to create a mock IFileHandler that       
//should receive the message. We then             register the mock  IFileHandler with the DispFile.
Mock mockFileHandler = mock(IFileHandler.class); 
final IFileHandler intf = (IFileHandler) mockFileHandler.proxy();     
DispFile df = new DispFile() {      
protected IFileHandler getFileHandler() {        
// I hope now the use of silly looking getFileHandler method is clear.          
return intf;
// expectations     
// Here we specify how DispFile class is expected to use the IFileHandler interface.      
//     
// The method open should be called only once with the argument file (String            // containing name of the file to display).     
String file = "E:\\@Com XML CorbaTask.xml";     
mockFileInterface.expects(once()).method("open").with(eq(file));         
//     
// The method close should be called only once and it must be called after the method       
// open . (Unless you want to close a file which is not yet opened! ).     
mockFileInterface.expects(once()).method("close").after("open");      
// The method read should be called one or more times (we are reading lines in a loop.)     
// It should return a null string when it is invoked.     
mockFileInterface.expects(atLeastOnce()).method("read").withNoArguments()     .will(returnValue(null));         
// execute     
// Call the business method we were waiting for     
boolean status;     
status = lf.list(file);     
assertTrue("Error displaying file : " + file, status);  
This when executed ensures that the methods in the interface (Mock object ) are invoked in correct order and in specified way. If anything is violated (e.g- if close is called without calling open , open called multiple times ) , it will result in test error.  

Note :

To mock concrete class jmock-cglib extension and cglib jar should be added to the eclipse project. Testcase should derive from cglib.MockObjectTestCase.
Eg:-          
Mock mockTaskDetailsClient = mock(TaskDetailsClient.class,"mockTaskDetailsClient");  
final TaskDetailsClient taskDetailsClient = (TaskDetailsClient)mockTaskDetailsClient.proxy() ;   
ctr with args. mock(TaskDetailsClient.class,"mockTaskDetailsClient", class[],Object[]); 
There are many tools/ services available now which will help in generating unit test for the existing legacy code base. One such service is www.UnitTestFactory.com
 

Tuesday, July 12, 2011


The top 7 reasons to love JBoss AS7:
(taken from JBoss AS7 webinar)

1) Blazing fast start-up time - up to 10X faster!

2) Java EE 6 - leading the pack. again.

3) Very lightweight - exceptionally small footprint and aggressive memory management mean you can run it practically everywhere.

4) Modular core - delivers true application isolation.

5) Elegant management - simplified console and APIs.

6) Domain management - manage servers as groups.

7) Testable by design - simplified in-container testing via the Arquillian project speeds development.

I hope some body from WAS team is also reading these data :)


Tuesday, March 15, 2011

Hacking Tool for Dummies - FireSheep


You might have already heard about FireSheep - an interesting FireFox extension.

It can be used to intercept unencrypted cookies from websites by using Packet Sniffing.
In plain english - if you are accessing sites like Facebook, Twitter in a public Wifi , a person using FireSheep extension can find out what you are doing and may be even impersonate you as the FireSheep user may get your login credentials.

It is developed by Eric Butler and currently available for Mac OS X and Windows.
More details can be found here http://codebutler.com/firesheep

Tuesday, February 1, 2011

Another tool from Google - AppInventor, I'm loving it.


Hope you guys heard about Google App Inventor.
It is tool for developing Android applications , all you need is browser (and internet connection).

To use the tool you need to register with Google.

There are mainly three parts to the App Inventor

1. Designer Part - This is the main application which will open in the browser window.
Here we can drag and drop different components (e.g.- buttons, images, media etc) to design our own application.

2. Blocks Editor - This window can be opened from the Designer window. Here we will be mentioning what are the expected functionality of the different components we added in the designer part. For example - what should happen when the button is clicked.
If the intention is to play a music file when the button is clicked , then we will be dragging and connecting different blocks like button.onClick mediaFile.play

3. Simulator - what fun it is if we can not see our world class application in action. Simulator is for that. It can be opened through the blocks editor. What ever changes we are making in the Designer and Blocks editor will be visible in the simulator.

There are couple of tutorials in Google to get started with App Inventor.
I had developed a paint program with out writing a single line of code :)

But do not get all excited, AppInventor is still in Beta state. There are many functionalities missing. I was really surprised at the long list of missing things. For example - there is no way to add menu items. How can Google miss out such basic features? (even if it is Beta version).

Important Links



Note that instead of using simulator you can also connect your mobile. But I would recommend to use the simulator and once the basic application is ready install it in the phone.

The different steps to install application (apk file) in the phone are

1. From the AppInventor, package the application in the computer.

2. In phone go to settings and enable installation from unknown source.

3. Connect the phone to computer as USB Mass storage.

4. Copy the apk file to phone.

5. Phone should have a file manager application. If you are not having one, download a file manager application from Android market (for example - Astro).

6. After this click on the copied apk file in the phone and select the option Open with TaskManager, this will install the application.




Sunday, December 20, 2009

Real Time Web Application Development Challenges and HTML 5


In the traditional web architecture the reliable message flow between the server and the browser is a problem , as the server is not only forwarding the message but also most of the other work like translating the messages. This might result in Server becoming non scalable.

There were many attempts to simulate two way communication initiated by the server towards the client. One of the most notable approach is Comet.

Comet uses a technique referred as hanging GET or pending POST. In this the completion of an HTTP response is delayed until the server has something to send. This is generally implemented in JavaScript.

But there are some problems with this approach -
-Resource consumption is high as many connections are opened and closed.
-Setup and teardown of connections will consume more resources if secure connections are used.

HTML 5 may be the answer to these issues.

This provides many enhancements to the browsers and will redefine how internet communicates. The communication section of HTML 5 specification defines WebSockets and ServerSentEvents. These features will enable two way communication a reality for browsers. This will change the way in which real time web applications are created.

The main features are

  1. Web Sockets : Usually most of what is transmitted in web will be protocol information and padding. Web Sockets establishes a true two-way connection between server and the browser. This is essentially a pure TCP socket through which any application data can flow in either direction. This is more efficient than traditional HTTP requests as the non payload information is not required.
  2. Server sent Events : Two-way real time communication pattern common in web today is not taken into account in traditional HTTP. Through Sever Sent Events, a server can initiate the transmission of data. This is a standard describing how servers can initiate transmission of data to client once the initial connection with client is established.
  3. Cross Document Messaging : This provides a system in which different documents are allowed to securely communicate across different origins. This will allow an application to communicate with server over many different channels.
  4. Cross Origin resource Sharing : This will allow browsers to do site aggregation. Result may be better performance.







Monday, December 14, 2009

Java EE 6 Features

Lets look at the new sexy Java EE6 features

EJB Lite

EJB Lite is coming from the fact that- most of the ejb applications simply use features like persistence management, declarative transaction, stateless session beans etc.

EJB Lite will allow simple , lightweight implementations. This will also reduce the learning curve required (It might be just learning a handful of annotations). Very soon there may be Java EE application servers which implement EJB Lite instead of the complete Ejb3.1 spec.

Some of the features in the EJB Lite are
  1. Stateless, State full, Singleton session beans
  2. Interceptors
  3. Declarative Security
  4. Declarative Transactions etc
EJB Lite does not have the following features
  1. Message driven beans
  2. Remote interfaces
  3. Asynchronous invocation
  4. Corba interoperability etc.

Managed Beans 1.0

This is simply a POJO which is treated as a managed component by the container.
It can make use of some of the predefined Java EE features like lifecycle management and injection.

  1. @Resource
  2. @PostConstruct
  3. @PreDestroy etc

More Later...

Sunday, December 6, 2009

Project COIN

Project coin is aiming to find out the small language changes that should be added to the JDK.
Around 70 proposals were submitted in the period of Feb-27, 2009 to Mar-30, 2009 and discussed in coin developer forum.

Out of these proposals 5 or so are selected for including in Jdk7.

Some of the accepted proposals are -

1. Using Strings in switch
- Ability to switch on string values

2. Automatic resource management
- Having try like statement to declare one or more Resources. Scope of the resource is limited by that of the statement. When the statement completes normally or abruptly , all the resources are closed automatically.

3. Improved Type Inference for Generic Instance Creation
- When the full parameterized type is obvious from the context, then the parameterized type of the constructor could be replaced with empty set of type parameters.

4. Simplified Varargs method invocation.
- Reduces the total number of warnings reported to and suppressed by programmers.

5. Language support for JSR 292

Some of the proposals which are considered but not accepted are



This project is sponsored by The Compiler Group